Nicolas314

All my geeky stuff ends up here. Mostly Unix-related

Go recipe: HTTPS server

leave a comment »

Go recipe: implement an HTTPS server that requires a client-side certificate for authentication but does not check certificate origin. Any client-side cert will be accepted, the Subject Common Name is printed upon visiting the page. Start the program and point your browser to https://localhost:4443

Generating a server key and cert is left as an exercise for the reader :-)

package main

import (
    "fmt"
    "net/http"
    "crypto/tls"
)

func Hello(w http.ResponseWriter, req * http.Request) {
    w.Header().Set("Content-type", "text/plain")
    fmt.Fprintf(w, "Hello\n")
    client_cert := req.TLS.PeerCertificates[0]
    fmt.Fprintf(w, "You are: %s\n", client_cert.Subject.CommonName)
}

func main() {
    http.HandleFunc("/", Hello)
    t := tls.Config {
            ClientAuth: tls.RequireAnyClientCert,
         }
    s := &http.Server {
            Addr:       ":4443",
            TLSConfig:  &t,
         }
    fmt.Println("Listening on 4443...")
    err := s.ListenAndServeTLS("server.crt", "server.key")
    if err!=nil {
        fmt.Printf("err: %s", err)
    }
}
Advertisements

Written by nicolas314

Tuesday 24 April 2012 at 11:02 pm

Posted in go, programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s