summaryrefslogtreecommitdiffhomepage
path: root/storage.go
diff options
context:
space:
mode:
Diffstat (limited to 'storage.go')
-rw-r--r--storage.go51
1 files changed, 51 insertions, 0 deletions
diff --git a/storage.go b/storage.go
new file mode 100644
index 0000000..ec2d33e
--- /dev/null
+++ b/storage.go
@@ -0,0 +1,51 @@
+package main
+
+import (
+ "crypto/sha1"
+ "encoding/hex"
+ "io/ioutil"
+ "net/http"
+ "os"
+ "sort"
+)
+
+type Storage struct {
+ Path string
+}
+
+func (s *Storage) MustInit() error {
+ os.Mkdir(s.Path, 0755)
+ os.Mkdir(s.Path+"/battles", 0755)
+ os.Mkdir(s.Path+"/tokens", 0700)
+ return nil
+}
+
+func (s *Storage) AddBattle(data []byte) (string, error) {
+ hash := sha1.Sum(data)
+ id := hex.EncodeToString(hash[:])
+ return id, ioutil.WriteFile(s.Path+"/battles/"+id, data, 0644)
+}
+
+func (s *Storage) ServeBattle(id string, w http.ResponseWriter, r *http.Request) {
+ w.Header().Add("Content-Type", "application/json")
+ http.ServeFile(w, r, s.Path+"/battles/"+id)
+}
+
+func (s *Storage) ListRecentBattles(count int) ([]Battle, error) {
+ files, err := ioutil.ReadDir(s.Path + "/battles")
+ if err != nil {
+ return nil, err
+ }
+
+ sort.Slice(files, func(lhs, rhs int) bool {
+ return files[lhs].ModTime().After(files[rhs].ModTime())
+ })
+
+ battles := make([]Battle, 0, count)
+
+ for i := 0; i < count && i < len(files); i++ {
+ battles = append(battles, Battle{Id: files[i].Name(), Date: files[i].ModTime()})
+ }
+
+ return battles, nil
+}