To establish a secure HTTPS client connection in Go, you can use the net/http
package in combination with the crypto/tls
package. Here's an example of how to do it:
import (
"crypto/tls"
"net/http"
)
http.Client
with a custom Transport
:func createHTTPSClient() *http.Client {
// Create a custom transport with TLS configuration
transport := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true, // Skip server certificate verification (not recommended in production)
},
}
// Create a new client with the custom transport
client := &http.Client{Transport: transport}
return client
}
func sendHTTPRequest() {
// Create the HTTPS client
client := createHTTPSClient()
// Send a GET request to an HTTPS URL
response, err := client.Get("https://example.com")
if err != nil {
// Handle the error
fmt.Println("Error: ", err)
return
}
// Read the response body
body, err := ioutil.ReadAll(response.Body)
if err != nil {
// Handle the error
fmt.Println("Error: ", err)
return
}
// Close the response body
defer response.Body.Close()
// Print the response body
fmt.Println(string(body))
}
sendHTTPRequest
function to establish a secure HTTPS connection and receive the response.Note: In the above example, InsecureSkipVerify
is set to true to skip server certificate verification. This is not recommended in production environments, as it exposes your application to security risks. Ideally, you should configure proper certificate verification by loading trusted CA certificates into the TLSConfig
supplied to the transport.