sensenet/config/config.go

76 lines
1.4 KiB
Go
Raw Permalink Normal View History

2022-02-27 06:57:13 +00:00
package config
import (
2022-02-27 10:10:21 +00:00
"context"
"fmt"
2022-02-27 06:57:13 +00:00
"io/ioutil"
2022-02-27 10:10:21 +00:00
"github.com/jackc/pgx/v4/pgxpool"
2022-02-27 06:57:13 +00:00
"gopkg.in/yaml.v3"
)
2022-02-27 10:10:21 +00:00
const (
defaultPort = 4000
2022-02-27 10:31:02 +00:00
defaultProto = "tcp"
2022-02-27 10:10:21 +00:00
)
2022-02-27 06:57:13 +00:00
type Database struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Name string `yaml:"name"`
User string `yaml:"user"`
Password string `yaml:"password"`
}
2022-02-27 10:10:21 +00:00
func (db Database) Connect(ctx context.Context) (*pgxpool.Pool, error) {
if db.Port == 0 {
db.Port = 5432
}
connstr := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=verify-full",
db.User, db.Password, db.Host, db.Port, db.Name)
return pgxpool.Connect(ctx, connstr)
}
2022-02-27 06:57:13 +00:00
type Publisher struct {
2022-02-27 10:10:21 +00:00
Name string `yaml:"name"`
Addr string
Proto string `yaml:"proto"`
Port int `yaml:"port"`
2022-02-27 06:57:13 +00:00
Topics []string `yaml:"topics"`
}
type Config struct {
2022-02-27 10:10:21 +00:00
Database Database `yaml:"db"`
Publishers map[string]*Publisher `yaml:"publishers"`
2022-02-27 06:57:13 +00:00
}
var DefaultConfigFile = "/etc/sensenet/sensenet.yaml"
func LoadConfig(path string) (*Config, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
config := &Config{}
err = yaml.Unmarshal(data, config)
if err != nil {
return nil, err
}
2022-02-27 10:10:21 +00:00
for k, v := range config.Publishers {
if v.Port == 0 {
v.Port = defaultPort
}
if v.Proto == "" {
v.Proto = defaultProto
}
v.Addr = fmt.Sprintf("%s://%s:%d", v.Proto, k, v.Port)
config.Publishers[k] = v
}
2022-02-27 06:57:13 +00:00
return config, nil
}