Created
July 11, 2019 19:59
-
-
Save alinz/6fdeae96255cdcabd468fe9d8d4c75ab to your computer and use it in GitHub Desktop.
Share tls config with server and client in golang
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" | |
"io" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"time" | |
) | |
func main() { | |
// certificate | |
caCert, err := ioutil.ReadFile("./cert/ca.crt") | |
if err != nil { | |
panic(err) | |
} | |
caCertPool := x509.NewCertPool() | |
caCertPool.AppendCertsFromPEM(caCert) | |
cert, err := tls.LoadX509KeyPair("./cert/service.crt", "./cert/service.key") | |
if err != nil { | |
panic(err) | |
} | |
tlsConfig := &tls.Config{ | |
RootCAs: caCertPool, | |
Certificates: []tls.Certificate{cert}, | |
ClientAuth: tls.RequireAndVerifyClientCert, | |
ClientCAs: caCertPool, | |
ServerName: "server", | |
} | |
go func() { | |
server := &http.Server{ | |
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("hello world")) | |
}), | |
} | |
server.TLSConfig = tlsConfig | |
ln, err := tls.Listen("tcp", ":10000", tlsConfig) | |
if err != nil { | |
panic(err) | |
} | |
err = server.Serve(ln) | |
if err != nil { | |
panic(err) | |
} | |
}() | |
time.Sleep(1 * time.Second) | |
client := &http.Client{} | |
client.Transport = &http.Transport{ | |
TLSClientConfig: tlsConfig, | |
} | |
resp, err := client.Get("https://localhost:10000") | |
if err != nil { | |
log.Fatal(err) | |
} | |
var buffer bytes.Buffer | |
io.Copy(&buffer, resp.Body) | |
println(buffer.String()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment