duanliexi1052 2013-10-25 05:21
浏览 137
已采纳

使用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 05: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部