Last active
January 2, 2016 19:49
-
-
Save ejcx/1756e3a179e04b6b37f1 to your computer and use it in GitHub Desktop.
Go Authentication Design Patterns
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 ( | |
"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 main() { | |
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 { | |
if _, ok := session.Values["loggedin"]; !ok { | |
w.WriteHeader(http.StatusUnauthorized) | |
return | |
} | |
handleFunc, _ := authMux.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