Skip to content

Instantly share code, notes, and snippets.

@andreadipersio
Created November 15, 2013 18:37
Show Gist options
  • Save andreadipersio/7489388 to your computer and use it in GitHub Desktop.
Save andreadipersio/7489388 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"flag"
"net/http"
)
var (
port int
)
func authHandler(w http.ResponseWriter, r *http.Request) {
// http://golang.org/pkg/net/http/#Cookie
cookie := &http.Cookie{
Name: "token",
Value: "foobar",
}
http.SetCookie(w, cookie)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
if c, err := r.Cookie("token"); err != nil || c.Value != "foobar" {
http.Error(w, "Ah ah ah, you didn't say the magic word", 401)
return
}
fmt.Fprintf(w, "Access granted")
}
func init() {
flag.IntVar(&port, "port", 8080, "HTTP Server Port")
flag.Parse()
}
func main() {
httpAddr := fmt.Sprintf(":%v", port)
log.Printf("Listening to %v", httpAddr)
// visit /auth to create a cookie
http.HandleFunc("/auth", authHandler)
// visit / to check cookie
http.HandleFunc("/", rootHandler)
log.Fatal(http.ListenAndServe(httpAddr, nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment