亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當路由方法不匹配時,在 gorilla mux 中發送自定義響應

當路由方法不匹配時,在 gorilla mux 中發送自定義響應

Go
慕森王 2022-06-13 10:44:28
當路由方法(HTTP 動詞)不匹配時,如何發送自定義響應?當我在 post 方法中點擊以下路線時r.handleFunc("/destination", handler).Methods('GET')我想接收(假設它是 JSON 響應){    status: "ERROR",    message: "Route method not supported."}這個想法是我不想讓每個處理程序都使用route.Method == $METHOD檢查。尋找一種我可以定義一次并應用于每條路線的方法。
查看完整描述

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")

    })

}


查看完整回答
反對 回復 2022-06-13
?
www說

TA貢獻1775條經驗 獲得超8個贊

查看一些 gorilla/handler 存儲庫。它包含中間件處理程序(例如,在您的主處理程序之前執行的處理程序),包括一個用于檢查是否允許 HTTP 方法的處理程序。例如:


MethodHandler{

  "GET": myHandler,

}

任何其他方法都會自動返回405 Method not allowed響應。


查看完整回答
反對 回復 2022-06-13
  • 2 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號