duanliexi1052 2013-10-25 13:21
浏览 136
已采纳

使用net / http / pprof用Gorilla的mux构建的Go Web应用程序性能分析

I have a relatively big web application written in Go that uses Gorilla's mux for routing. I recently realised that my web application is quite slow and I would like to profile the web application.

After reading about it, it seems that net/http/pprof is what I need. But I can't make it run with mux; even in the case of the most trivial web application.

Does anyone knows how to make that work?

Here is an example of a trivial code that does not work (i.e. nothing is served at /debug).

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "math"
    "net/http"
)
import _ "net/http/pprof"

func SayHello(w http.ResponseWriter, r *http.Request) {
    for i := 0; i < 1000000; i++ {
        math.Pow(36, 89)
    }
    fmt.Fprint(w, "Hello!")
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/hello", SayHello)
    http.ListenAndServe(":6060", r)
}
  • 写回答

8条回答 默认 最新

  • doumei7420 2013-10-25 13:35
    关注

    Sorry for that question. The answer is in the init() function of pprof. One just need to add 4 functions from pprof to the mux router. Here is the fixed code from above.

    package main
    
    import (
        "fmt"
        "github.com/gorilla/mux"
        "math"
    
        "net/http"
    )
    import "net/http/pprof"
    
    func AttachProfiler(router *mux.Router) {
        router.HandleFunc("/debug/pprof/", pprof.Index)
        router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
        router.HandleFunc("/debug/pprof/profile", pprof.Profile)
        router.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
    }
    
    func SayHello(w http.ResponseWriter, r *http.Request) {
        for i := 0; i < 1000000; i++ {
            math.Pow(36, 89)
        }
        fmt.Fprint(w, "Hello!")
    }
    
    func main() {
        r := mux.NewRouter()
        AttachProfiler(r)
        r.HandleFunc("/hello", SayHello)
        http.ListenAndServe(":6060", r)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探