-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (74 loc) · 2.24 KB
/
main.go
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
86
87
88
89
90
package main
import (
"encoding/json"
"path/filepath"
"rico-vz/SaltyBet-Glicko2Bot/bot"
"rico-vz/SaltyBet-Glicko2Bot/db"
_ "rico-vz/SaltyBet-Glicko2Bot/glicko"
"strings"
"net/http"
"github.com/charmbracelet/log"
"github.com/joho/godotenv"
)
func envLoad() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
func htmlFileHandler(root http.FileSystem) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the request path ends with "/" or has no extension, assume it's an HTML file
if strings.HasSuffix(r.URL.Path, "/") || filepath.Ext(r.URL.Path) == "" {
// Try serving the path with .html extension
htmlPath := r.URL.Path + ".html"
if _, err := root.Open(htmlPath); err == nil {
r.URL.Path = htmlPath
}
}
// Serve the file (or directory) from the root FileSystem
http.FileServer(root).ServeHTTP(w, r)
})
}
func startFrontend() {
log.Info("[FE] Starting Frontend")
log.Info("[FE] Listening on http://127.0.0.1:5807/")
http.Handle("/", http.StripPrefix("/", htmlFileHandler(http.Dir("./views"))))
http.Handle("/bet_results.json", http.FileServer(http.Dir("./")))
// /api/characters returns db.GetAllCharacters()
http.HandleFunc("/api/characters", func(w http.ResponseWriter, r *http.Request) {
characters, err := db.GetAllCharacters()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
charactersBytes, err := json.Marshal(characters)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(charactersBytes)
})
// /api/botstate returns bot.GetBotState()
http.HandleFunc("/api/botstate", func(w http.ResponseWriter, r *http.Request) {
botState := bot.GetBotState()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
botStateBytes, err := json.Marshal(botState)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(botStateBytes)
})
http.ListenAndServe(":5807", nil)
}
func main() {
envLoad()
db.InitializeDB("db/characters.db")
defer db.CloseDB()
go startFrontend()
bot.RunBot()
}