Skip to content

Instantly share code, notes, and snippets.

@marete
Created November 10, 2012 20:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marete/4052377 to your computer and use it in GitHub Desktop.
Save marete/4052377 to your computer and use it in GitHub Desktop.
In Go/Golang, authenticate all HTTP connections in one place (No code duplication)
package main
import "net/http"
import "io"
import "runtime"
import "log"
type authHandler func(http.ResponseWriter, *http.Request)
func allowed(r *http.Request) bool {
return true
}
func (f authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !allowed(r) {
w.WriteHeader(http.StatusForbidden)
return
}
f(w, r)
}
func serveHello(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello World!\n")
}
func serveBye(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Bye World!\n")
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU() * 2)
http.Handle("/hello", authHandler(serveHello))
http.Handle("/bye", authHandler(serveBye))
log.Fatal(http.ListenAndServe(":9000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment