Created
February 21, 2014 05:13
-
-
Save nimolix/9129172 to your computer and use it in GitHub Desktop.
Two-way SSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import( | |
"crypto/rand" | |
"crypto/tls" | |
"io/ioutil" | |
"log" | |
"net" | |
"net/http" | |
"compress/gzip" | |
"strings" | |
"time" | |
) | |
func main() { | |
cert, err := tls.LoadX509KeyPair("certificate.pem", "key.pem") | |
if err != nil { | |
log.Fatalf("Failed to load X509 key pair: %s", err) | |
} | |
ssl: = &tls.Config{ | |
Certificates: []tls.Certificate{cert}, | |
InsecureSkipVerify: true, | |
} | |
ssl.Rand = rand.Reader | |
client: = &http.Client{ | |
Transport: &http.Transport{ | |
Dial: func(network, addr string)(net.Conn, error) { | |
return net.DialTimeout(network, addr, time.Duration(time.Second*3)) | |
}, | |
TLSClientConfig: ssl, | |
}, | |
} | |
requestBody := strings.NewReader("{}"); | |
req, _ := http.NewRequest("POST", "https://www....", requestBody) | |
// some custom headers | |
req.Header.Add("Content-Type", "application/json") | |
req.Header.Add("Accept", "application/json") | |
response, err := client.Do(req) | |
if err != nil { | |
log.Fatalf("Failed to make request: %s", err) | |
} | |
if response.StatusCode != 200 { | |
log.Fatalf("FAILED: Got status: " + response.Status) | |
} | |
defer response.Body.Close() | |
// in case response is gziped, run that through the gzip reader to de decompress | |
if strings.Contains(response.Header.Get("Content-Encoding"), "gzip") { | |
response.Body, err = gzip.NewReader(response.Body) | |
if err != nil { | |
return | |
} | |
} | |
data, err := ioutil.ReadAll(response.Body) | |
if err != nil { | |
log.Fatalf("Could not read response body: %s", err) | |
} | |
log.Println(string(data)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment