This repository has been archived on 2024-05-18. You can view files and clone it, but cannot push or open issues or pull requests.
steamServer/cmd/main.go

84 lines
1.7 KiB
Go
Raw Normal View History

2021-09-20 14:57:24 +02:00
package main
import (
"log"
"fmt"
2021-09-20 14:57:24 +02:00
"net/http"
"time"
"io/ioutil"
"encoding/json"
2021-09-20 14:57:24 +02:00
"git.snrd.de/Spaenny/steamServer"
"git.snrd.de/Spaenny/steamServer/postgres"
"git.snrd.de/Spaenny/steamServer/web"
"github.com/robfig/cron/v3"
2021-09-20 14:57:24 +02:00
)
type Server struct {
AppID int `json:"AppID"`
Name string `json:"Name"`
Map string `json:"Map"`
Players int `json:"Players"`
MaxPlayers int `json:"MaxPlayers"`
}
2021-09-20 14:57:24 +02:00
func main() {
dsn := "postgres://postgres:secret@localhost/postgres?sslmode=disable"
store, err := postgres.NewStore(dsn)
if err != nil {
log.Fatal(err)
}
ss, err := store.Servers()
if err != nil {
log.Fatal("There is no server in the list.")
}
for _, s := range ss {
serverString := s.ServerIP
c := cron.New()
c.AddFunc("*/1 * * * *", func() { updateServers(serverString, store) })
c.Start()
}
2021-09-20 14:57:24 +02:00
h := web.NewHandler(store)
http.ListenAndServe(":3000", h)
2021-09-20 14:57:24 +02:00
}
func updateServers(serverString string, store steamServer.Store) {
url := "http://api.spenny.eu/server/" + serverString
reqClient := http.Client {
Timeout: time.Second * 2,
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
res, err := reqClient.Do(req)
if err != nil {
log.Fatal(err)
}
if res.Body != nil {
defer res.Body.Close()
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
server := steamServer.Server{}
json.Unmarshal([]byte(body), &server)
store.UpdateServerByQuery(&server)
fmt.Println(&server)
}