You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

73 lines
1.7 KiB

package devserver
import (
"encoding/json"
"fmt"
"git.diulo.com/mogfee/kit/core/logx"
"git.diulo.com/mogfee/kit/internal/health"
"github.com/felixge/fgprof"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/zeromicro/go-zero/core/threading"
"net/http"
"net/http/pprof"
"sync"
)
var once sync.Once
type Server struct {
config Config
server *http.ServeMux
routes []string
}
func NewServer(cfg Config) *Server {
return &Server{
config: cfg,
server: http.NewServeMux(),
}
}
func (s *Server) addRoutes() {
s.handleFunc("/", func(writer http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(writer).Encode(s.routes)
})
//health
s.handleFunc(s.config.HealthPath, health.CreateHttpHandler())
//metrics
if s.config.EnableMetrics {
s.handleFunc(s.config.MetricsPath, promhttp.Handler().ServeHTTP)
}
if s.config.EnablePprof {
s.handleFunc("/debug/fgprof", fgprof.Handler().(http.HandlerFunc))
s.handleFunc("/debug/pprof/", pprof.Index)
s.handleFunc("/debug/pprof/cmdline", pprof.Cmdline)
s.handleFunc("/debug/pprof/profile", pprof.Profile)
s.handleFunc("/debug/pprof/symbol", pprof.Symbol)
s.handleFunc("/debug/pprof/trace", pprof.Trace)
}
}
func (s *Server) handleFunc(pattern string, handler http.HandlerFunc) {
s.server.HandleFunc(pattern, handler)
s.routes = append(s.routes, pattern)
}
func (s *Server) StartASync() {
s.addRoutes()
threading.GoSafe(func() {
addr := fmt.Sprintf("%s:%d", s.config.Host, s.config.Port)
logx.Infof("Starting dev http server at %s", addr)
if err := http.ListenAndServe(addr, s.server); err != nil {
logx.Error(err)
}
})
}
func StartAgent(c Config) {
once.Do(func() {
if c.Enabled {
s := NewServer(c)
s.StartASync()
}
})
}