From cd90a16071475dbc67a76c04f0bebf90db9da4e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philipp=20B=C3=B6hm?= Date: Mon, 20 Sep 2021 12:15:44 +0200 Subject: [PATCH] first push --- go.mod | 5 +++++ go.sum | 2 ++ main.go | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..1cbc1e0 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module git.snrd.de/Spaenny/a2s-steam-server + +go 1.17 + +require github.com/rumblefrog/go-a2s v1.0.1 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..fa87b9b --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/rumblefrog/go-a2s v1.0.1 h1:0M4QUDB1Tz00tCz36r/AWB4YFO2ajksvPnd7Abzz9SE= +github.com/rumblefrog/go-a2s v1.0.1/go.mod h1:JwbTgMTRGZcWzr3T2MUfDusrJU5Bdg8biEeZzPtN0So= diff --git a/main.go b/main.go new file mode 100644 index 0000000..580e6dc --- /dev/null +++ b/main.go @@ -0,0 +1,67 @@ +package main + +import ( + "fmt" + "log" + "bytes" + "net/http" + "net/url" + "strings" + "runtime" + + "github.com/rumblefrog/go-a2s" + "encoding/json" +) + +func newServerQuerier(host string) ([]byte, error) { + client, err := a2s.NewClient(host) + + if err != nil { + log.Printf("Creation of client failed: %s", err) + } + + defer client.Close() + + info, err := client.QueryInfo() + + if err != nil { + log.Printf("Querying failed: %s", err) + return []byte("\"error\": \"1\""), nil + } + + log.Printf("%s - %s\n", host, info.Name) + + buf, err := json.Marshal(info) + + var indented bytes.Buffer + json.Indent(&indented, buf, "\t", "\t") + + return []byte(indented.String()), err +} + +func Log(handler http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + log.Printf("access: %s %s %s", r.RemoteAddr, r.Method, r.URL) + handler.ServeHTTP(w, r) + }) +} + +func httpServer(w http.ResponseWriter, r *http.Request) { + uriSegments := strings.Split(r.URL.String(), "/") + host, _ := url.QueryUnescape(uriSegments[2]) + + var info, err = newServerQuerier(host) + if err != nil { + log.Printf("Got an error while receiving data: %s", err) + } + + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + fmt.Fprintf(w, "%s", info) +} + +func main() { + runtime.GOMAXPROCS(runtime.NumCPU()) + + http.HandleFunc("/server/", httpServer) + log.Fatal(http.ListenAndServe(":8080", Log(http.DefaultServeMux))) +}