bbj2/server/cmd/config/config.go

77 lines
1.3 KiB
Go

package config
import (
"database/sql"
"fmt"
"io"
"log"
"os"
yaml "gopkg.in/yaml.v3"
)
const (
defaultPort = 7099
defaultInstanceName = "BBJ"
defaultHost = "127.0.0.1"
defaultDBPath = "db.sqlite3"
)
type IOStreams struct {
Err io.Writer
Out io.Writer
}
type Config struct {
Admins []string
Port int
Host string
InstanceName string `yaml:"instance_name"`
AllowAnon bool `yaml:"allow_anon"`
Debug bool
DBPath string `yaml:"db_path"`
}
type Options struct {
ConfigPath string
IO IOStreams
Logger *log.Logger
Log func(string)
Logf func(string, ...interface{})
Config Config
DB *sql.DB
Reset bool
}
func ParseConfig(configPath string) (*Config, error) {
cfgBytes, err := os.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %w", err)
}
var cfg Config
if err := yaml.Unmarshal(cfgBytes, &cfg); err != nil {
return nil, fmt.Errorf("failed to parse config: %w", err)
}
if cfg.Port == 0 {
cfg.Port = defaultPort
}
if cfg.InstanceName == "" {
cfg.InstanceName = defaultInstanceName
}
if cfg.Host == "" {
cfg.Host = defaultHost
}
if cfg.DBPath == "" {
cfg.DBPath = defaultDBPath
}
return &cfg, nil
}