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
+5.7k Golang : Find the shortest line of text example
+12k Golang : Get user input until a command or receive a word to stop
+10.4k Golang : Secure file deletion with wipe example
+4.4k Golang : Detect words using using consecutive letters in a given string
+3k Golang : PGX CopyFrom to insert rows into Postgres database
+9.5k Swift : Convert (cast) String to Integer
+6.1k Golang : Accessing dataframe-go element by row, column and name example
+8.2k Golang : Detect number of active displays and the display's resolution
+6.4k Golang : Rename part of filename
+3.7k Chrome : How to block socketloop.com links in Google SERP?
+13.2k Golang : Overwrite previous output with count down timer
+5.1k Golang : Convert Chinese UTF8 characters to Pin Yin