dsa5211314 2017-02-02 16:05
浏览 96
已采纳

大猩猩mux http包

I'm using Gorilla mux as my router and dispatcher in my golang apps and I have a -I think- simple question:

In my main, I create a router: r := mux.NewRouter(). A few lines further, I register a handler: r.HandleFunc("/", doSomething).

So far so good, but now my problem is that I have a package which adds handlers to the http package of Golang and not to my mux router. Like this:

func AddInternalHandlers() {
    http.HandleFunc("/internal/selfdiagnose.html", handleSelfdiagnose)
    http.HandleFunc("/internal/selfdiagnose.xml", handleSelfdiagnose)
    http.HandleFunc("/internal/selfdiagnose.json", handleSelfdiagnose)
}

As you can see, it adds handles to the http.HandleFunc and not to the mux-handleFunc. Any idea how I can fix this without touching the package itself?

Working example

package main

import (
    "fmt"
    "log"

    "net/http"

    selfdiagnose "github.com/emicklei/go-selfdiagnose"
    "github.com/gorilla/mux"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
    log.Println("home")
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", homeHandler)

    selfdiagnose.AddInternalHandlers()

  // when handler (nil) gets replaced with mux (r), then the
  // handlers in package selfdiagnose are not "active"
    err := http.ListenAndServe(fmt.Sprintf("%s:%d", "localhost", 8080), nil)
    if err != nil {
        log.Println(err)
    }

}
  • 写回答

1条回答 默认 最新

  • duanhoupeng6642 2017-02-02 19:21
    关注

    Well, in your particular case, the solution is easy.

    The author of the selfdiagnose package choose to make handlers themselves public, so you can just use them directly:

    r.HandleFunc("/", homeHandler)
    // use the handlers directly, but you need to name a route yourself
    r.HandleFunc("/debug", selfdiagnose.HandleSelfdiagnose)
    

    Working example: https://gist.github.com/miku/9836026cacc170ad5bf7530a75fec777

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.