1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
package main
import (
"cmp"
"embed"
"io/fs"
"log"
"net/http"
"os"
"strings"
"github.com/joho/godotenv"
)
/* 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) {
path := strings.Trim(r.URL.Path, "/")
if path == "" {
//http.ServeFile(w, r, "static/index.html")
renderIndexTemplate(w)
} else {
renderWatchTemplate(w, path, r.URL.RawQuery) // FIXME just redirect this one to /watch for simplicity
}
}
/* main */
func main() {
// load .env file if it exists
godotenv.Load()
// setup environment
debug = os.Getenv("DEBUG") != ""
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()
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://" + host + ":" + port)
err := http.ListenAndServe(host + ":" + port, mux)
if err != nil {
log.Fatal(err)
}
}
|