Home >Backend Development >Golang >How to Make HTTPS Requests with Self-Signed Certificates in Go?
How to Send an HTTPs Request with a Certificate in Go
When making HTTPS requests to a server running on a different port, it's common to encounter certificate-related errors. This occurs because the server's certificate is signed by an unknown authority, and the default HTTP client does not trust self-signed certificates.
To resolve this issue, we need to manually verify the server's certificate using the appropriate CA certificate. Here's a step-by-step guide on how to accomplish this in Go:
Obtain the CA Certificate:
Create a Certificate Pool:
Configure TLS Options:
Create an HTTP Client with Custom Transport:
Example Code:
package main import ( "crypto/tls" "crypto/x509" "io/ioutil" "log" "net/http" ) func main() { // Read the CA certificate from file caCert, err := ioutil.ReadFile("rootCA.crt") if err != nil { log.Fatal(err) } // Create a certificate pool and add the CA cert caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) // Configure TLS options tlsConfig := &tls.Config{ RootCAs: caCertPool, } // Create an HTTP client with custom transport client := &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, } // Send an HTTPs request _, err = client.Get("https://secure.domain.com") if err != nil { panic(err) } }
Note:
If you don't have a CA certificate, you can create your own. Refer to external resources for instructions on how to generate self-signed certificates.
The above is the detailed content of How to Make HTTPS Requests with Self-Signed Certificates in Go?. For more information, please follow other related articles on the PHP Chinese website!