-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
45 lines (37 loc) · 1.15 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package methodOverride
import "github.com/gin-gonic/gin"
import "strings"
// ProcessMethodOverride check POST request and re-dispatch them if _method
// exists in POST body, this was intent to act as Ruby MethodOverride rack
// ref: http://www.rubydoc.info/gems/rack/Rack/MethodOverride
func ProcessMethodOverride(r *gin.Engine) gin.HandlerFunc {
return func(c *gin.Context) {
// only need to check POST method
if c.Request.Method != "POST" {
return
}
// only deal with request where _method exists
method := c.PostForm("_method")
if method == "" {
return
}
// these are known verb used frequently
method = strings.ToLower(method)
switch method {
case "delete":
c.Request.Method = "DELETE"
case "put":
c.Request.Method = "PUT"
case "patch":
c.Request.Method = "PATCH"
// if user request method we don't know, then just pass this request to
// next middle-ware, then this will treat as plain POST request
default:
return
}
// cancel current request
c.Abort()
// after we rewrite this request, we need pass to gin engine for routing again, otherwise, this rewrite route will fail to 404
r.HandleContext(c)
}
}