-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
58 lines (47 loc) · 1.04 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package proxanne
import (
"errors"
"fmt"
"net/http/httputil"
"net/url"
"regexp"
"gopkg.in/yaml.v2"
)
var (
ErrNoRoutes = errors.New("no routes found")
)
type Config struct {
Routes []struct {
Matches string `yaml:"matches"`
Target string `yaml:"target"`
} `yaml:"routes"`
}
func ParseConfig(raw []byte) (*Config, error) {
config := &Config{}
err := yaml.Unmarshal(raw, config)
return config, err
}
func BuildRouter(config *Config) (Router, error) {
if len(config.Routes) == 0 {
return nil, ErrNoRoutes
}
router := Router{}
for _, route := range config.Routes {
matchesRegexp, err := regexp.Compile(route.Matches)
if err != nil {
return nil, fmt.Errorf("error in route %v: matches is not a valid regex", route)
}
targetURL, err := url.Parse(route.Target)
if err != nil {
return nil, fmt.Errorf("error in route %v: target is not a valid url", route)
}
router = append(
router,
&Route{
Matches: matchesRegexp,
Target: httputil.NewSingleHostReverseProxy(targetURL),
},
)
}
return router, nil
}