Skip to content

Instantly share code, notes, and snippets.

@ldclakmal
Last active April 20, 2019 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ldclakmal/93832a9fb0539a26df7f690b1b8b7982 to your computer and use it in GitHub Desktop.
Save ldclakmal/93832a9fb0539a26df7f690b1b8b7982 to your computer and use it in GitHub Desktop.
Go HTTP Client
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
client := &http.Client{}
// Create a pool with the server certificate since it is not signed
// by a known CA
caCert, err := ioutil.ReadFile("./cert/server.crt")
if err != nil {
log.Fatalf("Reading server certificate: %s", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
// Create TLS configuration with the certificate of the server
tlsConfig := &tls.Config{
RootCAs: caCertPool,
}
// Use the proper transport in the client
client.Transport = &http.Transport{
TLSClientConfig: tlsConfig,
}
// Perform the request
resp, err := client.Post("https://localhost:9191/hello/sayHello", "text/plain", bytes.NewBufferString("Hello Go!"))
if err != nil {
log.Fatalf("Failed get: %s", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Failed reading response body: %s", err)
}
fmt.Printf("Got response %d: %s %s", resp.StatusCode, resp.Proto, string(body))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment