diff options
Diffstat (limited to 'main.go')
| -rw-r--r-- | main.go | 49 |
1 files changed, 44 insertions, 5 deletions
@@ -1,6 +1,9 @@ package main import ( + "cmp" + "embed" + "io/fs" "log" "net/http" "os" @@ -8,8 +11,40 @@ import ( "github.com/joho/godotenv" ) -var debug = false +/* environment */ +var debug = false var apiKey = "" +var host = "" +var port = "" + +/* embeded filesystem */ +//go:embed static templates README.md +var embedded embed.FS + +func assetsFS() fs.FS { + if debug { + return os.DirFS(".") + } + return embedded +} + +var Assets = assetsFS() + +/* api key */ +func getAPIKey() { + if path := os.Getenv("API_KEY_FILE"); path != "" { + b, err := os.ReadFile(path) + if err != nil { + log.Fatalf("Failed to read API_KEY_FILE: %v", err) + } + apiKey = strings.TrimSpace(string(b)) + } else { + apiKey = os.Getenv("API_KEY") + } + if apiKey == "" { + log.Println("Warning: neither API_KEY and API_KEY_FILE are set. Endpoints that rely on the API key will return 500") + } +} /* root handler */ func rootHandler(w http.ResponseWriter, r *http.Request) { @@ -26,20 +61,24 @@ func rootHandler(w http.ResponseWriter, r *http.Request) { func main() { // load .env file if it exists godotenv.Load() + // setup environment debug = os.Getenv("DEBUG") != "" - apiKey = os.Getenv("API_KEY") + host = cmp.Or(os.Getenv("HOST"), "127.0.0.1") + port = cmp.Or(os.Getenv("PORT"), "8080") + getAPIKey() // setup routes mux := http.NewServeMux() registerRoutesAPI(mux, &APISourceOfficial{}) registerRoutesWatch(mux) setupHome() - mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) + static, _ := fs.Sub(Assets, "static") + mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(static)))) mux.HandleFunc("/", rootHandler) // start http server - log.Println("Listening on http://localhost:8080") - err := http.ListenAndServe(":8080", mux) + log.Println("Listening on http://" + host + ":" + port) + err := http.ListenAndServe(host + ":" + port, mux) if err != nil { log.Fatal(err) } |
