Created
June 29, 2016 14:51
-
-
Save gophertron/57c3cad7bdb2c18fe1b038c58beb6fca to your computer and use it in GitHub Desktop.
negroni, gorilla and middleware
This file contains hidden or 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 ( | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/codegangsta/negroni" | |
"github.com/gorilla/mux" | |
) | |
type Handler func(w http.ResponseWriter, r *http.Request) | |
func main() { | |
r := mux.NewRouter().StrictSlash(false) | |
r.HandleFunc("/", GenericHandler("Home Page")) | |
r.HandleFunc("/page1", GenericHandler("Page 1")) | |
r.HandleFunc("/page2", GenericHandler("Page 2")) | |
api := r.PathPrefix("/auth").Subrouter() | |
api.HandleFunc("/login", GenericHandler("login")) | |
api.HandleFunc("/logout", GenericHandler("logout")) | |
mux1 := http.NewServeMux() | |
mux1.Handle("/", negroni.New( | |
negroni.HandlerFunc(AuthMiddleware), | |
negroni.Wrap(r), | |
)) | |
mux1.Handle("/auth/", negroni.New( | |
negroni.HandlerFunc(LoggingMiddleware), | |
negroni.Wrap(r), | |
)) | |
n := negroni.Classic() | |
n.UseHandler(mux1) | |
http.ListenAndServe(":3000", n) | |
} | |
func GenericHandler(s string) Handler { | |
return func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, s) | |
} | |
} | |
func AuthMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { | |
log.Println("AuthMiddleware") | |
next(w, r) | |
} | |
func LoggingMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { | |
log.Println("LoggingMiddleware") | |
next(w, r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment