twins/config.go

111 lines
2.1 KiB
Go
Raw Normal View History

2020-10-29 20:35:48 +00:00
package main
import (
"errors"
"io/ioutil"
2020-10-30 00:17:23 +00:00
"log"
2020-10-29 20:35:48 +00:00
"os"
"regexp"
"strconv"
"strings"
2020-10-29 20:35:48 +00:00
"github.com/kballard/go-shellquote"
2020-10-29 20:35:48 +00:00
"gopkg.in/yaml.v3"
)
type pathConfig struct {
// Path to match
Path string
2020-10-30 00:17:23 +00:00
// Resource to serve
Root string
Proxy string
Command string
2020-10-29 20:35:48 +00:00
2020-10-31 01:31:13 +00:00
// List directory entries
ListDirectory bool
r *regexp.Regexp
cmd []string
2020-10-29 20:35:48 +00:00
}
type certConfig struct {
Cert string
Key string
}
2020-10-29 20:35:48 +00:00
type serverConfig struct {
Listen string
Certificates []*certConfig
2020-10-30 20:36:55 +00:00
Hosts map[string][]*pathConfig
hostname string
port int
2020-10-29 20:35:48 +00:00
}
var config = &serverConfig{
hostname: "localhost",
port: 1965,
}
2020-10-29 20:35:48 +00:00
func readconfig(configPath string) error {
if configPath == "" {
return errors.New("file unspecified")
}
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return errors.New("file not found")
}
configData, err := ioutil.ReadFile(configPath)
if err != nil {
return err
}
err = yaml.Unmarshal(configData, &config)
if err != nil {
return err
}
split := strings.Split(config.Listen, ":")
if len(split) != 2 {
config.hostname = config.Listen
config.Listen += ":1965"
} else {
config.hostname = split[0]
config.port, err = strconv.Atoi(split[1])
if err != nil {
log.Fatalf("invalid port specified: %s", err)
2020-10-29 20:35:48 +00:00
}
}
2020-10-30 20:36:55 +00:00
for _, paths := range config.Hosts {
for _, serve := range paths {
if serve.Path == "" {
log.Fatal("path must be specified in serve entry")
} else if (serve.Root != "" && (serve.Proxy != "" || serve.Command != "")) ||
(serve.Proxy != "" && (serve.Root != "" || serve.Command != "")) ||
(serve.Command != "" && (serve.Root != "" || serve.Proxy != "")) {
log.Fatal("only one root, reverse proxy or command may specified in a serve entry")
}
if serve.Path[0] == '^' {
serve.r = regexp.MustCompile(serve.Path)
} else if serve.Path[len(serve.Path)-1] == '/' {
serve.Path = serve.Path[:len(serve.Path)-1]
}
if serve.Command != "" {
serve.cmd, err = shellquote.Split(serve.Command)
if err != nil {
log.Fatalf("failed to parse command %s: %s", serve.cmd, err)
}
}
}
2020-10-29 20:35:48 +00:00
}
return nil
}