diff --git a/README.md b/README.md index eaabf20..4de0ebe 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,6 @@ Website to show home server infrastructure up/down indicators ## Build and run ```sh -$ go build main.go -$ go run main.go +$ go build main.go functions.go +$ ./main ``` diff --git a/main.go b/main.go index c24d614..0d9c66b 100644 --- a/main.go +++ b/main.go @@ -1,9 +1,11 @@ package main import ( + "flag" "fmt" "log" "net/http" + "os" ) type WebsiteStatus struct { @@ -13,19 +15,88 @@ type WebsiteStatus struct { IconURL string } +type Config struct { + Mode string + WebsiteConfFile string + ListenAddress string + Port int + Verbose bool +} + +var config Config + func main() { - websites, err := readWebsitesFromFile("websites.conf") + config = parseFlags() + + if config.Verbose { + fmt.Printf("Reading websites from file %s", config.WebsiteConfFile) + } + + websites, err := readWebsitesFromFile(config.WebsiteConfFile) + if err != nil { log.Fatal(err) } + runWebsite(fmt.Sprintf("%s:%d", config.ListenAddress, config.Port), websites) +} + +func parseFlags() Config { + // Define command-line flags + websiteConfFileFlag := flag.String("config", "websites.conf", "Path to the config file") + verboseFlag := flag.Bool("verbose", false, "Enable verbose mode") + listenAddressFlag := flag.String("address", "localhost", "The address the server will listen on") + portFlag := flag.Int("port", 8080, "The port the server will listen on") + modeFlag := flag.String("mode", "server", "The mode the program will run in. Options are \"cmd\" and \"server\"") + + // Parse command-line flags + flag.Parse() + + // Access the parsed values + config := Config{ + WebsiteConfFile: *websiteConfFileFlag, + Verbose: *verboseFlag, + ListenAddress: *listenAddressFlag, + Port: *portFlag, + Mode: *modeFlag, + } + + success := true + + // Check if the config file exists + if _, err := os.Stat(config.WebsiteConfFile); os.IsNotExist(err) { + success = false + fmt.Printf("File '%s' does not exist\n", config.WebsiteConfFile) + } + + if config.Port < 0 || config.Port > 65535 { + success = false + fmt.Printf("Port '%d' is out of range for a port, must be between 0 and 65535\n", config.Port) + } + + if config.Mode != "cmd" && config.Mode != "server" { + success = false + fmt.Printf("Mode has to be either cmd or server, but was '%s'\n", config.Mode) + } + + if !success { + fmt.Printf("Config error(s), aborting...\n") + os.Exit(1) + } + + return config +} + +func runWebsite(url string, websites []WebsiteStatus) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { renderTemplate(w, websites) }) http.HandleFunc("/check", handleCheck) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) - fmt.Println("Server listening on http://localhost:8080") + if config.Verbose { + fmt.Println("Server listening on ", url) + } - log.Fatal(http.ListenAndServe(":8080", nil)) + log.Fatal(http.ListenAndServe(url, nil)) }