/
stats.go
48 lines (41 loc) · 1.17 KB
/
stats.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
// Copyright (c) 2012-2016 Eli Janssen
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package stats
import (
"fmt"
"net/http"
"sync/atomic"
)
// ProxyStats is the counter container
type ProxyStats struct {
clients uint64
bytes uint64
}
// AddServed increments the number of clients served counter
func (ps *ProxyStats) AddServed() {
atomic.AddUint64(&ps.clients, 1)
}
// AddBytes increments the number of bytes served counter
func (ps *ProxyStats) AddBytes(bc int64) {
if bc <= 0 {
return
}
atomic.AddUint64(&ps.bytes, uint64(bc))
}
// GetStats returns the stats: clients, bytes
func (ps *ProxyStats) GetStats() (uint64, uint64) {
psClients := atomic.LoadUint64(&ps.clients)
psBytes := atomic.LoadUint64(&ps.bytes)
return psClients, psBytes
}
// Handler returns an http.HandlerFunc that returns running totals and
// stats about the server.
func Handler(ps *ProxyStats) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(200)
c, b := ps.GetStats()
fmt.Fprintf(w, "ClientsServed, BytesServed\n%d, %d\n", c, b)
}
}