Add RCON connection

This commit is contained in:
Chandler Swift 2020-03-19 23:40:23 -05:00
parent e6cc669333
commit f60c7a15bc

View file

@ -4,7 +4,10 @@ import (
"flag" "flag"
"fmt" "fmt"
"html/template" "html/template"
"log"
"net/http" "net/http"
"github.com/james4k/rcon"
) )
type serverData struct { type serverData struct {
@ -15,8 +18,10 @@ type serverData struct {
func main() { func main() {
port := flag.Int("port", 65536, "Port on which the HTTP server should serve") port := flag.Int("port", 65536, "Port on which the HTTP server should serve (required)")
server := flag.String("serverAddr", "factorio.blackolivepineapple.pizza", "Server to check status of") serverAddr := flag.String("serverAddr", "factorio.blackolivepineapple.pizza", "Server to check status of (optional, defaults to factorio.bopp")
serverPort := flag.Int("serverport", 34196, "RCON port on the Factorio server")
password := flag.String("password", "", "RCON password of the server (required)")
flag.Parse() flag.Parse()
if *port < 1 || *port > 65535 { if *port < 1 || *port > 65535 {
@ -24,19 +29,42 @@ func main() {
return return
} }
if *password == "" {
fmt.Printf("Password flag is required")
}
fmt.Print("Parsing templates...\n") fmt.Print("Parsing templates...\n")
t, err := template.ParseFiles("templates/index.html") t, err := template.ParseFiles("templates/index.html")
if err != nil { if err != nil {
fmt.Printf("Error parsing HTML template: %v\n", err) fmt.Printf("Error parsing HTML template: %v\n", err)
} }
data := serverData{ rconConnection, err := rcon.Dial(fmt.Sprintf("%v:%v", *serverAddr, *serverPort), *password)
*server, if err != nil {
"bopp server", log.Fatalf("Error making RCON connection: %v", err)
"none",
} }
defer rconConnection.Close()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, err := rconConnection.Write("/players o")
if err != nil {
fmt.Print(w, "Error connecting to server")
return
}
playersOnline, _, err := rconConnection.Read()
if err != nil {
fmt.Print(w, "Error receiving data from server")
return
}
data := serverData{
*serverAddr,
"Server with Bob's Mod, est. Feb 2020",
playersOnline,
}
t.Execute(w, data) t.Execute(w, data)
}) })