A simple server for serving our SpaceAPI interactively.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

64 lines
1.2 KiB

package spaceapi
import (
"encoding/json"
"fmt"
"os"
)
type Listener func(old, new SpaceStatus)
type Storage struct {
filePath string
status SpaceStatus
listeners []Listener
}
func Open(filePath string) (*Storage, error) {
status, err := readFile(filePath)
if err != nil {
return nil, fmt.Errorf("error reading status: %s", err)
}
return &Storage{
filePath: filePath,
status: *status,
}, nil
}
func (s *Storage) Status() SpaceStatus {
return s.status
}
func (s *Storage) Modify(modifiers ...func(*SpaceStatus)) {
old := s.status
for _, m := range modifiers {
m(&s.status)
}
s.notify(old, s.status)
}
func (s *Storage) AddListener(l Listener) {
s.listeners = append(s.listeners, l)
}
func (s *Storage) notify(old, new SpaceStatus) {
for _, l := range s.listeners {
l(old, new)
}
}
func readFile(fileName string) (*SpaceStatus, error) {
file, err := os.Open(fileName)
if err != nil {
return nil, fmt.Errorf("error opening file: %s", err)
}
defer file.Close()
var status SpaceStatus
if err := json.NewDecoder(file).Decode(&status); err != nil {
return nil, fmt.Errorf("error decoding state: %s", err)
}
return &status, nil
}