/
config.go
134 lines (105 loc) · 2.2 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"errors"
"net/url"
"os"
"gopkg.in/yaml.v3"
)
type BackendConfig struct {
URL string `yaml:"url"`
}
func (c BackendConfig) Validate() error {
if c.URL == "" {
return errors.New("http.routes[].backend.url is required")
}
_, err := url.Parse(c.URL)
if err != nil {
return err
}
return nil
}
type RouteConfig struct {
Path string `yaml:"path"`
Rewrite *string `yaml:"rewrite"`
Backend BackendConfig `yaml:"backend"`
}
func (c RouteConfig) Validate() error {
if c.Path == "" {
return errors.New("http.routes[].path is required")
}
return nil
}
type MiddlewareConfig struct {
Name string `yaml:"name"`
Options map[string]interface{} `yaml:"options"`
}
func (c MiddlewareConfig) Validate() error {
if c.Name == "" {
return errors.New("http.middlewares[].name is required")
}
return nil
}
type HttpConfig struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
Middlewares []MiddlewareConfig `yaml:"middlewares"`
Routes []RouteConfig `yaml:"routes"`
}
func (c HttpConfig) Validate() error {
if c.Host == "" {
return errors.New("host is required")
}
if c.Port == 0 {
return errors.New("port is required")
}
if c.Port < 0 || c.Port > 65535 {
return errors.New("port must be between 0 and 65535")
}
for _, middleware := range c.Middlewares {
err := middleware.Validate()
if err != nil {
return err
}
}
for _, route := range c.Routes {
err := route.Validate()
if err != nil {
return err
}
}
return nil
}
type ServerConfig struct {
Http *HttpConfig `yaml:"http"`
}
func (c ServerConfig) Validate() error {
err := c.Http.Validate()
if err != nil {
return err
}
return nil
}
type ProxyConfig struct {
Servers []ServerConfig `yaml:"servers"`
}
func (c ProxyConfig) Validate() error {
for _, server := range c.Servers {
err := server.Validate()
if err != nil {
return err
}
}
return nil
}
func LoadConfig(filePath string) (*ProxyConfig, error) {
file, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
var config ProxyConfig
err = yaml.Unmarshal(file, &config)
if err != nil {
return nil, err
}
return &config, nil
}