ministream/server/config.go

80 lines
1.2 KiB
Go
Raw Normal View History

2023-12-04 23:45:43 +00:00
package server
import (
"io"
"os"
"github.com/pelletier/go-toml/v2"
)
type Config struct {
2023-12-05 00:15:09 +00:00
SiteName string `toml:"siteName"`
HTTP ConfigHTTP `toml:"http"`
}
type ConfigHTTP struct {
ListenAddr string `json:"ListenAddr" toml:"ListenAddr"`
2023-12-04 23:45:43 +00:00
}
func DefaultConfig() *Config {
return &Config{
2023-12-05 00:15:09 +00:00
SiteName: "ministream",
HTTP: ConfigHTTP{
ListenAddr: ":8080",
},
2023-12-04 23:45:43 +00:00
}
}
func (c *Config) OverrideFromEnv() {
if siteName, ok := os.LookupEnv("MINISTREAM_SITENAME"); ok {
c.SiteName = siteName
}
2023-12-05 00:15:09 +00:00
if httpAddr, ok := os.LookupEnv("MINISTREAM_HTTP_LISTENADDR"); ok {
c.HTTP.ListenAddr = httpAddr
2023-12-04 23:45:43 +00:00
}
}
func ConfigFromReader(r io.Reader) (*Config, error) {
var c Config
err := toml.NewDecoder(r).Decode(&c)
if err != nil {
return nil, err
}
return &c, nil
}
func ConfigFromFile(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return ConfigFromReader(f)
}
func ConfigFromDefault() (*Config, error) {
var config *Config
defaultPaths := []string{
"ministream.toml",
}
for _, p := range defaultPaths {
c, err := ConfigFromFile(p)
if err != nil {
continue
}
config = c
break
}
if config == nil {
config = DefaultConfig()
}
return config, nil
}