Golang expvar.Do() function examples
package expvar
Do calls f (1st parameter) for each exported variable. The global variable map is locked during the iteration, but existing entries may be concurrently updated.
Golang expvar.Do() function usage examples
Example 1 :
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) { // <-- here
if !first {
fmt.Fprintf(w, ",\n")
}
first = false
fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
})
fmt.Fprintf(w, "\n}\n")
}
Example 2 :
package main
import (
"fmt"
"net/http"
"expvar"
)
func kvfunc(kv expvar.KeyValue) {
fmt.Println(kv.Key, kv.Value)
}
func main() {
var inerInt int64 = 10
pubInt := expvar.NewInt("Int")
pubInt.Set(inerInt)
pubInt.Add(2)
var inerFloat float64 = 1.2
pubFloat := expvar.NewFloat("Float")
pubFloat.Set(inerFloat)
pubFloat.Add(0.1)
var inerString string = "hello gophers"
pubString := expvar.NewString("String")
pubString.Set(inerString)
pubMap := expvar.NewMap("Map").Init()
pubMap.Set("Int", pubInt)
pubMap.Set("Float", pubFloat)
pubMap.Set("String", pubString)
pubMap.Add("Int", 1)
pubMap.Add("NewInt", 123)
pubMap.AddFloat("Float", 0.5)
pubMap.AddFloat("NewFloat", 0.9)
pubMap.Do(kvfunc)
expvar.Do(kvfunc) // <---- here
http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "hello gophers")
})
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}
References :
http://golang.org/pkg/expvar/#Do
https://github.com/docker/docker/blob/master/api/server/server.go
Advertisement
Something interesting
Tutorials
+11.3k Golang : Byte format example
+6.3k Javascript : Generate random key with specific length
+11.5k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+10.6k Golang : ISO8601 Duration Parser example
+7.7k Golang : get the current working directory of a running program
+15.9k Golang : Get file permission
+16.9k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+10.5k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+9k Golang : How to use Gorilla webtoolkit context package properly
+5.4k Golang : Return multiple values from function
+11.1k Golang : Fix go.exe is not compatible with the version of Windows you're running
+11.7k Golang : How to detect a server/machine network interface capabilities?