Skip to content

Instantly share code, notes, and snippets.

@abdollar
Forked from chriswhitcombe/gist:2e0450294f370f493aec
Last active September 2, 2015 20:36
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 abdollar/fccae96bb22c12568d9d to your computer and use it in GitHub Desktop.
Save abdollar/fccae96bb22c12568d9d to your computer and use it in GitHub Desktop.
Secure server in go (TLS Mutual Auth)
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