Skip to content

Instantly share code, notes, and snippets.

@raninho
Created November 30, 2018 21:17
Show Gist options
  • Save raninho/8bfd9e5277948551825e38aa16223c21 to your computer and use it in GitHub Desktop.
Save raninho/8bfd9e5277948551825e38aa16223c21 to your computer and use it in GitHub Desktop.
Request With Two Way SSL With Golang
package main
import (
"bytes"
"crypto/tls"
"encoding/base64"
"io"
"io/ioutil"
"log"
"net/http"
"time"
)
func checkBody(body *bytes.Buffer) io.Reader {
if body == nil {
return nil
}
return body
}
//DoRequestWithTwoWaySSL is In Two-Way SSL authentication, the client and server need to authenticate and validate each others identities.
func DoRequestWithTwoWaySSL(timeOut time.Duration, certPEM string, keyPEM string, basicUsername string, basicPassword string, method string, url string, header http.Header, body *bytes.Buffer) ([]byte, int, error) {
c, err := tls.X509KeyPair([]byte(certPEM), []byte(keyPEM))
if err != nil {
log.Fatal("Unable to load cert", err)
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{c},
}
tlsConfig.BuildNameToCertificate()
if timeOut == 0 {
timeOut = 10 * time.Second
}
var client = &http.Client{
Timeout: timeOut,
Transport: &http.Transport{TLSClientConfig: tlsConfig},
}
req, err := http.NewRequest(method, url, checkBody(body))
if err != nil {
return nil, 0, err
}
if header != nil {
req.Header = header
} else {
auth := base64.StdEncoding.EncodeToString([]byte(basicUsername + ":" + basicPassword))
header := http.Header{}
header.Add("Accept", "application/json")
header.Add("Content-Type", "application/json")
header.Add("Authorization", "Basic "+auth)
req.Header = header
}
resp, err := client.Do(req)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, 0, err
}
return content, resp.StatusCode, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment