To create and expose a counter variable with expvar
in Go, you can follow these steps:
Step 1: Import the necessary packages:
import (
"expvar"
"net/http"
)
Step 2: Declare a global counter variable:
var counter = expvar.NewInt("counter")
Step 3: Implement an HTTP handler to increment the counter:
func incrementCounterHandler(w http.ResponseWriter, r *http.Request) {
// Increment the counter
counter.Add(1)
// Write a response
w.Write([]byte("Counter incremented"))
}
Step 4: Start the HTTP server and register the /increment
endpoint:
func main() {
http.HandleFunc("/increment", incrementCounterHandler)
http.ListenAndServe(":8080", nil)
}
Now, when you run your Go program and make a GET request to http://localhost:8080/increment
, the counter will be incremented by 1. You can access the counter's current value by visiting http://localhost:8080/debug/vars
in your browser. The counter variable will be listed under the expvar variables section.