From d6226a4a928a386a29e173f7516e3c3d09681dc0 Mon Sep 17 00:00:00 2001 From: Aki Date: Sat, 24 Apr 2021 02:49:54 +0200 Subject: Moved storage handling to another file --- storage.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 storage.go (limited to 'storage.go') 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 +} -- cgit v1.1