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
+26.4k Golang : Convert(cast) string to uint8 type and back to string
+10.9k Golang : How to transmit update file to client by HTTP request example
+3.6k Java : Get FX sentiment from website example
+5.4k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+13k Golang : Calculate elapsed years or months since a date
+5.9k Golang : Shuffle array of list
+15.7k Golang : Get checkbox or extract multipart form data value example
+8.1k Golang : Randomize letters from a string example
+33.6k Golang : How to check if slice or array is empty?
+21.7k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+14.5k Golang : Overwrite previous output with count down timer
+13.5k Golang : Read XML elements data with xml.CharData example