From 2309c80d0030fd4db1b17a5a4e2224e3ca951ce6 Mon Sep 17 00:00:00 2001 From: Thisadee Preeyawongsakul Date: Tue, 4 May 2021 12:08:47 +0700 Subject: [PATCH 1/2] add StatusOverrideFromContext --- middleware.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/middleware.go b/middleware.go index e65c68b..1312ca6 100644 --- a/middleware.go +++ b/middleware.go @@ -2,6 +2,7 @@ package ginprometheus import ( "bytes" + "fmt" "io/ioutil" "net/http" "os" @@ -100,7 +101,8 @@ type Prometheus struct { ReqCntURLLabelMappingFn RequestCounterURLLabelMappingFn // gin.Context string to use as a prometheus URL label - URLLabelFromContext string + URLLabelFromContext string + StatusOverrideFromContext string } // PrometheusPushGateway contains the configuration for pushing to a Prometheus pushgateway (optional) @@ -367,6 +369,13 @@ func (p *Prometheus) HandlerFunc() gin.HandlerFunc { c.Next() status := strconv.Itoa(c.Writer.Status()) + if p.StatusOverrideFromContext != "" { + statusFromContext, found := c.Get(p.StatusOverrideFromContext) + if found { + status = fmt.Sprintf("%v", statusFromContext) + } + } + elapsed := float64(time.Since(start)) / float64(time.Second) resSz := float64(c.Writer.Size()) From 5646ff6ba4d75950e0a1e3f2786d898ace3e5798 Mon Sep 17 00:00:00 2001 From: Thisadee Preeyawongsakul Date: Tue, 4 May 2021 12:11:27 +0700 Subject: [PATCH 2/2] multi-status support --- middleware.go | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/middleware.go b/middleware.go index 1312ca6..24ad18f 100644 --- a/middleware.go +++ b/middleware.go @@ -101,8 +101,9 @@ type Prometheus struct { ReqCntURLLabelMappingFn RequestCounterURLLabelMappingFn // gin.Context string to use as a prometheus URL label - URLLabelFromContext string - StatusOverrideFromContext string + URLLabelFromContext string + //read value to override api status ( first match in array) + StatusOverrideFromContext []string } // PrometheusPushGateway contains the configuration for pushing to a Prometheus pushgateway (optional) @@ -369,10 +370,15 @@ func (p *Prometheus) HandlerFunc() gin.HandlerFunc { c.Next() status := strconv.Itoa(c.Writer.Status()) - if p.StatusOverrideFromContext != "" { - statusFromContext, found := c.Get(p.StatusOverrideFromContext) - if found { - status = fmt.Sprintf("%v", statusFromContext) + + //iterate over each context key to find first match + if len(p.StatusOverrideFromContext) > 0 { + for _, v := range p.StatusOverrideFromContext { + statusFromContext, found := c.Get(v) + if found { + status = fmt.Sprintf("%v", statusFromContext) + break + } } }