To import and use the expvar
package in Go, you can follow these steps:
expvar
package at the top of your Go file:import "expvar"
expvar
:var (
counter = expvar.NewInt("counter")
gauge = expvar.NewFloat("gauge")
)
In this example, we created two exported variables, counter
(of type int
) and gauge
(of type float64
).
counter.Add(1)
gauge.Set(3.14)
Here, we incremented the counter
value by 1 and set the gauge
value to 3.14.
expvar
package's http.Handler()
function to expose these variables:http.Handle("/debug/vars", expvar.Handler())
In this example, the /debug/vars
endpoint is used to expose the exported variables.
http.ListenAndServe()
function to achieve this:http.ListenAndServe(":8080", nil)
In this case, the server listens on port 8080
, but you can change it to the desired port.
With these steps, you can import the expvar
package, create and update exported variables, and expose them through an HTTP endpoint in your Go application.