登录
首页 >  Golang >  Go问答

当路由方法不匹配时,在 gorilla mux 中发送自定义响应

来源:stackoverflow

时间:2024-03-29 19:27:30 473浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《当路由方法不匹配时,在 gorilla mux 中发送自定义响应》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

当路由方法(http 动词)不匹配时,如何发送自定义响应?

当我在 post 方法中点击以下路线时

r.handlefunc("/destination", handler).methods('get')

我想接收(假设它是一个 json 响应)

{
    status: "ERROR",
    message: "Route method not supported."

}

我的想法是,我不想让每个处理程序都进行 route.method == $method 检查。寻找一种可以定义一次并应用于每条路线的方法。


解决方案


要为路由方法设置自定义返回,您只需用自己的处理程序覆盖“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")
    })
}

查看一些 gorilla/handler 存储库。它包含中间件处理程序(例如,在主处理程序之前执行的处理程序),包括 handler for checking whether a HTTP method is allowed。例如:

MethodHandler{
  "GET": myHandler,
}

任何其他方法都会自动返回 405 method not allowed 响应。

今天关于《当路由方法不匹配时,在 gorilla mux 中发送自定义响应》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>