Created
February 14, 2017 01:17
-
-
Save ericxtang/bd5e6cde9e92d254c9871a078e47b6b9 to your computer and use it in GitHub Desktop.
examples for using expvar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
import "time" | |
import "expvar" | |
import "encoding/json" | |
type Nodes struct { | |
peers map[string][]string | |
} | |
func (n *Nodes) AddPeer(node string, peer string) { | |
n.peers[node] = append(n.peers[node], peer) | |
} | |
func (n *Nodes) String() string { | |
str, _ := json.Marshal(n.peers) | |
return string(str) | |
} | |
var ( | |
nodes *Nodes | |
) | |
func main() { | |
nodes = &Nodes{peers: make(map[string][]string)} | |
expvar.Publish("Nodes", nodes) | |
go simulateAdd("node1", "node2", 1) | |
go simulateAdd("node1", "node3", 3) | |
go simulateAdd("node1", "node4", 5) | |
go simulateAdd("node2", "node5", 4) | |
go simulateAdd("node2", "node4", 4) | |
go simulateAdd("node3", "node4", 3) | |
time.Sleep(time.Second * time.Duration(8)) | |
newNodes := expvar.Get("Nodes").(*Nodes) | |
fmt.Println(newNodes) | |
fmt.Println("Done") | |
} | |
func simulateAdd(node string, peer string, waitTime int) { | |
time.Sleep(time.Second * time.Duration(waitTime)) | |
nodes := expvar.Get("Nodes").(*Nodes) | |
nodes.AddPeer(node, peer) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment