-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
94 lines (77 loc) · 2.4 KB
/
http.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
91
92
93
94
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"github.com/gorilla/mux"
)
func NewFileLoader() *FileLoader {
router := new(mux.Router)
addRoutes(router)
return &FileLoader{
Router: router,
}
}
func (h *FileLoader) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.Router.ServeHTTP(w, r)
}
func addRoutes(router *mux.Router) {
router.HandleFunc("/api/sprites", handleGetSpriteData).Methods("GET")
router.HandleFunc("/api/sprites/{spriteType}/{fileName}", handleGetSprite).Methods("GET")
router.HandleFunc("*", handleServeFile).Methods("GET")
}
func handleGetSpriteData(w http.ResponseWriter, r *http.Request) {
sd, err := makeSpriteData()
if err != nil {
writeJSON(w, http.StatusInternalServerError, ServerError{Error: "error getting sprite data: " + err.Error()})
return
}
writeJSON(w, http.StatusOK, sd)
}
// Check if this sprite exists in the modded-sprites os file system, and if so serve it.
// If not, serve the original from the embedded file system.
func handleGetSprite(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
spriteType := mux.Vars(r)["spriteType"]
fileName := mux.Vars(r)["fileName"]
filePath := "modded-sprites/" + spriteType + "/" + fileName
fileData, err := os.ReadFile(filePath)
if err != nil {
fd, err := assets.ReadFile("frontend/dist/sprites/" + spriteType + "/" + fileName)
if err != nil {
w.WriteHeader(http.StatusNotFound)
} else {
fileData = fd
}
}
w.Write(fileData)
}
// If the file exists in the os file system, serve it.
// If not check if it exists in the embedded file system, and if so serve it.
// Else, write bad request.
func handleServeFile(w http.ResponseWriter, r *http.Request) {
requestedFilename := strings.TrimPrefix(r.URL.Path, "/")
println("Requesting file:", requestedFilename)
var fileData = make([]byte, 0)
fileData, err := os.ReadFile(requestedFilename)
if err != nil {
fd, err := assets.ReadFile(requestedFilename)
if err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(fmt.Sprintf("Could not load file %s", requestedFilename)))
} else {
fileData = fd
}
}
w.Write(fileData)
}
func writeJSON(w http.ResponseWriter, status int, v any) error {
w.Header().Set(HTTPHeaderContentType, ContentTypeApplicationJSON)
w.WriteHeader(status)
return json.NewEncoder(w).Encode(v)
}
func SegmentPath(path string) []string {
return strings.Split(path, "/")
}