加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang http mux更改处理函数

发布时间:2020-12-16 19:23:36 所属栏目:大数据 来源:网络整理
导读:我是Go的新手,并且无法找到任何有关此信息的信息,也许此时此刻不可能. 我试图删除或替换多路复用路由(使用http.NewServeMux或gorilla的mux.Router).我的最终目标是能够启用/禁用路由或路由集,而无需重新启动程序. 我可以在处理程序基础上完成此操作,如果该功
我是Go的新手,并且无法找到任何有关此信息的信息,也许此时此刻不可能.

我试图删除或替换多路复用路由(使用http.NewServeMux或gorilla的mux.Router).我的最终目标是能够启用/禁用路由或路由集,而无需重新启动程序.

我可以在处理程序基础上完成此操作,如果该功能被“禁用”,则返回404,但我宁愿找到更通用的方法来执行此操作,因为我想为我的应用程序中的每个路由实现它.

或者我会更好地跟踪禁用的url模式并使用一些中间件来阻止处理程序执行?

如果有人能够至少指出我正确的方向,我绝对会发布解决方案的代码示例,假设有一个.谢谢!

没有内置方式,但很容易实现 play.
type HasHandleFunc interface { //this is just so it would work for gorilla and http.ServerMux
    HandleFunc(pattern string,handler func(w http.ResponseWriter,req *http.Request))
}
type Handler struct {
    http.HandlerFunc
    Enabled bool
}
type Handlers map[string]*Handler

func (h Handlers) ServeHTTP(w http.ResponseWriter,r *http.Request) {
    path := r.URL.Path
    if handler,ok := h[path]; ok && handler.Enabled {
        handler.ServeHTTP(w,r)
    } else {
        http.Error(w,"Not Found",http.StatusNotFound)
    }
}

func (h Handlers) HandleFunc(mux HasHandleFunc,pattern string,handler http.HandlerFunc) {
    h[pattern] = &Handler{handler,true}
    mux.HandleFunc(pattern,h.ServeHTTP)
}

func main() {
    mux := http.NewServeMux()
    handlers := Handlers{}
    handlers.HandleFunc(mux,"/",func(w http.ResponseWriter,r *http.Request) {
        w.Write([]byte("this will show once"))
        handlers["/"].Enabled = false
    })
    http.Handle("/",mux)
    http.ListenAndServe(":9020",nil)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读