Files
2026-06-10 18:10:54 +02:00

130 lines
2.9 KiB
Go

package config
import (
"errors"
"os"
"path/filepath"
"mbase/pkg/client"
"go.yaml.in/yaml/v4"
)
const (
defaultHostname = "localhost"
configFilename = "mbased.yaml"
logFilename = "mbased.log"
pidFilename = "mbased.pid"
)
type Networks struct {
Enabled []string `json:"enabled" yaml:"enabled"`
Disabled []string `json:"disabled" yaml:"disabled"`
}
type Service struct {
Portnum uint32 `json:"port" yaml:"port"`
Address string `json:"address" yaml:"address"`
Protocol string `json:"protocol" yaml:"protocol"`
}
type Config struct {
Version string `json:"version" yaml:"version"`
Service Service `json:"service" yaml:"service"`
Networks Networks `json:"networks" yaml:"networks"`
Hostname string `json:"hostname" yaml:"hostname"`
Debug bool `json:"debug" yaml:"debug"`
Build string `json:"build" yaml:"build"`
ConfPath string `json:"conffile" yaml:"conffile"`
LogPath string `json:"logfile" yaml:"logfile"`
RunPath string `json:"runfile" yaml:"runfile"`
DataDir string `json:"datadir" yaml:"datadir"`
AsDaemon bool `json:"asDaemon" yaml:"asDaemon"`
RunUser string `json:"runUser" yaml:"runUser"`
LogLimit int64 `json:"logLimit" yaml:"logLimit"`
}
var (
defaultEnabledNetworks = []string{"0.0.0.0/0", "::/0"}
defaultDisabledNetworks = []string{}
)
const (
defaultServiceAddress = "[::]"
defaultServiceProtocol = "tcp"
)
func NewConfig() *Config {
conf := &Config{
Service: Service{
Portnum: client.DefaultPort,
Address: defaultServiceAddress,
Protocol: defaultServiceProtocol,
},
Networks: Networks{
Enabled: defaultEnabledNetworks,
Disabled: defaultDisabledNetworks,
},
DataDir: datadirPath,
Debug: false,
Hostname: defaultHostname,
Build: packageVersion,
AsDaemon: true,
Version: packageVersion,
LogLimit: 1024 * 1024 * 10, // 10 Mb
RunUser: "daemon",
}
conf.ConfPath = filepath.Join(confdirPath, configFilename)
conf.LogPath = filepath.Join(logdirPath, logFilename)
conf.RunPath = filepath.Join(rundirPath, pidFilename)
return conf
}
func (conf *Config) ReadFile() error {
var err error
confBytes, err := os.ReadFile(conf.ConfPath)
if err != nil {
return err
}
err = yaml.Unmarshal(confBytes, conf)
if err != nil {
return err
}
return nil
}
func (conf *Config) ReadEnv() error {
var err error
return err
}
func (conf *Config) ReadOpts() error {
var err error
return err
}
func (conf *Config) String() (string, error) {
var err error
var res string
yamlBytes, err := yaml.Marshal(conf)
if err != nil {
return res, err
}
res = string(yamlBytes)
return res, err
}
func (conf *Config) Normalize() error {
var err error
if conf.Service.Portnum == 0 {
conf.Service.Portnum = client.DefaultPort
}
return err
}
func (conf *Config) Validate() error {
var err []error
return errors.Join(err...)
}