tins2020/resourceloader.go

54 lines
1.1 KiB
Go

package tins2020
import (
"bufio"
"fmt"
"strings"
"opslag.de/schobers/zntg/ui"
)
type ResourceLoader struct {
Resources map[string]string
}
func NewResourceLoader() *ResourceLoader {
return &ResourceLoader{}
}
func (l *ResourceLoader) parseResourcesFile(res ui.Resources, name string) error {
f, err := res.OpenResource(name)
if err != nil {
return err
}
defer f.Close()
l.Resources = map[string]string{}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
definition := scanner.Text()
sep := strings.Index(definition, ":")
if sep == -1 {
continue
}
name := strings.TrimSpace(definition[:sep])
content := strings.TrimSpace(definition[sep+1:])
l.Resources[name] = content
}
return nil
}
func (l *ResourceLoader) LoadFromFile(res ui.Resources, name string, action func(string, string) error) error {
err := l.parseResourcesFile(res, name)
if err != nil {
return err
}
for name, content := range l.Resources {
err = action(name, content)
if err != nil {
return fmt.Errorf("cannot load resource '%s'; error: %v", name, err)
}
}
return nil
}