Golang HTTP Mux更改处理程序功能 [英] Golang http mux change handler function
问题描述
我刚开始使用Go,还无法找到有关此的任何信息,也许暂时无法.
I am fairly new to Go and have not been able to find any information on this, maybe it is just not possible at this time.
我正在尝试删除或替换多路复用路由(使用http.NewServeMux或大猩猩的mux.Router).我的最终目标是能够启用/禁用一条路由或一组路由,而不必重新启动程序.
I am trying to delete or replace a mux route (using http.NewServeMux, or gorilla's mux.Router). My end goal is to be able to enable/disable a route or set of routes without having to restart the program.
我可能可以在处理程序到处理程序的基础上完成此操作,并且如果该功能被禁用",则只返回404,但是我宁愿找到更通用的方法来执行此操作,因为我想为我的每条路线实现应用程序.
I can probably accomplish this on a handler to handler basis and just return 404 if that feature is "disabled", but I would rather find a more general way to do this since I would like to implement it for every route in my application.
还是只跟踪禁用的URL模式并使用一些中间件来阻止处理程序执行,我会更好吗?
Or would I be better off just keeping track of disabled url patterns and using some middleware to prevent handler execution?
如果有人至少可以向我指出正确的方向,那么我将绝对地发布解决方案的代码示例(假设有一个解决方案).谢谢!
If someone can at least point me in the right direction, I will absolutely post code examples of a solution assuming there is one. Thanks!
推荐答案
虽然没有内置方法,但是实现播放.
There's no built in way, but it is easy enough to implement 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)
}
这篇关于Golang HTTP Mux更改处理程序功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!