summaryrefslogtreecommitdiffhomepage
path: root/derelict.go
diff options
context:
space:
mode:
Diffstat (limited to 'derelict.go')
-rw-r--r--derelict.go47
1 files changed, 44 insertions, 3 deletions
diff --git a/derelict.go b/derelict.go
index 2f5e8b3..aac7c10 100644
--- a/derelict.go
+++ b/derelict.go
@@ -4,9 +4,11 @@ import (
"embed"
"github.com/gorilla/mux"
"html/template"
+ "io/ioutil"
"log"
"net/http"
"os"
+ "sort"
)
//go:embed *.json *.css *.js *.svg
@@ -17,24 +19,63 @@ var internal embed.FS
var templates *template.Template
+var root string
+
func main() {
+ initRoot()
+
port := os.Getenv("DERELICTPORT")
if port == "" {
port = "8080"
}
+
templates = template.Must(template.ParseFS(internal, "*.tmpl"))
router := mux.NewRouter()
router.HandleFunc("/", handleRecent).Methods("GET")
- router.HandleFunc("/view", handleView).Queries("id", "{id:[_0-9]+}").Methods("GET")
+ router.HandleFunc("/view/{id:[_0-9]+}", handleView).Methods("GET")
+ router.HandleFunc("/battles/", handleBattlesPost).Methods("POST")
+ router.HandleFunc("/battles/{id:[_0-9]+}", handleBattlesId).Methods("GET")
router.PathPrefix("/").Handler(http.FileServer(http.FS(content)))
+
log.Fatal(http.ListenAndServe(":"+port, router))
}
+func initRoot() {
+ root = os.Getenv("DERELICTROOT")
+ if root == "" {
+ root = ".derelict"
+ }
+ os.Mkdir(root, 0755)
+ os.Mkdir(root+"/battles", 0755)
+}
+
+func handleBattlesPost(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusNotImplemented)
+}
+
+func handleBattlesId(w http.ResponseWriter, r *http.Request) {
+ id := mux.Vars(r)["id"]
+ w.Header().Add("Content-Type", "application/json")
+ http.ServeFile(w, r, root+"/battles/"+id)
+}
+
func handleRecent(w http.ResponseWriter, r *http.Request) {
- templates.ExecuteTemplate(w, "recent", "")
+ files, err := ioutil.ReadDir(root + "/battles")
+ if err != nil {
+ panic(err)
+ }
+ sort.Slice(files, func(lhs, rhs int) bool {
+ return files[lhs].ModTime().After(files[rhs].ModTime())
+ })
+ count := 10
+ if count > len(files) {
+ count = len(files)
+ }
+ templates.ExecuteTemplate(w, "recent", files[:count])
}
func handleView(w http.ResponseWriter, r *http.Request) {
- templates.ExecuteTemplate(w, "view", "")
+ id := mux.Vars(r)["id"]
+ templates.ExecuteTemplate(w, "view", id)
}