bbj2/server/cmd/config/config.go

77 lines
1.3 KiB
Go
Raw Normal View History

2022-06-01 03:27:55 +00:00
package config
2022-04-11 03:59:26 +00:00
import (
2022-06-01 03:27:55 +00:00
"database/sql"
2022-04-11 03:59:26 +00:00
"fmt"
2022-06-01 03:27:55 +00:00
"io"
2022-06-14 17:44:03 +00:00
"log"
2022-04-11 03:59:26 +00:00
"os"
yaml "gopkg.in/yaml.v3"
)
const (
defaultPort = 7099
defaultInstanceName = "BBJ"
defaultHost = "127.0.0.1"
2022-04-12 20:33:13 +00:00
defaultDBPath = "db.sqlite3"
2022-04-11 03:59:26 +00:00
)
2022-06-01 03:27:55 +00:00
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
2022-06-14 17:44:03 +00:00
Logger *log.Logger
2022-06-01 03:27:55 +00:00
Log func(string)
Logf func(string, ...interface{})
Config Config
DB *sql.DB
Reset bool
}
func ParseConfig(configPath string) (*Config, error) {
2022-04-11 03:59:26 +00:00
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
}
2022-04-12 20:33:13 +00:00
if cfg.DBPath == "" {
cfg.DBPath = defaultDBPath
}
2022-04-11 03:59:26 +00:00
return &cfg, nil
}