Skip to content

Instantly share code, notes, and snippets.

@mrk21
Last active November 28, 2021 12:06
Show Gist options
  • Save mrk21/a22c6f67398b77fedcf5237c5e44522f to your computer and use it in GitHub Desktop.
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.
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