Created
November 10, 2012 20:24
-
-
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)
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 "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