2020-10-29 21:35:48 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"io/ioutil"
|
2020-10-30 01:17:23 +01:00
|
|
|
"log"
|
2020-10-29 21:35:48 +01:00
|
|
|
"os"
|
|
|
|
"regexp"
|
|
|
|
|
2020-10-30 19:19:16 +01:00
|
|
|
"github.com/kballard/go-shellquote"
|
2020-10-29 21:35:48 +01:00
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
)
|
|
|
|
|
|
|
|
type serveConfig struct {
|
2020-10-30 19:19:16 +01:00
|
|
|
// Path to match
|
2020-10-29 22:58:12 +01:00
|
|
|
Path string
|
2020-10-30 01:17:23 +01:00
|
|
|
|
2020-10-30 19:19:16 +01:00
|
|
|
// Resource to serve
|
|
|
|
Root string
|
|
|
|
Proxy string
|
|
|
|
Command string
|
2020-10-29 21:35:48 +01:00
|
|
|
|
2020-10-30 19:19:16 +01:00
|
|
|
r *regexp.Regexp
|
|
|
|
cmd []string
|
2020-10-29 21:35:48 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type serverConfig struct {
|
2020-10-30 19:19:16 +01:00
|
|
|
Cert string
|
|
|
|
Key string
|
|
|
|
Hostname string
|
|
|
|
Port int
|
|
|
|
Serve []*serveConfig
|
2020-10-29 21:35:48 +01:00
|
|
|
}
|
|
|
|
|
2020-10-30 19:19:16 +01:00
|
|
|
var config = &serverConfig{
|
|
|
|
Hostname: "localhost",
|
|
|
|
Port: 1965,
|
|
|
|
}
|
2020-10-29 21:35:48 +01: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
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, serve := range config.Serve {
|
2020-10-29 22:58:12 +01:00
|
|
|
if serve.Path == "" {
|
2020-10-30 01:17:23 +01:00
|
|
|
log.Fatal("path must be specified in serve entry")
|
2020-10-30 19:19:16 +01:00
|
|
|
} 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")
|
2020-10-29 21:35:48 +01:00
|
|
|
}
|
2020-10-29 22:58:12 +01:00
|
|
|
|
|
|
|
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]
|
2020-10-29 21:35:48 +01:00
|
|
|
}
|
2020-10-30 19:19:16 +01:00
|
|
|
|
|
|
|
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 21:35:48 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|