Description
I would like to add a middleware to Gin which detects whether the HTTP status code has been set by another handler to anything from 400
and above, and if so, add an application/problem+json
response body that is tailored to the status code.
With the built-in BasicAuthForRealm
middleware, it currently seems impossible to detect that it has invoked c.AbortWithStatus(http.StatusUnauthorized)
in my middleware, since c.Errors()
is not invoked and I can't figure out in my handler that http.StatusUnauthorized
is being set as the status code.
https://github.com/gin-gonic/gin/blob/a889c58de78711cb9b53de6cfcc9272c8518c729/auth.go#L45-L65
c.Request.Response.StatusCode
is also unavailable, as c.Request.Response
is nil
.
How to reproduce
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
g := gin.Default()
g.Use(func(c *gin.Context) {
c.Next()
if c.IsAborted() {
c.JSON(200, gin.H{"message": "You are probably not authorized, but I can't tell for sure."})
}
})
accounts := gin.Accounts{"admin": "password"}
admin := g.Group("admin", gin.BasicAuth(accounts))
admin.GET("", func(c *gin.Context) {
c.JSON(200, gin.H{"message": "Hello admin, nice to meet you!"})
})
g.Run(":9000")
}
Expectations
I expect to be able to detect what previously run handlers have done to the response, so I can act upon it and enrich the response accordingly.
Actual result
It is currently not possible to see what a previously run handler have done to the response.
Environment
- go version:
go1.20.3 darwin/amd64
- gin version (or commit ref):
v1.9.0
- operating system: macOS
11.7.6
Comment From: asbjornu
I just discovered gin.Context.Writer.Status()
which seems to return 401
as expected. Closing.