【问题标题】:Gorilla mux http packageGorilla mux http 包
【发布时间】:2017-06-19 19:15:05
【问题描述】:

我在我的 golang 应用程序中使用 Gorilla mux 作为我的路由器和调度程序,我有一个 - 我认为 - 简单的问题:

在我的主目录中,我创建了一个路由器:r := mux.NewRouter()。再往前几行,我注册了一个处理程序:r.HandleFunc("/", doSomething)

到目前为止一切顺利,但现在我的问题是我有一个包,它将处理程序添加到 Golang 的 http package 而不是我的多路复用路由器。像这样:

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

如您所见,它将句柄添加到 http.HandleFunc 而不是 mux-handleFunc。知道如何在不接触包装本身的情况下解决此问题吗?

工作示例

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

}

【问题讨论】:

  • 您是否在问如何从 DefaultServeMux 中提取处理程序并将它们插入您的路由器?修复你的包以不注册这样的处理程序可能更易于维护。
  • 问题是它不是我的包:)。
  • 那么,这就是您要问的吗?或者,也许您想将您的路由器添加到 DefaultServeMux?
  • 我认为我解释问题的能力不是很好:)。请参阅我刚刚添加到初始问题中的工作示例。

标签: go gorilla mux


【解决方案1】:

嗯,在您的特定情况下,解决方案很简单。

selfdiagnose 包的作者选择将handlers 自己设为公开,因此您可以直接使用它们:

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

工作示例:https://gist.github.com/miku/9836026cacc170ad5bf7530a75fec777

【讨论】:

猜你喜欢
  • 2014-12-22
  • 2017-11-07
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 2020-08-26
  • 2017-05-27
  • 2017-11-09
相关资源
最近更新 更多