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
+14k Golang : Get current time
+10.3k Golang : How to profile or log time spend on execution?
+16.4k Golang : How to extract links from web page ?
+9.6k Golang : Extract or copy items from map based on value
+12.8k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+16k Golang : How to login and logout with JWT example
+13.5k Golang : Verify token from Google Authenticator App
+22.1k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+11.7k Golang : Simple file scaning and remove virus example
+8.4k Golang : Configure Apache and NGINX to access your Go service example
+6.6k PHP : Shuffle to display different content or advertisement
+14.5k Golang : Find network of an IP address