How to expose and track request/response sizes with expvar in Go?

To expose and track request/response sizes with expvar in Go, you can follow these steps:

  1. Import the necessary packages:
import ( "expvar" "net/http" )
  1. Define global variables to track the request and response sizes:
var ( requestsSize = expvar.NewInt("request_size") responseSize = expvar.NewInt("response_size") )
  1. Create middleware to measure the size of the incoming request. This middleware will update the requestsSize variable with the size of each incoming request:
func measureRequestSize(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w, r) requestsSize.Add(int64(r.ContentLength)) }) }
  1. Create middleware to measure the size of the outgoing response. This middleware will update the responseSize variable with the size of each outgoing response:
func measureResponseSize(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w, r) proxyWriter := w.(*httputil.ReverseProxy).BufferPool.(*httputil.BufferPool).ProxyWriter responseSize.Add(int64(proxyWriter.BytesWritten())) }) }

Note: Make sure to adjust the cast to httputil.ReverseProxy and httputil.BufferPool based on your specific use case. The example above assumes you are using a reverse proxy in your application.

  1. Use the middleware in your main request handler:
func mainHandler(w http.ResponseWriter, r *http.Request) { // Your main request handler logic here } func main() { http.Handle("/", measureRequestSize(measureResponseSize(http.HandlerFunc(mainHandler)))) http.ListenAndServe(":8080", nil) }
  1. Now, you can access the request and response sizes by visiting the /debug/vars endpoint of your application:
http://localhost:8080/debug/vars

The output will include the request size (request_size) and the response size (response_size) under the expvar section.

Note: Remember to import the required packages and customize the middleware and handlers based on your application's needs.

By following these steps, you can expose and track the request/response sizes using expvar in your Go application.