103 lines
2.4 KiB
Go
Raw Normal View History

package main
2023-06-02 04:32:10 +02:00
import (
2023-06-02 16:30:52 +02:00
"flag"
2023-06-02 04:32:10 +02:00
"fmt"
"log"
"net/http"
2023-06-02 16:30:52 +02:00
"os"
2023-06-02 04:32:10 +02:00
)
type WebsiteStatus struct {
2023-06-02 15:47:33 +02:00
WebsiteURL string
2023-06-02 04:32:10 +02:00
Description string
HasIcon bool
2023-06-02 15:47:33 +02:00
IconURL string
2023-06-02 04:32:10 +02:00
}
2023-06-02 16:30:52 +02:00
type Config struct {
Mode string
WebsiteConfFile string
ListenAddress string
Port int
Verbose bool
}
var config Config
2023-06-02 04:32:10 +02:00
func main() {
2023-06-02 16:30:52 +02:00
config = parseFlags()
if config.Verbose {
fmt.Printf("Reading websites from file %s", config.WebsiteConfFile)
}
websites, err := readWebsitesFromFile(config.WebsiteConfFile)
2023-06-02 15:47:33 +02:00
if err != nil {
log.Fatal(err)
2023-06-02 04:32:10 +02:00
}
2023-06-02 16:30:52 +02:00
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) {
2023-06-02 04:32:10 +02:00
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, websites)
2023-06-02 04:32:10 +02:00
})
http.HandleFunc("/check", handleCheck)
2023-06-02 04:32:10 +02:00
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
2023-06-02 16:30:52 +02:00
if config.Verbose {
fmt.Println("Server listening on ", url)
}
2023-06-02 16:30:52 +02:00
log.Fatal(http.ListenAndServe(url, nil))
2023-06-02 04:32:10 +02:00
}