github.com/kyleu/dbaudit@v0.0.2-0.20240321155047-ff2f2c940496/app/lib/telemetry/httpmetrics/routing.go (about)

     1  // Package httpmetrics - Content managed by Project Forge, see [projectforge.md] for details.
     2  package httpmetrics
     3  
     4  import (
     5  	"net/http"
     6  	"time"
     7  
     8  	"github.com/gorilla/mux"
     9  
    10  	"github.com/kyleu/dbaudit/app/util"
    11  )
    12  
    13  var defaultMetricPath = "/metrics"
    14  
    15  func (p *Metrics) WrapHandler(mux *mux.Router) http.HandlerFunc {
    16  	return func(w http.ResponseWriter, r *http.Request) {
    17  		reqBytes := make(chan int)
    18  		go computeApproximateRequestSize(r, reqBytes)
    19  
    20  		start := util.TimeCurrent()
    21  		mux.ServeHTTP(w, r)
    22  		elapsed := float64(time.Since(start)) / float64(time.Second)
    23  		// status := strconv.Itoa(rc.Response.StatusCode())
    24  		status := "200"
    25  		// rspBytes := float64(len(rc.Response.Body()))
    26  		rspBytes := 100.0
    27  
    28  		reqDur.WithLabelValues(p.Key, status).Observe(elapsed)
    29  		reqCnt.WithLabelValues(p.Key, status, r.Method).Inc()
    30  		reqSize.Observe(float64(<-reqBytes))
    31  		rspSize.Observe(rspBytes)
    32  	}
    33  }
    34  
    35  func computeApproximateRequestSize(r *http.Request, out chan int) {
    36  	s := 0
    37  	if r.URL != nil {
    38  		s += len(r.URL.Path)
    39  		s += len(r.URL.Host)
    40  	}
    41  	s += len(r.Method)
    42  	s += len("HTTP/1.1")
    43  	for k, v := range r.Header {
    44  		if k != "Host" {
    45  			s += len(k) + len(v)
    46  		}
    47  	}
    48  	out <- s
    49  }