Last active
April 20, 2019 04:46
-
-
Save ldclakmal/334d4a7765da54fe3f9d9988168ff01f to your computer and use it in GitHub Desktop.
Go HTTP/2 Client
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 ( | |
"bytes" | |
"crypto/tls" | |
"crypto/x509" | |
"fmt" | |
"golang.org/x/net/http2" | |
"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 = &http2.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