github.com/annwntech/go-micro/v2@v2.9.5/debug/profile/http/http.go (about)

     1  // Package http enables the http profiler
     2  package http
     3  
     4  import (
     5  	"context"
     6  	"net/http"
     7  	"net/http/pprof"
     8  	"sync"
     9  
    10  	"github.com/annwntech/go-micro/v2/debug/profile"
    11  )
    12  
    13  type httpProfile struct {
    14  	sync.Mutex
    15  	running bool
    16  	server  *http.Server
    17  }
    18  
    19  var (
    20  	DefaultAddress = ":6060"
    21  )
    22  
    23  // Start the profiler
    24  func (h *httpProfile) Start() error {
    25  	h.Lock()
    26  	defer h.Unlock()
    27  
    28  	if h.running {
    29  		return nil
    30  	}
    31  
    32  	go func() {
    33  		if err := h.server.ListenAndServe(); err != nil {
    34  			h.Lock()
    35  			h.running = false
    36  			h.Unlock()
    37  		}
    38  	}()
    39  
    40  	h.running = true
    41  
    42  	return nil
    43  }
    44  
    45  // Stop the profiler
    46  func (h *httpProfile) Stop() error {
    47  	h.Lock()
    48  	defer h.Unlock()
    49  
    50  	if !h.running {
    51  		return nil
    52  	}
    53  
    54  	h.running = false
    55  
    56  	return h.server.Shutdown(context.TODO())
    57  }
    58  
    59  func (h *httpProfile) String() string {
    60  	return "http"
    61  }
    62  
    63  func NewProfile(opts ...profile.Option) profile.Profile {
    64  	mux := http.NewServeMux()
    65  
    66  	mux.HandleFunc("/debug/pprof/", pprof.Index)
    67  	mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
    68  	mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
    69  	mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
    70  	mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
    71  
    72  	return &httpProfile{
    73  		server: &http.Server{
    74  			Addr:    DefaultAddress,
    75  			Handler: mux,
    76  		},
    77  	}
    78  }