Skip to content

Commit

Permalink
feat(go): rewrite in go
Browse files Browse the repository at this point in the history
  • Loading branch information
debemdeboas committed Feb 27, 2024
1 parent f6881b0 commit ab80232
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 70 deletions.
15 changes: 8 additions & 7 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
FROM python:3.11-slim
FROM golang:1.22-bookworm

ENV DEBIAN_FRONTEND=noninteractive

RUN apt update && apt install -y \
curl \
gnupg

RUN curl -s https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh | bash
RUN apt install -y speedtest && rm -rf /var/lib/apt/lists/*

EXPOSE 80

WORKDIR /app
COPY speedtest.py /app/

CMD ["python", "speedtest.py"]
COPY go.mod ./
RUN go mod download

COPY *.go ./

RUN CGO_ENABLED=0 GOOS=linux go build -o /speedtest
CMD ["/speedtest"]
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module debem.dev/speedtest

go 1.22
84 changes: 84 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package main

import (
"encoding/json"
"fmt"
"net/http"
"os/exec"
"sync"
"time"
)

type Container struct {
mu sync.Mutex
result *SpeedtestResult
}

func (c *Container) Set(result *SpeedtestResult) {
c.mu.Lock()
defer c.mu.Unlock()
c.result = result
}

func (c *Container) Get() *SpeedtestResult {
c.mu.Lock()
defer c.mu.Unlock()

if c.result == nil {
return &SpeedtestResult{
Download: 0,
Upload: 0,
Ping: 0,
Timestamp: time.Now().UTC().Format(time.RFC3339),
}
}

return c.result
}

type SpeedtestResult struct {
Download float64 `json:"download"`
Upload float64 `json:"upload"`
Ping float64 `json:"ping"`
Timestamp string `json:"timestamp"`
}

func NewSpeedtestResult() *SpeedtestResult {
cmd := exec.Command("speedtest", "--accept-license", "--accept-gdpr", "-fjson")
// Read output
stdout, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
panic(err)
}
var output map[string]any
if err := json.Unmarshal(stdout, &output); err != nil {
fmt.Println(err)
panic(err)
}

return &SpeedtestResult{
Download: output["download"].(map[string]any)["bandwidth"].(float64),
Upload: output["upload"].(map[string]any)["bandwidth"].(float64),
Ping: output["ping"].(map[string]any)["latency"].(float64),
Timestamp: output["timestamp"].(string),
}
}

func main() {
c := &Container{}
go func() {
for {
result := NewSpeedtestResult()
c.Set(result)
time.Sleep(5 * time.Minute)
}
}()

http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
result := c.Get()
json.NewEncoder(w).Encode(result)
})

http.ListenAndServe(":80", nil)
}
63 changes: 0 additions & 63 deletions speedtest.py

This file was deleted.

0 comments on commit ab80232

Please sign in to comment.