Created
June 25, 2015 20:33
-
-
Save chriswhitcombe/2e0450294f370f493aec to your computer and use it in GitHub Desktop.
Secure server in go (TLS Mutual Auth)
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/tls" | |
"crypto/x509" | |
"io" | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
func HelloServer(w http.ResponseWriter, req *http.Request) { | |
io.WriteString(w, "hello, world!\n") | |
} | |
func main() { | |
http.HandleFunc("/hello", HelloServer) | |
caCert, err := ioutil.ReadFile("../secure-client/selfsigned.crt") | |
if err != nil { | |
log.Fatal(err) | |
} | |
caCertPool := x509.NewCertPool() | |
caCertPool.AppendCertsFromPEM(caCert) | |
// Setup HTTPS client | |
tlsConfig := &tls.Config{ | |
ClientCAs: caCertPool, | |
// NoClientCert | |
// RequestClientCert | |
// RequireAnyClientCert | |
// VerifyClientCertIfGiven | |
// RequireAndVerifyClientCert | |
ClientAuth: tls.RequireAndVerifyClientCert, | |
} | |
tlsConfig.BuildNameToCertificate() | |
server := &http.Server{ | |
Addr: ":8080", | |
TLSConfig: tlsConfig, | |
} | |
server.ListenAndServeTLS("selfsigned.crt", "selfsigned.key") //private cert | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment