-
Notifications
You must be signed in to change notification settings - Fork 0
/
collector.go
71 lines (59 loc) · 1.2 KB
/
collector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"time"
"github.com/julienschmidt/httprouter"
)
type Collector struct {
sync.RWMutex
Keys []string // expvar keys
Data map[string]*ExpvarData // key: url
Interval time.Duration
URLs []string
}
func (c *Collector) Run() {
for {
wg := &sync.WaitGroup{}
for _, url := range c.URLs {
wg.Add(1)
c.CollectExpvar(url, wg)
}
wg.Wait()
time.Sleep(c.Interval)
}
}
func (c *Collector) getResponseJsonData() string {
var ret []byte
var err error
exp := new(ExpvarResponseData)
c.RLock()
defer c.RUnlock()
for _, data := range c.Data {
data.getFlattenData(c.Keys, exp)
ret, err = json.Marshal(exp)
if err != nil {
log.Printf("json encode error!! err: %v", err)
return ""
}
}
return string(ret)
}
func (c *Collector) CollectExpvar(url string, wg *sync.WaitGroup) {
x, err := getExpvarData(url)
if err != nil {
return
}
c.Lock()
c.Data[url] = x
c.Unlock()
wg.Done()
}
func (c *Collector) ServeHTTP(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
ret := c.getResponseJsonData()
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, "%s", ret)
}