Last active
August 29, 2015 13:56
-
-
Save rolaveric/9169716 to your computer and use it in GitHub Desktop.
A classic martini web server that demonstrates using middleware and route handlers to keep authentication and authorization code DRY.
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 ( | |
"github.com/go-martini/martini" | |
) | |
func main() { | |
// Create a new Martini server | |
m := martini.New() | |
// Add middleware that logs incoming requests, and how long they take to handle | |
m.Use(martini.Logger()) | |
// Add middleware which recovers from any panics, preventing the whole server from | |
// crashing over one bad request. | |
m.Use(martini.Recovery()) | |
// Creates a new martini router and sets it as the handler that runs after all middleware | |
r := martini.NewRouter() | |
m.Action(r.Handle) | |
// Everything so far could be replaced by one line: m := martini.Classic() | |
// Register middleware which authenticates the client | |
m.Use(Authentication) | |
// Public route | |
r.Get("/", func() string { | |
return "Hello World!" | |
}) | |
// Private route | |
r.Get("/secret", Authorization("secret access"), func() string { | |
return "Hello Secret Agent!" | |
}) | |
// Start the server | |
m.Run() | |
} | |
// Type which, through reflection, Martini uses to dependency inject the user | |
// found by the Authentication middleware | |
type User interface{} | |
// Identifies the user for the request | |
func Authentication(c martini.Context) { | |
// ... | |
c.MapTo(user, (*User)(nil)) | |
} | |
// Creates a handler function for checking that the user has specific access | |
func Authorization(access string) func() { | |
return func(u User) { | |
// ... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment