From 44ddd1d497f7a74cc0db900e1faa0b67579e22e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=AB=98=E6=B8=90=E7=A6=BB?= Date: Wed, 22 Jan 2025 10:10:00 +0800 Subject: [PATCH] feat: use internal http server not default mux (#13) * use internal http server not default mux * change config * rename option * rename option --- options.go | 27 ++++++++++++++++++--------- trace.go | 8 ++++++-- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/options.go b/options.go index 08c3d13..183b673 100644 --- a/options.go +++ b/options.go @@ -35,19 +35,21 @@ func (fn option) apply(cfg *config) { } type config struct { - buckets []float64 - enableGoCollector bool - registry *prom.Registry - runtimeMetricRules []collectors.GoRuntimeMetricsRule - disableServer bool + buckets []float64 + enableGoCollector bool + registry *prom.Registry + runtimeMetricRules []collectors.GoRuntimeMetricsRule + disableServer bool + useDefaultServerMux bool } func defaultConfig() *config { return &config{ - buckets: defaultBuckets, - enableGoCollector: false, - registry: prom.NewRegistry(), - disableServer: false, + buckets: defaultBuckets, + enableGoCollector: false, + registry: prom.NewRegistry(), + disableServer: false, + useDefaultServerMux: true, } } @@ -89,3 +91,10 @@ func WithRegistry(registry *prom.Registry) Option { } }) } + +// WithDefaultServerMux use http.DefaultServeMux +func WithDefaultServerMux(useDefault bool) Option { + return option(func(cfg *config) { + cfg.useDefaultServerMux = useDefault + }) +} diff --git a/trace.go b/trace.go index ed6ba64..e3727fb 100644 --- a/trace.go +++ b/trace.go @@ -84,9 +84,13 @@ func NewServerTracer(addr, path string, opts ...Option) tracer.Tracer { } if !cfg.disableServer { - http.Handle(path, promhttp.HandlerFor(cfg.registry, promhttp.HandlerOpts{ErrorHandling: promhttp.ContinueOnError})) + httpServer := http.DefaultServeMux + if !cfg.useDefaultServerMux { + httpServer = http.NewServeMux() + } + httpServer.Handle(path, promhttp.HandlerFor(cfg.registry, promhttp.HandlerOpts{ErrorHandling: promhttp.ContinueOnError})) go func() { - if err := http.ListenAndServe(addr, nil); err != nil { + if err := http.ListenAndServe(addr, httpServer); err != nil { hlog.Fatal("HERTZ: Unable to start a promhttp server, err: " + err.Error()) } }()