Golang expvar.Map type, NewMap(), Add(), AddFloat(), Do(), Get(), Init(), Set() and String() functions examples

package expvar

Map type is a string-to-Var map variable that satisfies the Var interface.

AddFloat function adds delta to the *Float value stored under the given map key.

Do function calls f (1st parameter) for each entry in the map. The map is locked during the iteration, but existing entries may be concurrently updated.

Golang expvar.Map type, NewMap(), Add(), AddFloat(), Do(), Get(), Init(), Set() and String() functions usage examples

 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() // <-- here
 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)
 // getInt := pubMap.Get("Int") // just for demo
 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/#Map

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

http://golang.org/pkg/expvar/#Map.Add

http://golang.org/pkg/expvar/#Map.AddFloat

http://golang.org/pkg/expvar/#Map.Do

http://golang.org/pkg/expvar/#Map.Get

Advertisement