Last active
August 29, 2015 14:10
-
-
Save albertoleal/3ffa6e0b50d65b8f9525 to your computer and use it in GitHub Desktop.
negroni_issue.go
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" | |
"time" | |
"github.com/gorilla/context" | |
"github.com/codegangsta/negroni" | |
"github.com/gorilla/mux" | |
"github.com/stretchr/graceful" | |
) | |
type ApiServer struct { | |
n *negroni.Negroni | |
http.Handler | |
mux *mux.Router | |
muxAuth *mux.Router | |
} | |
func NewApiServer() (*ApiServer, error) { | |
a := &ApiServer{} | |
a.n = negroni.New(negroni.NewRecovery(), | |
negroni.HandlerFunc(errorHandlerMiddleware), | |
//negroni.HandlerFunc(authorizationMiddleware), //Uncomment this to see it working! | |
) | |
a.drawRoutes() | |
return a, nil | |
} | |
func (a *ApiServer) drawRoutes() { | |
a.mux = mux.NewRouter() | |
a.muxAuth = mux.NewRouter() | |
a.mux.HandleFunc("/debug/helloworld", HelloWorldHandler) | |
a.muxAuth.HandleFunc("/services", HelloWorldHandler).Methods("POST") | |
a.mux.Handle("/services", negroni.New(negroni.HandlerFunc(authorizationMiddleware), negroni.Wrap(a.muxAuth))) | |
a.n.UseHandler(a.mux) | |
} | |
func (a *ApiServer) RunServer() error { | |
log.Print("Started at :2010") | |
graceful.Run(":2010", 10*time.Second, a.n) | |
return nil | |
} | |
func authorizationMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { | |
val1 := context.GetAll(r) | |
log.Print(len(val1)) | |
for k, v := range val1 { | |
log.Print(k) | |
log.Print(v) | |
} | |
log.Print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>") | |
context.Set(r, "key", "unauthorizedRequest") | |
return | |
} | |
func errorHandlerMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { | |
context.Set(r, "key", "unauthorizedRequest") | |
next(w, r) | |
val1 := context.GetAll(r) | |
log.Print(len(val1)) | |
for k, v := range val1 { | |
log.Print(k) | |
log.Print(v) | |
} | |
val := context.GetAll(r) | |
log.Print(len(val)) | |
} | |
func HelloWorldHandler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "Hello World!") | |
} | |
func main() { | |
api, err := NewApiServer() | |
err = api.RunServer() | |
if err != nil { | |
log.Fatal("Could not start the server: ", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment