我是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) }
原文地址:https://www.jb51.cc/go/186911.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。