speed-tester/main.go

81 lines
1.5 KiB
Go

package main
import (
"embed"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/showwin/speedtest-go/speedtest"
"gitea.zokki.net/zokki/speed-tester/database"
"gitea.zokki.net/zokki/speed-tester/flag"
"gitea.zokki.net/zokki/speed-tester/routes"
)
var isDev = strings.ToUpper(os.Getenv("ENVIRONMENT")) == "DEVELOPMENT"
//go:embed assets
var assetFS embed.FS
func main() {
defer database.DB.Close()
ticker := time.NewTicker(300 * time.Second)
quit := make(chan struct{})
go func() {
for {
select {
case <-ticker.C:
testInternet()
case <-quit:
ticker.Stop()
return
}
}
}()
router := http.NewServeMux()
router.HandleFunc("/", routes.Routes())
if isDev {
router.Handle("/assets/", http.StripPrefix("/assets", http.FileServer(http.Dir("assets"))))
} else {
router.Handle("/assets/", http.FileServer(http.FS(assetFS)))
}
server := http.Server{
Addr: fmt.Sprintf(":%d", *flag.Port),
Handler: router,
}
log.Fatal("listen and serve", server.ListenAndServe())
}
func testInternet() {
serverList, err := speedtest.New().FetchServers()
if database.CheckError("fetch servers", err) {
return
}
targets, err := serverList.FindServer([]int{})
if database.CheckError("find server", err) {
return
}
server := targets[0]
if database.CheckError("ping", server.PingTest(nil)) {
return
}
if database.CheckError("download", server.DownloadTest()) {
return
}
if database.CheckError("upload", server.UploadTest()) {
return
}
database.InsertServer(server)
}