add load and save methods

This commit is contained in:
2025-12-07 02:13:48 +07:00
parent ee76743097
commit 2192bf4e77
2 changed files with 26 additions and 4 deletions
+25 -3
View File
@@ -15,16 +15,38 @@ type StoryService struct {
}
func NewStoryService(filepath string) (*StoryService, error) {
s := &StoryService{}
if err := s.Load(filepath); err != nil {
return nil, err
}
return s, nil
}
func (s *StoryService) Load(filepath string) error {
data, err := os.ReadFile(filepath)
if err != nil {
return nil, fmt.Errorf("story file %s not found", filepath)
return fmt.Errorf("story file %s not found", filepath)
}
log.Printf("load story from: %s", filepath)
story := &Story{}
if err := json.Unmarshal(data, story); err != nil {
return nil, err
return err
}
return &StoryService{story: story}, nil
s.story = story
return nil
}
func (s *StoryService) Save(filepath string) error {
story := s.story
data, err := json.Marshal(story)
if err != nil {
return err
}
if err := os.WriteFile(filepath, data, 0x777); err != nil {
return err
}
log.Printf("save story to: %s", filepath)
return nil
}
func (s *StoryService) GetPlace(code string) *Place {