Skip to content

Instantly share code, notes, and snippets.

@narenaryan
Last active May 29, 2024 02:26
Show Gist options
  • Save narenaryan/e6c5065bafc04d1b99071fcd47ab08fd to your computer and use it in GitHub Desktop.
Save narenaryan/e6c5065bafc04d1b99071fcd47ab08fd to your computer and use it in GitHub Desktop.
A go program to configure TLS for server certificate
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"net/http"
"os"
"time"
)
func getCertPool(fileName string) *x509.CertPool {
// Load the server certificate from a file
certBytes, err := os.ReadFile(fileName)
if err != nil {
fmt.Println("Error reading certificate file:", err)
return nil
}
// Decode the PEM-encoded certificate
pemBlock, _ := pem.Decode(certBytes)
if pemBlock == nil {
fmt.Println("Failed to decode PEM block")
return nil
}
// Parse the certificate data
cert, err := x509.ParseCertificate(pemBlock.Bytes)
if err != nil {
fmt.Println("Error parsing certificate:", err)
return nil
}
// Create a certificate pool and add the server certificate to it
pool := x509.NewCertPool()
pool.AddCert(cert)
return pool
}
func main() {
// Create a custom transport with a certificate pool
transport := &http.Transport{
MaxIdleConns: 1,
MaxIdleConnsPerHost: 1,
IdleConnTimeout: 30 * time.Second,
TLSClientConfig: &tls.Config{RootCAs: getCertPool("httpbin.cer")},
}
// Create a client with the custom transport
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
defer client.CloseIdleConnections()
req, err := http.NewRequest("GET", "https://httpbin.org/get", nil)
if err != nil {
fmt.Println(err)
return
}
// Add headers to the request
req.Header.Add("User-Agent", "go-http-client")
req.Header.Add("Content-Type", "application/json")
// Send the request
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(resp.StatusCode)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment