-
Notifications
You must be signed in to change notification settings - Fork 3
/
no_method.go
30 lines (27 loc) · 891 Bytes
/
no_method.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
package ginKit
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/richelieu-yang/chimera/v3/src/core/sliceKit"
"github.com/richelieu-yang/chimera/v3/src/core/strKit"
"net/http"
)
func DefaultNoMethod(engine *gin.Engine) {
engine.NoMethod(func(ctx *gin.Context) {
var allowed []string
route := ctx.Request.URL.Path
routeInfoSlice := engine.Routes()
for _, routeInfo := range routeInfoSlice {
if routeInfo.Path == route {
allowed = append(allowed, routeInfo.Method)
}
}
// http状态码405,需要加上响应头 Allow
ctx.Header("Allow", sliceKit.Join(allowed, ", "))
text := fmt.Sprintf("Method(%s) isn't allowed for route(%s), allowed methods is %s.", ctx.Request.Method, ctx.Request.URL.Path, allowed)
if strKit.IsNotEmpty(serviceInfo) {
text = fmt.Sprintf("[%s] %s", serviceInfo, text)
}
ctx.String(http.StatusMethodNotAllowed, text)
})
}