Skip to content

Instantly share code, notes, and snippets.

@ejcx
Last active January 2, 2016 23:47
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 ejcx/4b24c23fbe39ff790419 to your computer and use it in GitHub Desktop.
Save ejcx/4b24c23fbe39ff790419 to your computer and use it in GitHub Desktop.
Go Authentication Design Pattern
package main
import (
"log"
"net/http"
"os"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION-INTEGRITY")))
func authenticated(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Why yes, you are logged in!"))
}
func unauthenticated(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("You are not authenticated"))
}
func main() {
unauthMux := http.NewServeMux()
unauthMux.HandleFunc("/authenticated", unauthenticated)
authMux := http.NewServeMux()
authMux.HandleFunc("/authenticated", authenticated)
apiMux := http.NewServeMux()
apiMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if session, err := store.Get(r, "SESSIONID"); err == nil {
activeMux := unauthMux
if _, ok := session.Values["loggedin"]; ok {
activeMux = authMux
}
handleFunc, _ := activeMux.Handler(r)
handleFunc.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
})
log.Fatal(http.ListenAndServe(":8080", apiMux))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment