Middlewares Route Related with Negroni

I have a web server using httprouter and negroni. Users log in to this system through external OAuth. We store the token in an encrypted session that indicates whether they are logged in. I would like to use middleware to check for the presence or absence of this token, and then drop the user to the login page if that is not the case. I want to exclude some routes from using middleware for authentication. Negroni README has an example of doing this with gorilla mux, but I can't fully think of this scaling with httprouter. Something similar to setting up my server below:

router := httprouter.New()
router.GET("/login", Login) // auth not required
router.GET("/", Index)  // auth required

s := negroni.Classic()

s.Use(sessions.Sessions("example-web-dev", cookiestore.New([]byte("some garbage"))))
s.Use(authenticator.Get())
s.UseHandler(router)

Where /loginis the route, I do not want to request authorization through middleware and /is. authenticator.Get()is my function of an authentication handler with content that, it seems to me, is not relevant to the issue.

How can I apply authenticator.Get()to /but not /login? Remembering that there will be several more β€œpublic” routes next to t21 and many other closed routes.

Some links:

+4
source share
2 answers

. , negroni.Negroni . :

router := httprouter.New()
router.Handler("GET", "/login",
               negroni.New(negroni.HandlerFunc(loginHandler)))
router.Handler("GET", "/",
               negroni.New(authenticator.Get(),
               negroni.HandlerFunc(indexHandler)))

server := negroni.Classic()
server.UseHandler(router)
server.Use(sessions.Sessions("example-web-dev",
           cookiestore.New([]byte("some secret"))))
server.Run(":3000")

loginHandler indexHandler :

func(http.ResponseWriter, *http.Request, http.HandlerFunc)

, negroni.Classic(), sessions server, / , authenticator.Get().

+4

httprouter, , router.Lookup. :

_, params, _: = router.Lookup( "GET", req.URL.Path) httprouter.Router

-1

All Articles