Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Created December 19, 2012 15:12

Revisions

  1. imjasonh revised this gist Dec 19, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion mustlogin.go
    Original file line number Diff line number Diff line change
    @@ -21,7 +21,7 @@ func loggedIn(w http.ResponseWriter, r *http.Request, u user.User) {
    }

    // Option 1: Use a closure
    func MustLogin(done func(http.ResponseWriter, *http.Request, user.User)) func(http.ResponseWriter, *http.Request) {
    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 {
  2. imjasonh revised this gist Dec 19, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion mustlogin.go
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    package mustlogin

    import (
    "appengine"
    "appengine"
    "appengine/user"
    "fmt"
    "net/http"
  3. imjasonh created this gist Dec 19, 2012.
    49 changes: 49 additions & 0 deletions mustlogin.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    package mustlogin

    import (
    "appengine"
    "appengine/user"
    "fmt"
    "net/http"
    )

    func init() {
    http.HandleFunc("/1", MustLogin(loggedIn))
    http.Handle("/2", MustLoginHandler{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)) func(http.ResponseWriter, *http.Request) {
    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)
    }
    }