Search code examples
goswagger-2.0swagger-codegengo-swagger

How to respond with code 401 or 404 instead of 500 in go-swagger for invalid bearer token


I have created a REST API server using go-swagger and added bearer token security to a few endpoints. As per docs, the token verification method should have a signature like func(string) (interface{}, error).

The token verification method returns an error if the passed bearer token is not valid. This results in 500 responses to the requestor with JSON response body:

{
    "code": 500,
    "message": "Token is expired"
}

However, as standers how can I make this response with code 401.

Note: A similar discussion like this for Java can be found at https://stackoverflow.com/a/60738107/16087692 , Is there any way to achieve this Go?


Solution

  • I've no experience with go-swagger but just stumbled upon this question. The answer is in the examples: https://github.com/go-swagger/go-swagger/tree/master/examples/authentication

    The example shows that the function returns an:

    errors.New(401, "incorrect api key auth")
    

    This is an error from the package: "github.com/go-openapi/errors" where you can pass in a http status code.