Basic REST app
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type GlobalConfig struct {
|
||||
Token string `yaml:"token"`
|
||||
GithubPat string `yaml:"github_pat"`
|
||||
StoragePath string `yaml:"storage_path"`
|
||||
}
|
||||
|
||||
type SiteConfig struct {
|
||||
Repo string `yaml:"repo"`
|
||||
Owner string `yaml:"owner"`
|
||||
Branch string `yaml:"branch"`
|
||||
Domain string `yaml:"domain"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Global GlobalConfig `yaml:"global"`
|
||||
Sites []SiteConfig `yaml:"sites"`
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Field string
|
||||
Message string
|
||||
}
|
||||
|
||||
func (c Error) Error() string {
|
||||
return "Config error: " + c.Field + " - " + c.Message
|
||||
}
|
||||
|
||||
func validateConfig(config *Config) error {
|
||||
if config.Global.Token == "" {
|
||||
return &Error{Field: "global.token", Message: "Token is required"}
|
||||
}
|
||||
if config.Global.GithubPat == "" {
|
||||
return &Error{Field: "global.github_pat", Message: "GitHub PAT is required"}
|
||||
}
|
||||
if config.Global.StoragePath == "" {
|
||||
return &Error{Field: "global.storage_path", Message: "Storage path is required"}
|
||||
}
|
||||
for i, site := range config.Sites {
|
||||
if site.Repo == "" {
|
||||
return &Error{Field: "sites[" + string(i) + "].repo", Message: "Repo is required"}
|
||||
}
|
||||
if site.Owner == "" {
|
||||
return &Error{Field: "sites[" + string(i) + "].owner", Message: "Owner is required"}
|
||||
}
|
||||
if site.Branch == "" {
|
||||
return &Error{Field: "sites[" + string(i) + "].branch", Message: "Branch is required"}
|
||||
}
|
||||
if site.Domain == "" {
|
||||
return &Error{Field: "sites[" + string(i) + "].domain", Message: "Domain is required"}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
f, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
expanded := os.Expand(string(f), os.Getenv)
|
||||
var config Config
|
||||
err = yaml.Unmarshal([]byte(expanded), &config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = validateConfig(&config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
Reference in New Issue
Block a user