duanchun1852 2014-06-16 21:27
浏览 72
已采纳

Golang HTTP Mux更改处理程序功能

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.

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.

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.

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!

  • 写回答

3条回答 默认 最新

  • drdyszuy488152 2014-06-16 21:53
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分