How to expose the number of HTTP requests or responses using expvar in Go?

To expose the number of HTTP requests or responses using expvar in Go, you can follow these steps:

  1. Import the required packages:
import ( "expvar" "net/http" )
  1. Initialize expvar variables to track the number of requests and responses:
var ( requests = expvar.NewInt("requests") responses = expvar.NewInt("responses") )
  1. Create an HTTP handler to increment the request and response counters:
func handler(w http.ResponseWriter, r *http.Request) { requests.Add(1) // Increment the requests counter // Your code here... // This is the actual handler logic responses.Add(1) // Increment the responses counter }
  1. Set up the expvar HTTP handler to expose the variables:
func main() { http.Handle("/debug/vars", expvar.Handler()) // Your other handlers, route configurations, etc. // Start the server http.ListenAndServe(":8080", nil) }
  1. Run your Go program, and access the expvar endpoint at http://localhost:8080/debug/vars to see the exposed variables.

By monitoring the exposed requests and responses variables, you can track the number of HTTP requests and responses to your Go application.