Golang : Get expvar(export variables) to work with multiplexer
Golang has the expvar package that allows your web application to display debugging information during run time. Basically, what it does is to expose these variables(debug information or metrics) via HTTP at /debug/vars in JSON format.
Run this code example
package main
import (
"expvar"
"net/http"
"strconv"
"time"
)
type ServerUpTime struct {
StartTime time.Time
}
func (t *ServerUpTime) String() string {
return strconv.FormatFloat(time.Since(t.StartTime).Seconds(), 'f', 2, 64)
}
func init() {
// add one counter to display server up time
expvar.Publish("server uptime", &ServerUpTime{time.Now()})
}
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := "Hello"
html = html + " World"
w.Write([]byte(html))
}
func main() {
http.HandleFunc("/", SayHelloWorld)
http.ListenAndServe(":8080", nil)
}
and point your web browser to let say :
localhost:8080/debug/vars
will produce information such as :
{ "cmdline": ["/var/folders/nd/5m9x1vj4338yt1rg02zbph0000gn/T/go-build469965791/command-line-arguments/_obj/exe/expvar-no-result"], "memstats": {"Alloc":148448,"TotalAlloc":148448,"Sys":3377400,"Lookups":6,"Mallocs":678,"Frees":0,"HeapAlloc":148448,"HeapSys":753664,
...
{"Size":10496,"Mallocs":0,"Frees":0},{"Size":12288,"Mallocs":0,"Frees":0},{"Size":13568,"Mallocs":0,"Frees":0},{"Size":14080,"Mallocs":0,"Frees":0},{"Size":16384,"Mallocs":0,"Frees":0},{"Size":16640,"Mallocs":0,"Frees":0},{"Size":17664,"Mallocs":0,"Frees":0}]}, "server uptime": 4.16 }
However, the expvar
package will not show any information at /debug/vars
when the above code is converted to use http.NewServeMux
(or any multiplexers like Gin or Gorilla). To get the expvar
package to work again with multiplexer, we will need to borrow some codes from https://golang.org/src/expvar/expvar.go and plug the codes into the previous code example.
package main
import (
"expvar"
"net/http"
"runtime"
"strconv"
"time"
"fmt"
"os"
)
type ServerUpTime struct {
StartTime time.Time
}
func (t *ServerUpTime) String() string {
return strconv.FormatFloat(time.Since(t.StartTime).Seconds(), 'f', 2, 64)
}
func init() {
expvar.Publish("server uptime", &ServerUpTime{time.Now()})
}
func expvarHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintf(w, "{\n")
first := true
expvar.Do(func(kv expvar.KeyValue) {
if !first {
fmt.Fprintf(w, ",\n")
}
first = false
fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
})
fmt.Fprintf(w, "\n}\n")
}
func cmdline() interface{} {
return os.Args
}
func memstats() interface{} {
stats := new(runtime.MemStats)
runtime.ReadMemStats(stats)
return *stats
}
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := "Hello"
html = html + " World"
w.Write([]byte(html))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/debug/vars", expvarHandler)
http.ListenAndServe(":8080", mux)
}
Run this modified code example and pointing your browser to localhost:8080/debug/vars
should work now.
NOTES : You can configure another application to eat/parse/store the debugging data produced by your web application in crontab at certain time interval. The debugging data exported by expvar
package can be very useful in analysing performance and resource/memory consumption of your web application.
Happy coding!
References :
https://golang.org/src/expvar/expvar.go
https://www.socketloop.com/references/golang-expvar-publish-function-example
See also : Golang : Debug with Godebug
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.8k Golang : Find and replace data in all files recursively
+19.6k Golang : How to get time from unix nano example
+18.5k Golang : Display list of time zones with GMT
+6.9k Golang : Gorrila mux.Vars() function example
+15.5k Golang : Get current time from the Internet time server(ntp) example
+15k nginx: [emerg] unknown directive "ssl"
+15.8k Golang : How to reverse elements order in map ?
+23.5k Golang : Fix type interface{} has no field or no methods and type assertions example
+4.6k Golang : A program that contain another program and executes it during run-time
+10.1k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+9.8k Golang : Get escape characters \u form from unicode characters
+8.9k Android Studio : Indicate progression with ProgressBar example