github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_server_pprof.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  // pprof封装.
     7  
     8  package ghttp
     9  
    10  import (
    11  	"github.com/zhongdalu/gf/g/os/gview"
    12  	netpprof "net/http/pprof"
    13  	runpprof "runtime/pprof"
    14  	"strings"
    15  )
    16  
    17  // 用于pprof的对象
    18  type utilPprof struct{}
    19  
    20  func (p *utilPprof) Index(r *Request) {
    21  	profiles := runpprof.Profiles()
    22  	action := r.Get("action")
    23  	data := map[string]interface{}{
    24  		"uri":      strings.TrimRight(r.URL.Path, "/") + "/",
    25  		"profiles": profiles,
    26  	}
    27  	if len(action) == 0 {
    28  		buffer, _ := gview.ParseContent(`
    29              <html>
    30              <head>
    31                  <title>gf ghttp pprof</title>
    32              </head>
    33              {{$uri := .uri}}
    34              <body>
    35                  profiles:<br>
    36                  <table>
    37                      {{range .profiles}}<tr><td align=right>{{.Count}}<td><a href="{{$uri}}{{.Name}}?debug=1">{{.Name}}</a>{{end}}
    38                  </table>
    39                  <br><a href="{{$uri}}goroutine?debug=2">full goroutine stack dump</a><br>
    40              </body>
    41              </html>
    42              `, data)
    43  		r.Response.Write(buffer)
    44  		return
    45  	}
    46  	for _, p := range profiles {
    47  		if p.Name() == action {
    48  			p.WriteTo(r.Response.Writer, r.GetRequestInt("debug"))
    49  			break
    50  		}
    51  	}
    52  }
    53  
    54  func (p *utilPprof) Cmdline(r *Request) {
    55  	netpprof.Cmdline(r.Response.Writer, r.Request)
    56  }
    57  
    58  func (p *utilPprof) Profile(r *Request) {
    59  	netpprof.Profile(r.Response.Writer, r.Request)
    60  }
    61  
    62  func (p *utilPprof) Symbol(r *Request) {
    63  	netpprof.Symbol(r.Response.Writer, r.Request)
    64  }
    65  
    66  func (p *utilPprof) Trace(r *Request) {
    67  	netpprof.Trace(r.Response.Writer, r.Request)
    68  }
    69  
    70  // 开启pprof支持
    71  func (s *Server) EnablePprof(pattern ...string) {
    72  	p := "/debug/pprof"
    73  	if len(pattern) > 0 {
    74  		p = pattern[0]
    75  	}
    76  	up := &utilPprof{}
    77  	_, _, uri, _ := s.parsePattern(p)
    78  	uri = strings.TrimRight(uri, "/")
    79  	s.BindHandler(uri+"/*action", up.Index)
    80  	s.BindHandler(uri+"/cmdline", up.Cmdline)
    81  	s.BindHandler(uri+"/profile", up.Profile)
    82  	s.BindHandler(uri+"/symbol", up.Symbol)
    83  	s.BindHandler(uri+"/trace", up.Trace)
    84  }