gibcasa/main.go

80 lines
2.1 KiB
Go
Raw Permalink Normal View History

package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os/exec"
"syscall"
)
var serverCmd *exec.Cmd
func startServer(w http.ResponseWriter, r *http.Request) {
if serverCmd != nil {
fmt.Fprintln(w, "Server is already running.")
return
}
serverCmd = exec.Command("/opt/hl2dm/Steam/hl2dm/srcds_run", "-game", "hl2mp", "+map", "dm_lockdown", "+maxplayers", "16")
serverCmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // Allow stopping the entire process group
if err := serverCmd.Start(); err != nil {
log.Println("Error starting server:", err)
http.Error(w, "Failed to start server", http.StatusInternalServerError)
return
}
fmt.Fprintln(w, "Server started with PID", serverCmd.Process.Pid)
}
func stopServer(w http.ResponseWriter, r *http.Request) {
if serverCmd == nil {
fmt.Fprintln(w, "Server is not running.")
return
}
if err := syscall.Kill(-serverCmd.Process.Pid, syscall.SIGKILL); err != nil {
log.Println("Error stopping server:", err)
http.Error(w, "Failed to stop server", http.StatusInternalServerError)
return
}
serverCmd = nil
fmt.Fprintln(w, "Server stopped.")
}
func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
// Define routes
http.HandleFunc("/", homeHandler)
http.HandleFunc("/hl2", hl2Handler)
http.HandleFunc("/quake", quakeHandler)
http.HandleFunc("/start", startServer)
http.HandleFunc("/stop", stopServer)
// http.HandleFunc("/restart", restartServer)
// Start the server
fmt.Println("Server running on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
// Render the homepage
func homeHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/index.xhtml"))
tmpl.Execute(w, nil)
}
// Render the Half-Life 2 page
func hl2Handler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/hl2.xhtml"))
tmpl.Execute(w, nil)
}
// Render the Quake page
func quakeHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/quake.xhtml"))
tmpl.Execute(w, nil)
}