blob: c6a40ac9a0a13c48c1f573a03fcc94f6c845f942 (
plain)
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
|
package main
import (
"bufio"
"fmt"
"io"
"os"
"regexp"
"strings"
"sync"
)
type Route struct {
match *regexp.Regexp
backend string
}
// Config stores the TLS routing configuration.
type Config struct {
mu sync.Mutex
routes []Route
}
func dnsRegex(s string) (*regexp.Regexp, error) {
return regexp.Compile(s)
}
func (c *Config) Match(hostname string) string {
c.mu.Lock()
defer c.mu.Unlock()
for _, r := range c.routes {
if r.match.MatchString(hostname) {
return r.backend
}
}
return ""
}
func (c *Config) Read(r io.Reader) error {
var routes []Route
s := bufio.NewScanner(r)
for s.Scan() {
fs := strings.Fields(s.Text())
switch len(fs) {
case 0:
continue
case 1:
return fmt.Errorf("invalid %q on a line by itself", s.Text())
case 2:
re, err := dnsRegex(fs[0])
if err != nil {
return err
}
routes = append(routes, Route{re, fs[1]})
default:
// TODO: multiple backends?
return fmt.Errorf("too many fields on line: %q", s.Text())
}
}
if err := s.Err(); err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
c.routes = routes
return nil
}
func (c *Config) ReadFile(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
return c.Read(f)
}
|