homebox/backend/internal/config/conf.go

70 lines
1.6 KiB
Go
Raw Permalink Normal View History

2022-08-30 02:30:36 +00:00
package config
import (
"encoding/json"
"errors"
"fmt"
"github.com/ardanlabs/conf/v2"
"os"
)
const (
ModeDevelopment = "development"
ModeProduction = "production"
)
type Config struct {
Mode string `yaml:"mode" conf:"default:development"` // development or production
Web WebConfig `yaml:"web"`
Storage Storage `yaml:"storage"`
Log LoggerConf `yaml:"logger"`
Mailer MailerConf `yaml:"mailer"`
Swagger SwaggerConf `yaml:"swagger"`
Demo bool `yaml:"demo"`
2022-08-30 02:30:36 +00:00
}
type SwaggerConf struct {
Host string `yaml:"host" conf:"default:localhost:7745"`
Scheme string `yaml:"scheme" conf:"default:http"`
}
type WebConfig struct {
Port string `yaml:"port" conf:"default:7745"`
Host string `yaml:"host"`
MaxUploadSize int64 `yaml:"max_file_upload" conf:"default:10"`
2022-08-30 02:30:36 +00:00
}
2022-10-12 21:03:42 +00:00
// New parses the CLI/Config file and returns a Config struct. If the file argument is an empty string, the
2022-08-30 02:30:36 +00:00
// file is not read. If the file is not empty, the file is read and the Config struct is returned.
2022-10-12 21:03:42 +00:00
func New() (*Config, error) {
2022-08-30 02:30:36 +00:00
var cfg Config
2022-09-14 17:35:23 +00:00
const prefix = "HBOX"
2022-08-30 02:30:36 +00:00
2022-10-12 21:03:42 +00:00
help, err := conf.Parse(prefix, &cfg)
2022-08-30 02:30:36 +00:00
if err != nil {
if errors.Is(err, conf.ErrHelpWanted) {
fmt.Println(help)
os.Exit(0)
}
return &cfg, fmt.Errorf("parsing config: %w", err)
}
return &cfg, nil
}
// Print prints the configuration to stdout as a json indented string
// This is useful for debugging. If the marshaller errors out, it will panic.
func (c *Config) Print() {
res, err := json.MarshalIndent(c, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(res))
}