summaryrefslogtreecommitdiff
path: root/api/usage.go
blob: 5849ba72a033baed631f2de7d5b1158edffb744f (plain) (blame)
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
package api

import (
	"context"
	"encoding/json"
	"log"
	"net"

	"github.com/dustin/go-humanize"
	"sinanmohd.com/redq/db"
	"sinanmohd.com/redq/usage"
)

type UsageStat struct {
	Ingress string `json:"ingress"`
	Egress  string `json:"egress"`
}

type UsageResp map[string]UsageStat

func handleUsage(conn net.Conn, u *usage.Usage, queries *db.Queries, ctxDb context.Context) {
	resp := make(UsageResp)

	fetchedUsage, err := queries.GetUsage(ctxDb)
	if err != nil {
		log.Printf("fetching from database: %s", err)
		return
	}

	u.Mutex.RLock()
	for _, value := range u.Data {
		fetchedUsage.Ingress += int64(value.Ingress)
		fetchedUsage.Egress += int64(value.Egress)
	}
	u.Mutex.RUnlock()
	resp["total"] = UsageStat{
		Ingress: humanize.Bytes(uint64(fetchedUsage.Ingress)),
		Egress:  humanize.Bytes(uint64(fetchedUsage.Egress)),
	}

	buf, err := json.Marshal(resp)
	if err != nil {
		log.Printf("marshaling json: %s", err)
		return
	}

	conn.Write(buf)
}