-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.go
93 lines (75 loc) · 1.59 KB
/
app.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
package candy
import (
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
)
type App struct {
Host string
Addr string
}
type AppServiceConfig struct {
TLDs []string
HostRoot string
}
func NewAppService(cfg AppServiceConfig) *AppService {
return &AppService{cfg: cfg}
}
type AppService struct {
cfg AppServiceConfig
}
func (f *AppService) FindApps() ([]App, error) {
files, err := os.ReadDir(f.cfg.HostRoot)
if err != nil {
return nil, err
}
var result []App
for _, file := range files {
if file.IsDir() {
continue
}
b, err := os.ReadFile(filepath.Join(f.cfg.HostRoot, file.Name()))
if err != nil {
return nil, err
}
apps, err := f.parseApps(file.Name(), strings.TrimSpace(string(b)))
if err != nil {
continue
}
result = append(result, apps...)
}
return result, nil
}
func (f *AppService) parseApps(domain, data string) ([]App, error) {
// port
port, err := strconv.Atoi(data)
if err == nil {
return f.buildApps(domain, fmt.Sprintf("127.0.0.1:%d", port)), nil
}
// http://ip:port
u, err := url.ParseRequestURI(data)
if err == nil {
return f.buildApps(domain, u.Host), nil
}
// ip:port
host, sport, err := net.SplitHostPort(data)
if err == nil {
return f.buildApps(domain, host+":"+sport), nil
}
// TODO: json
return nil, fmt.Errorf("invalid domain for file: %s", filepath.Join(f.cfg.HostRoot, domain))
}
func (f *AppService) buildApps(domain, addr string) []App {
var apps []App
for _, tld := range f.cfg.TLDs {
apps = append(apps, App{
Host: domain + "." + tld, // e.g., app.test
Addr: addr,
})
}
return apps
}