Problem with routing and middleware

For middlewares, I use alice package.

Here is my dynamic middleware:

dynamicMiddleware := alice.New(app.session.Enable, app.authenticate)

And for the /snippet/create/ route:

mux.Post("/snippet/create", dynamicMiddleware.ThenFunc(app.createSnippet))

When I’m trying to add one more method to that route for authentication and use alice.Append(), I’m getting a error:

mux.Post("/snippet/create", dynamicMiddleware.Append(app.requireAuthenticatedUser, app.createSnippet))

I guess the reason is that requireAuthenticatedUser cannot be used as an argument is that it returns a http.Handler func (app *application) requireAuthenticatedUser(next http.Handler) http.Handler.

In contrast, the createSnippet() method has a func (app *application) createSnippet(w http.ResponseWriter, r *http.Request) signature.

So the question is, what should I do with requireAuthenticatedUser to satisfy alice.Append()?

The error message is: cannot use dynamicMiddleware.Append(app.requireAuthenticatedUser, app.createSnippet) (value of type alice.Chain) as http.Handler value in argument to mux.Post: missing method ServeHTTP.

mux.Post("/snippet/create", 
    dynamicMiddleware.
        Append(app.requireAuthenticatedUser).
        ThenFunc(app.createSnippet),
)

mux.Post expects a http.Handler. Append returns a Chain, not a http.Handler. Therfore you always need to end with a Then or ThenFunc because only they return http.Handler.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.