2 回答
TA贡献1796条经验 获得超10个赞
要为路由方法设置自定义返回,您可以简单地用您自己的处理程序“MethodNotAllowedHandler”覆盖。
例子:
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
log.Fatal(http.ListenAndServe(":8080", router()))
}
func router() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/destination", destination).Methods("GET")
r.MethodNotAllowedHandler = MethodNotAllowedHandler()
return r
}
func destination(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "destination output")
}
func MethodNotAllowedHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Method not allowed")
})
}
TA贡献1775条经验 获得超8个赞
查看一些 gorilla/handler 存储库。它包含中间件处理程序(例如,在您的主处理程序之前执行的处理程序),包括一个用于检查是否允许 HTTP 方法的处理程序。例如:
MethodHandler{
"GET": myHandler,
}
任何其他方法都会自动返回405 Method not allowed响应。
- 2 回答
- 0 关注
- 191 浏览
添加回答
举报
