danielgtaylor / huma

Huma REST/HTTP API Framework for Golang with OpenAPI 3.1
https://huma.rocks/
MIT License
2.12k stars 152 forks source link

Question: How to influence huma response code and error from router specific middleware? #514

Open kamal2311 opened 3 months ago

kamal2311 commented 3 months ago

I am using Gin as the router with Huma. I have added a gin specific middleware to perform auth on incoming requests based on Authorization header.

From my Gin middleware, I attempt to set status and error on gin Context and return

c.Status(http.StatusUnauthorized)
c.Error(fmt.Errorf(errStr))
return

Huma responds with 200 OK. How do I pass on status and error to influence huma's response?

If I use c.AbortWithError like the following

c.AbortWithError(http.StatusUnauthorized, huma.Error401Unauthorized(errStr))
return

huma returns the response with status code but without the error body.

How do I get huma to return the right status code and the error detail taking into account the error produced from the gin middleware?

danielgtaylor commented 3 months ago

@kamal2311 If you are still calling c.Next() it will still route the request into Huma's handlers and process them. Do you have a quick example you can share that triggers this so I can dig deeper if you aren't calling c.Next()? You can use https://go.dev/play/p/xrlGxyVZBge as a starting point.