Last active
November 28, 2021 12:06
-
-
Save mrk21/a22c6f67398b77fedcf5237c5e44522f to your computer and use it in GitHub Desktop.
Gin middleware. It override HTTP method by `_method` POST body parameter. It's for HTML forms.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"strings" | |
"github.com/gin-gonic/gin" | |
) | |
// Override HTTP method by `_method` POST body parameter. It's for HTML forms. | |
// @see [bu/gin-method-override: MethodOverride middleware for Gin web framework](https://github.com/bu/gin-method-override) | |
func OverrideHttpMethod(r *gin.Engine) gin.HandlerFunc { | |
return func(c *gin.Context) { | |
if c.Request.Method != "POST" { | |
c.Next() | |
return | |
} | |
method := strings.ToUpper(c.PostForm("_method")) | |
switch method { | |
case "PUT", "PATCH", "DELETE": | |
c.Request.Method = method | |
c.Abort() | |
r.HandleContext(c) | |
default: | |
c.Next() | |
} | |
} | |
} | |
func main() { | |
r := gin.New() | |
r.Use(OverrideHttpMethod(r)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment