为了账号安全,请及时绑定邮箱和手机立即绑定

当路由方法不匹配时,在 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 关注
  • 191 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号