Middleware like functionality, e.g. for login checks?

465 views
Skip to first unread message

Philipp Klose

unread,
Jul 30, 2013, 2:20:14 PM7/30/13
to goril...@googlegroups.com
I am currently evaluating go and gorilla for one of my next projects. (To put it simple: A JSON HTTP API server.)

Gorrilla looks promising and offers most of the functionality I need. There is only one thing I'm not sure of:

I want that every request should only be done if the user is authenticated. Is any way to call a specific function before the routes are handled to test whether the user is logged in? Otherwise this login check must be replicated in every handler function, which could be a little bit annoying.

Philipp

Philipp Klose

unread,
Jul 30, 2013, 2:34:14 PM7/30/13
to goril...@googlegroups.com
My current workaround for this look like this:

func main() {
r := mux.NewRouter()
r.HandleFunc("/", PreHandler(HomeHandler))
// r.HandleFunc("/hello/{name}", PreHandler(HelloHandler))
http.Handle("/", r)
}

func PreHandler(exe func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
f := func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Check login")
exe(w, r)
}
return f
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
}

Kamil Kisiel

unread,
Jul 30, 2013, 2:45:39 PM7/30/13
to goril...@googlegroups.com
That's a pretty standard pattern and how the gorilla/handlers package is generally designed. 

bennAH

unread,
Apr 18, 2014, 11:34:22 PM4/18/14
to goril...@googlegroups.com
Hi,

I have a quick and dirty hack used as a proof of concept to achieve this, that is a slightly different way of achieving this.

It essentially is embedding a mux.Router into a new defined struct:
- the struct allows a list of  paths to be defined as secured urls.
- the ServeHTTP method is then overwritten to perform pre-processing (check if auth for request url required, check for authenticated user, redirect, etc)
- finally, if there is no redirection (url does not require auth, or user is already authenticated) call the ServeHTTP of the mux router

func (a *AuthManager) ServeHTTP(w http.ResponseWriter, req *http.Request) {
session, _ := a.Store.Get(req, a.sessionName)
authPrincipal := session.Values[AUTHENTICATED_PRINCIPAL]

if a.isAuthRequired(req) && authPrincipal == nil {
  // omitted, some pre-processing
}

http.Redirect(w, req, "/", http.StatusFound)
}
a.Router.ServeHTTP(w, req)
}


I had some ideas of using this to create http request filters like functionality and implementing the logic as a filter. So I guess my main question is whether this is a recommended approach and how clean is it?
Reply all
Reply to author
Forward
0 new messages