Error compiling with BasicAuth middleware


#1

Hello, I am having an issue when I try to compile my program with the Basic Auth middleware. This is the code:

g := e.Group("/admin")
g.Use(middleware.Logger())
g.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (error, bool) {
    //Check DB
    if username == "carl" && password == "12345" {
        return nil, true
    }
    return nil, false
}))

This is the error I get:

cannot use func literal (type func(string, string, echo.Context) (error, bool)) as type middleware.BasicAuthValidator in argument to middleware.BasicAuth

I am relatively new to Go and Echo so I’m not quite sure what this means as this handler does fit the definition of the middleware.BasicAuthValidator type. I am using go version go1.11.4 darwin/amd64 and the latest version of Echo (I installed it today). I know that there is a similar question that was asked, however, the chosen answer doesn’t make sense to me.

Any help you can provide would be greatly appreciated!


#2

My advice would be to start trusting the compiler :wink: If compiler says one thing and you’re thinking something else, it’s safe to bet that you (and I mean “you” generically, you, me, everyone) are wrong :slight_smile: The compiling errors are your friend.

In this case, if you carefully read the error and compare that against the expectation, you’d quickly identify the issue:

Error message: "cannot use func literal type…

func(string, string, echo.Context) (error, bool)

and the definition from https://github.com/labstack/echo/blob/master/middleware/basic_auth.go#L27:

func(string, string, echo.Context) (bool, error)

So, is the compiler right or wrong to give that error?

Hope it helps!
Alex


#3

Also, FWIW, in general in Go, if a function/method returns an error, that parameter is the last one.