2019-12-08 20:31:16 +00:00
|
|
|
// Package http enables the http profiler
|
2023-04-11 22:20:37 +03:00
|
|
|
package http // import "go.unistack.org/micro/v4/profiler/http"
|
2019-12-08 20:31:16 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
"net/http/pprof"
|
|
|
|
"sync"
|
|
|
|
|
2023-04-11 22:20:37 +03:00
|
|
|
profile "go.unistack.org/micro/v4/profiler"
|
2019-12-08 20:31:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type httpProfile struct {
|
2021-03-06 19:45:13 +03:00
|
|
|
server *http.Server
|
2019-12-08 20:31:16 +00:00
|
|
|
sync.Mutex
|
|
|
|
running bool
|
|
|
|
}
|
|
|
|
|
2021-04-27 08:32:47 +03:00
|
|
|
// DefaultAddress for http profiler
|
|
|
|
var DefaultAddress = ":6060"
|
2019-12-08 20:31:16 +00:00
|
|
|
|
|
|
|
// Start the profiler
|
|
|
|
func (h *httpProfile) Start() error {
|
|
|
|
h.Lock()
|
|
|
|
defer h.Unlock()
|
|
|
|
|
|
|
|
if h.running {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
if err := h.server.ListenAndServe(); err != nil {
|
|
|
|
h.Lock()
|
|
|
|
h.running = false
|
|
|
|
h.Unlock()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
h.running = true
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop the profiler
|
|
|
|
func (h *httpProfile) Stop() error {
|
|
|
|
h.Lock()
|
|
|
|
defer h.Unlock()
|
|
|
|
|
|
|
|
if !h.running {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
h.running = false
|
|
|
|
|
|
|
|
return h.server.Shutdown(context.TODO())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *httpProfile) String() string {
|
|
|
|
return "http"
|
|
|
|
}
|
|
|
|
|
2021-02-14 16:16:01 +03:00
|
|
|
// NewProfile returns new http profiler
|
|
|
|
func NewProfile(opts ...profile.Option) profile.Profiler {
|
2019-12-08 20:31:16 +00:00
|
|
|
mux := http.NewServeMux()
|
|
|
|
|
|
|
|
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
|
|
|
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
|
|
|
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
|
|
|
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
|
|
|
|
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
|
|
|
|
|
|
|
|
return &httpProfile{
|
|
|
|
server: &http.Server{
|
|
|
|
Addr: DefaultAddress,
|
|
|
|
Handler: mux,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|