Returning a response from Middleware
Closed this issue · 2 comments
Hi there !
I'm currently switching my project that was using plain Gin to the Chi router in combination with Huma. So far everything went quite smoothly, but I'm really struggling to migrate one of my middleware.
This middleware is checking the global state of the application and then send a response to the user if the state is true
. In Gin it was a quite simple thing to do, and did not need too much thinking to implement. However here, I'm struggling a lot, not really knowing how I should do this.
Note that I want to implement this has an agnostic router middleware, but let me know if it's not possible.
Here's what I used with Gin as a part of my middleware :
if status := statusHandler.GetStatus(); status {
c.AbortWithStatusJSON(http.StatusForbidden, models.ErrorResponse{
Error: "Current status of the app does not allow this request for now.",
})
return
}
Could someone let me know how I can reproduce this using a router agnostic middleware ? I did see the huma.WriteErr
method but it wants me to pass the main API object which I find quite strange. And since my middleware is not in the same package as the API object, I cannot really easily pass it to my middleware.
Thanks in advance !
@redat00 any dependencies your middleware needs you can just pass in when instantiating it, for example:
func MyMiddleware(api huma.API) func(ctx huma.Context, next func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
if true /* some condition */ {
huma.WriteErr(api, ctx, http.StatusForbidden, "Current status of the app does not allow this request for now.")
return
}
next(ctx)
}
}
Ouh of course why didn't I think of that ! Thanks for including a link to a Go playground ! Thanks a lot !