Skip to content

Instantly share code, notes, and snippets.

@groks
Forked from imjasonh/mustlogin.go
Last active December 10, 2015 04:28
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 groks/4381796 to your computer and use it in GitHub Desktop.
Save groks/4381796 to your computer and use it in GitHub Desktop.
package mustlogin
import (
"appengine"
"appengine/user"
"fmt"
"net/http"
)
func init() {
http.HandleFunc("/1", MustLogin(loggedIn))
http.Handle("/2", MustLoginHandler{loggedIn})
http.Handle("/3", MustLogin3(loggedIn))
}
func loggedIn(w http.ResponseWriter, r *http.Request, u user.User) {
fmt.Fprintln(w, "<html><body>")
fmt.Fprintln(w, u.Email)
url, _ := user.LogoutURL(appengine.NewContext(r), r.URL.String())
fmt.Fprintln(w, "<br /><a href=\""+url+"\">Log out</a>")
fmt.Fprintln(w, "</body></html>")
}
// Option 1: Use a closure
func MustLogin(done func(http.ResponseWriter, *http.Request, user.User)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
if u := user.Current(c); u == nil {
url, _ := user.LoginURL(c, r.URL.String())
http.Redirect(w, r, url, http.StatusSeeOther)
} else {
done(w, r, *u)
}
}
}
// Option 2: Use a http.Handler
type MustLoginHandler struct {
inner func(http.ResponseWriter, *http.Request, user.User)
}
func (h MustLoginHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
if u := user.Current(c); u == nil {
url, _ := user.LoginURL(c, r.URL.String())
http.Redirect(w, r, url, http.StatusSeeOther)
} else {
h.inner(w, r, *u)
}
}
// Option 3: An http.Handler does not have to be a struct...
type MustLoginHandler3 func(http.ResponseWriter, *http.Request, u user.User)
func (f MustLoginHandler3) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
if u := user.Current(c); u == nil {
url, _ := user.LoginURL(c, r.URL.String())
http.Redirect(w, r, url, http.StatusSeeOther)
} else {
f(w, r, *u)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment