disable prometheus if not configured (#663)
This commit is contained in:
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/tal-tech/go-zero/core/metric"
|
||||
"github.com/tal-tech/go-zero/core/prometheus"
|
||||
"github.com/tal-tech/go-zero/core/timex"
|
||||
"github.com/tal-tech/go-zero/rest/internal/security"
|
||||
)
|
||||
@@ -34,6 +35,10 @@ var (
|
||||
// PrometheusHandler returns a middleware that reports stats to prometheus.
|
||||
func PrometheusHandler(path string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
if !prometheus.Enabled() {
|
||||
return next
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
startTime := timex.Now()
|
||||
cw := &security.WithCodeResponseWriter{Writer: w}
|
||||
|
||||
@@ -6,9 +6,26 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/tal-tech/go-zero/core/prometheus"
|
||||
)
|
||||
|
||||
func TestPromMetricHandler(t *testing.T) {
|
||||
func TestPromMetricHandler_Disabled(t *testing.T) {
|
||||
promMetricHandler := PrometheusHandler("/user/login")
|
||||
handler := promMetricHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
|
||||
resp := httptest.NewRecorder()
|
||||
handler.ServeHTTP(resp, req)
|
||||
assert.Equal(t, http.StatusOK, resp.Code)
|
||||
}
|
||||
|
||||
func TestPromMetricHandler_Enabled(t *testing.T) {
|
||||
prometheus.StartAgent(prometheus.Config{
|
||||
Host: "localhost",
|
||||
Path: "/",
|
||||
})
|
||||
promMetricHandler := PrometheusHandler("/user/login")
|
||||
handler := promMetricHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
Reference in New Issue
Block a user