Skip to content

Commit

Permalink
feat: support retrieving a TLS config from the certificate
Browse files Browse the repository at this point in the history
  • Loading branch information
mdelapenya committed Apr 11, 2024
1 parent 8b38468 commit d220577
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Therefore, it's possible to issue a self-signed certificate with a custom host n

The `Request` struct also provides a `ParentDir` option that can be used to save the generated certificate to disk as a PEM file.

The `Certificate` struct provides a `Transport` method, which returns a pointer to a `http.Transport` that can be used to perform HTTP requests using the generated certificate.
The `Certificate` struct provides a `Transport` method, which returns a pointer to a `http.Transport` that can be used to perform HTTP requests using the generated certificate; and a `TLSConfig` method, which returns a pointer to a `tls.Config`. The `Transport` method internally uses the `TLSConfig` method.

## Example

Expand Down
20 changes: 16 additions & 4 deletions tlscert.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,26 @@ type Certificate struct {
KeyPath string
}

// Transport returns an http.Transport that uses the certificate as the root CA.
func (c *Certificate) Transport() *http.Transport {
// TLSConfig returns a tls.Config that uses the certificate as the root CA,
// and the certificate for the server's certificate.
func (c *Certificate) TLSConfig() *tls.Config {
caCertPool := x509.NewCertPool()
caCertPool.AddCert(c.Cert)

tlsConfig := &tls.Config{
RootCAs: caCertPool,
tlsCert, err := tls.X509KeyPair(c.Bytes, c.KeyBytes)
if err != nil {
return nil
}

return &tls.Config{
Certificates: []tls.Certificate{tlsCert},
RootCAs: caCertPool,
}
}

// Transport returns an http.Transport that uses the certificate as the root CA.
func (c *Certificate) Transport() *http.Transport {
tlsConfig := c.TLSConfig()

return &http.Transport{
TLSClientConfig: tlsConfig,
Expand Down

0 comments on commit d220577

Please sign in to comment.