doujia9204 2017-03-02 15:12
浏览 29
已采纳

绕过Golang HTTP处理程序

Let's say I have code like this

handler := middleware1.New(
    middleware2.New(
        middleware3.New(
            middleware4.New(
                NewHandler()
            ),
        ),
    ),
)
http.ListenAndServe(":8080", handler)

where handler has tons of middleware.

Now I want to create custom endpoint, which will skip all the middleware, so nothing what's inside serveHTTP() functions is executed:

http.HandleFunc("/testing", func(
    w http.ResponseWriter,
    r *http.Request,
) {
    fmt.Fprintf(w, "it works!")
    return
})
http.ListenAndServe(":8080", handler)

But this doesn't work and /testing is never reached. Ideally, I don't want to modify handler at all, is that possible?

  • 写回答

2条回答 默认 最新

  • doushi1964 2017-03-02 15:44
    关注

    You can use an http.ServeMux to route requests to the correct handler:

    m := http.NewServeMux()
    m.HandleFunc("/testing", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "it works!")
        return
    })
    m.Handle("/", handler)
    
    http.ListenAndServe(":8080", m)
    

    Using the http.HandleFunc and http.Handle functions will accomplish the same result using the http.DefaultServerMux, in which case you would leave the handler argument to ListenAndServe as nil.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我现在每日需要统计工作数据,分别登在几个工作簿里面,然后每个工作簿里面有多个工作表,我只想在一个界面输入信息,然后这些信息能自动写到对应的工作表中去
  • ¥15 Vue 前端调用本地jar包有什么方法?
  • ¥20 py3.7.4离线安装openpyxl等错误
  • ¥15 基础的图像处理问题求解答
  • ¥50 全国两定智慧医保接口开发相关业务文档,以及技术实现流程文档
  • ¥15 idea做图书管理系统,要求如下
  • ¥15 最短路径分配法——多路径分配
  • ¥15 SQL server 2022安装程序(英语)无法卸载
  • ¥15 关于#c++#的问题:把一个三位数的素数写在另一个三位数素数的后面
  • ¥15 求一个nao机器人跳舞的程序