diff options
| author | Tim Keller <tjk@tjkeller.xyz> | 2026-09-22 17:12:59 -0500 |
|---|---|---|
| committer | Tim Keller <tjk@tjkeller.xyz> | 2026-09-22 17:12:59 -0500 |
| commit | 55c7c104c0d548837c510ca831e0f1f29c210323 (patch) | |
| tree | 701d392bad5d866316ca25e1cf5505cb9fc4573c /main.go | |
| parent | 4407433bd31df5526df0dd167d2d9d9d878a09d1 (diff) | |
| download | embedtube-55c7c104c0d548837c510ca831e0f1f29c210323.tar.xz embedtube-55c7c104c0d548837c510ca831e0f1f29c210323.zip | |
use embed fs and add options for host and port + api_key_file
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) } |
