我是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) }