evening_detective/internal/services/story_service/service.go

55 lines
1.0 KiB
Go

package story_service
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
)
type Story struct {
Places []*Place `json:"places"`
}
type Place struct {
Code string `json:"code"`
Text string `json:"text"`
Applications []*Application `json:"applications"`
}
type Application struct {
Name string `json:"name"`
}
type StoryService struct {
story *Story
}
func NewStoryService() (*StoryService, error) {
data, err := os.ReadFile("./story/story.json")
if err != nil {
return nil, err
}
story := &Story{}
if err := json.Unmarshal(data, story); err != nil {
return nil, err
}
return &StoryService{story: story}, nil
}
func (s *StoryService) GetPlace(code string) (*Place, error) {
code = clearCode(code)
for _, place := range s.story.Places {
if clearCode(place.Code) == code {
return place, nil
}
}
return nil, errors.New(fmt.Sprintf("place not found: %s", code))
}
func clearCode(code string) string {
code = strings.ToLower(code)
return strings.ReplaceAll(code, "-", "")
}