Golang expvar.Publish() function example

package expvar

Publish declares a named exported variable. This should be called from a package's init function when it creates its Vars. If the name (1st parameter) is already registered then this will log.Panic.

Golang expvar.Publish() function usage example

 type UptimeVar struct {
 StartTime time.Time
 }

 func (v *UptimeVar) String() string {
 return strconv.FormatFloat(time.Since(v.StartTime).Seconds(), 'f', 2, 64)
 }

 func init() {
 runtime.GOMAXPROCS(runtime.NumCPU())

 hostname, _ := os.Hostname()
 hostnameVar.Set(hostname)

 expvar.Publish("uptime", &UptimeVar{time.Now()}) // <-- here. Must be called in init() function
 ...
 }

Reference :

http://golang.org/pkg/expvar/#Publish

Advertisement