76 lines
1.4 KiB
Go
76 lines
1.4 KiB
Go
package config
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io/ioutil"
|
|
|
|
"github.com/jackc/pgx/v4/pgxpool"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
const (
|
|
defaultPort = 4000
|
|
defaultProto = "tcp"
|
|
)
|
|
|
|
type Database struct {
|
|
Host string `yaml:"host"`
|
|
Port int `yaml:"port"`
|
|
Name string `yaml:"name"`
|
|
User string `yaml:"user"`
|
|
Password string `yaml:"password"`
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
type Publisher struct {
|
|
Name string `yaml:"name"`
|
|
Addr string
|
|
Proto string `yaml:"proto"`
|
|
Port int `yaml:"port"`
|
|
Topics []string `yaml:"topics"`
|
|
}
|
|
|
|
type Config struct {
|
|
Database Database `yaml:"db"`
|
|
Publishers map[string]*Publisher `yaml:"publishers"`
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
return config, nil
|
|
}
|