Basic config package to parse NTP Pool system config

This commit is contained in:
Ask Bjørn Hansen 2023-12-10 20:43:38 -08:00
parent 608f05d395
commit 5c7ae6ab8a
3 changed files with 147 additions and 0 deletions

90
config/config.go Normal file
View File

@ -0,0 +1,90 @@
// Package config provides NTP Pool specific
// configuration tools.
package config
import (
"net/url"
"os"
"strconv"
"strings"
"go.ntppool.org/common/logger"
)
//go:generate accessory -type Config
type Config struct {
deploymentMode string `accessor:"getter"`
manageHostname string `accessor:"getter"`
manageTLS bool
webHostname string `accessor:"getter"`
webHostnames []string
webTLS bool
valid bool `accessor:"getter"`
}
func New() *Config {
c := Config{}
c.deploymentMode = os.Getenv("deployment_mode")
c.manageHostname = os.Getenv("manage_hostname")
c.webHostnames = strings.Split(os.Getenv("web_hostname"), ",")
for i, h := range c.webHostnames {
c.webHostnames[i] = strings.TrimSpace(h)
}
if len(c.webHostnames) > 0 {
c.webHostname = c.webHostnames[0]
c.valid = true
}
c.manageTLS = parseBool(os.Getenv("manage_tls"))
c.webTLS = parseBool(os.Getenv("web_tls"))
return &c
}
func (c *Config) WebURL(path string, query *url.Values) string {
return baseURL(c.webHostname, c.webTLS, path, query)
}
func baseURL(host string, tls bool, path string, query *url.Values) string {
uri := url.URL{}
uri.Host = host
if tls {
uri.Scheme = "https"
} else {
uri.Scheme = "http"
}
uri.Path = path
if query != nil {
uri.RawQuery = query.Encode()
}
return uri.String()
}
func parseBool(s string) bool {
switch strings.ToLower(s) {
case "yes":
return true
case "y":
return true
case "no":
return false
case "n":
return false
case "":
return false
}
t, err := strconv.ParseBool(s)
if err != nil {
logger.Setup().Error("could not parse bool", "string", s, "err", err)
return false
}
return t
}

31
config/config_accessor.go Normal file
View File

@ -0,0 +1,31 @@
// Code generated by accessory; DO NOT EDIT.
package config
func (c *Config) DeploymentMode() string {
if c == nil {
return ""
}
return c.deploymentMode
}
func (c *Config) ManageHostname() string {
if c == nil {
return ""
}
return c.manageHostname
}
func (c *Config) WebHostname() string {
if c == nil {
return ""
}
return c.webHostname
}
func (c *Config) Valid() bool {
if c == nil {
return false
}
return c.valid
}

26
config/config_test.go Normal file
View File

@ -0,0 +1,26 @@
package config
import (
"net/url"
"os"
"testing"
)
func TestBaseURL(t *testing.T) {
os.Setenv("web_hostname", "www.ntp.dev, web.ntppool.dev")
os.Setenv("web_tls", "yes")
c := New()
if !c.Valid() {
t.Fatalf("config not valid")
}
q := url.Values{}
q.Set("foo", "bar")
u := c.WebURL("/foo", &q)
if u != "https://www.ntp.dev/foo?foo=bar" {
t.Fatalf("unexpected WebURL: %s", u)
}
}