How to create and expose custom runtime variables using expvar in Go?

To create and expose custom runtime variables using expvar in Go, you can follow these steps:

  1. Import the required packages:
import ( "expvar" "net/http" )
  1. Define global variables that you want to expose:
var ( totalRequests = expvar.NewInt("total_requests") responseTime = expvar.NewFloat("response_time") )
  1. Increment and update the values of these variables wherever necessary in your code:
totalRequests.Add(1) responseTime.Set(0.123)
  1. Optionally, create an HTTP handler function to expose these variables:
func expvarHandler(w http.ResponseWriter, r *http.Request) { expvar.Do(func(kv expvar.KeyValue) { // Write the key-value pairs to the response fmt.Fprintf(w, "%s: %s\n", kv.Key, kv.Value) }) }
  1. Register the handler function to expose the variables:
http.HandleFunc("/debug/vars", expvarHandler)
  1. Start the HTTP server to listen and serve requests:
http.ListenAndServe(":8080", nil)

Now, when you access http://localhost:8080/debug/vars in your web browser or through a tool like cURL, you will see a list of all variables and their values, including the custom runtime variables defined using expvar.

Note: expvar package does not provide any form of authentication or security. So, make sure to handle the access to these runtime variables appropriately in production systems.