diff options
Diffstat (limited to 'api/usage.go')
-rw-r--r-- | api/usage.go | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/api/usage.go b/api/usage.go new file mode 100644 index 0000000..5849ba7 --- /dev/null +++ b/api/usage.go @@ -0,0 +1,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) +} |