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
+23.9k Golang : How to validate URL the right way
+16.1k Golang : Check if a string contains multiple sub-strings in []string?
+15.1k Golang : ROT47 (Caesar cipher by 47 characters) example
+13.5k Golang : Get dimension(width and height) of image file
+10.7k Golang : Simple image viewer with Go-GTK
+5.5k Unix/Linux : How to test user agents blocked successfully ?
+10.4k Golang : Simple File Server
+8.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+8.3k Linux/Unix : fatal: the Postfix mail system is already running
+8.2k Golang : How to check if input string is a word?
+38.7k Golang : How to iterate over a []string(array)
+8.7k Golang : Inject/embed Javascript before sending out to browser example