Home > Mobile >  Go Gin - http "HEAD" request method
Go Gin - http "HEAD" request method

Time:09-17

I tried to set http method to "GET" if an incoming request method is "HEAD" in a middleware like below.

It looks like Gin recognizes this as "GET" request if I do curl -I, but it responds with 404 as the attached log shows (the bottom one).

I just wanted to see if this works without implementing "HEAD" method in a router level. Any advice?

func CORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "*")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "*")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(http.StatusNoContent)
            return
        }

        //  set http method to "GET" if an incoming request is "HEAD"
        if c.Request.Method == "HEAD" {
            c.Request.Method = "GET"
        }

        c.Next()
    }
}

gin's log

CodePudding user response:

Because gin middleware is a processing function obtained after route matching, middleware executes after route matching, so middleware cannot modify the route matching method.

By decorating a layer of http.Handler(gin.Engine), use http.Server middleware to modify the request method.

Note: There is no response body for the 'HEAD' request. If there is a response body after converting 'HEAD' to 'GET', which does not conform to the http protocol specification, it is recommended to register all the 'Get' processing functions with the 'Head' method.

func main() {
    router := gin.Default()

    s := &http.Server{
        Addr:           ":8080",
        Handler:        http.Handler(func(w http.ResponseWriter, r *http.Request){
            if r.Method == "HEAD" {
                r.Method = "GET"
            }
            router.ServeHTTP(w, r)
        }),
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    s.ListenAndServe()
}
  • Related