How to import and use the expvar package in Go?

To import and use the expvar package in Go, you can follow these steps:

  1. Import the expvar package at the top of your Go file:
import "expvar"
  1. Create one or more variables that need to be exported using 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).

  1. Update the value of the variables whenever needed. You can do this at any point in your code using the exported variables:
counter.Add(1) gauge.Set(3.14)

Here, we incremented the counter value by 1 and set the gauge value to 3.14.

  1. Expose the exported variables via an HTTP endpoint. You can use the 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.

  1. Start an HTTP server to serve the expvar endpoint. You can use Go's built-in 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.