TLS certificates¶
Interacting with services that require TLS certificates is a common issue when working with containers. You can create one or more on-the-fly certificates in order to communicate with your services.
Testcontainers for Go uses a library to generate certificates on-the-fly. This library is called tlscert.
Examples¶
In the following example we are going to start an HTTP server with a self-signed certificate. It exposes one single handler that will return a simple message when accessed. The example will also create a client that will connect to the server using the generated certificate, demonstrating how to use the generated certificate to communicate with a service.
caCert := tlscert.SelfSignedFromRequest(tlscert.Request{
Name: "ca",
SubjectCommonName: "Cockroach Test CA",
Host: "localhost,127.0.0.1",
IsCA: true,
ValidFor: time.Hour,
})
if caCert == nil {
return nil, errors.New("failed to generate CA certificate")
}
nodeCert := tlscert.SelfSignedFromRequest(tlscert.Request{
Name: "node",
SubjectCommonName: "node",
Host: "localhost,127.0.0.1",
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
ValidFor: time.Hour,
Parent: caCert, // using the CA certificate as parent
})
if nodeCert == nil {
return nil, errors.New("failed to generate node certificate")
}