gorilla mux http 包

标签 go gorilla mux

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

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

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

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

}

最佳答案

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

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

关于 gorilla mux http 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42006921/

相关文章:

logging - 如何将 Golang 的日志输出设置回控制台?

node.js - 如何在产品环境中保护我的 GO REST 服务?

go - 阻止来自 gorilla/mux 的打开 URL 重定向

json - Golang JSON 路由配置

sql - 如何在go中使用sql server包

go - 无法将数字解码为 Go Value

go - 如何捕获像 ctrl+c 这样的 os 信号并通过 gorilla websocket 在 go 中发送它们

session - 如何检测 session 是否即将过期?

go - 如何使用 Gorilla Mux 进行 URL 匹配?