diff options
Diffstat (limited to 'api')
-rw-r--r-- | api/main.go | 10 | ||||
-rw-r--r-- | api/usage.go | 48 |
2 files changed, 55 insertions, 3 deletions
diff --git a/api/main.go b/api/main.go index 7081d3c..32f7d08 100644 --- a/api/main.go +++ b/api/main.go @@ -1,10 +1,12 @@ package api import ( + "context" "encoding/json" "log" "net" + "sinanmohd.com/redq/db" "sinanmohd.com/redq/usage" ) @@ -40,7 +42,7 @@ func New() (*Api, error) { return &a, nil } -func (a *Api) Run(u *usage.Usage) { +func (a *Api) Run(u *usage.Usage, queries *db.Queries, ctxDb context.Context) { for { conn, err := a.sock.Accept() if err != nil { @@ -48,11 +50,11 @@ func (a *Api) Run(u *usage.Usage) { continue } - go handleConn(conn, u) + go handleConn(conn, u, queries, ctxDb) } } -func handleConn(conn net.Conn, u *usage.Usage) { +func handleConn(conn net.Conn, u *usage.Usage, queries *db.Queries, ctxDb context.Context) { defer conn.Close() var req ApiReq buf := make([]byte, bufSize) @@ -72,6 +74,8 @@ func handleConn(conn net.Conn, u *usage.Usage) { switch req.Type { case "bandwidth": handleBandwidth(conn, u) + case "usage": + handleUsage(conn, u, queries, ctxDb) default: log.Printf("invalid request type: %s", req.Type) } 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) +} |