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 關注
- 136 瀏覽
添加回答
舉報