-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
214 lines (186 loc) · 4.57 KB
/
main.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package main
import (
"embed"
"fmt"
"html/template"
"io/fs"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/bmatcuk/doublestar/v3"
"github.com/rs/zerolog"
"github.com/urfave/cli/v2"
"github.com/maxihafer/gosynchro/pkg/logger"
"github.com/maxihafer/gosynchro/pkg/proxy"
)
var (
version = "development"
commit = "none"
date = "none"
builtBy = "user"
//go:embed all:static/*
staticFS embed.FS
//go:embed all:templates/*
templateFS embed.FS
)
var StaticFS fs.FS
var ErrorTemplate *template.Template
func init() {
ErrorTemplate = template.Must(template.ParseFS(templateFS, "templates/error.gohtml"))
var err error
StaticFS, err = fs.Sub(staticFS, "static")
if err != nil {
panic(err)
}
}
type Config struct {
remote string
port int
debug bool
json bool
patterns cli.StringSlice
}
func (c *Config) Parse() (*proxy.Config, error) {
_, err := url.Parse(c.remote)
if err != nil {
return nil, fmt.Errorf("invalid remote '%s': %w", c.remote, err)
}
if c.port < 0 || c.port > 65535 {
return nil, fmt.Errorf("invalid port '%d'", c.port)
}
var files []string
for _, pattern := range c.patterns.Value() {
matches, err := doublestar.Glob(pattern)
if err != nil {
return nil, fmt.Errorf("invalid pattern '%s': %w", pattern, err)
}
files = append(files, matches...)
}
return &proxy.Config{
Remote: c.remote,
Port: c.port,
Debug: c.debug,
Files: files,
}, nil
}
func main() {
var rawConfig Config
var log zerolog.Logger
cli.VersionPrinter = func(c *cli.Context) {
fmt.Printf("version: %s\ncommit: %s\ncompiled: %s\nbuilt by: %s\n", c.App.Version, c.App.Metadata["commit"], c.App.Metadata["compiled"], c.App.Metadata["builtBy"])
}
app := &cli.App{
Name: "gosynchro",
Usage: "A tool to synchronize browser windows",
Version: version,
Metadata: map[string]interface{}{
"commit": commit,
"builtBy": builtBy,
"compiled": date,
},
Flags: []cli.Flag{
&cli.IntFlag{
Name: "port",
Aliases: []string{"p"},
Usage: "Port to listen on",
Value: 3000,
Destination: &rawConfig.port,
},
&cli.BoolFlag{
Name: "verbose",
Usage: "Enable verbose logging",
Value: false,
Destination: &rawConfig.debug,
},
&cli.BoolFlag{
Name: "json",
Usage: "Output logs in JSON format",
Value: false,
Destination: &rawConfig.json,
},
},
Before: func(context *cli.Context) error {
var opts []logger.Option
if rawConfig.debug {
opts = append(opts, logger.WithLevel(zerolog.DebugLevel))
}
if rawConfig.json {
opts = append(opts, logger.WithOutput(context.App.Writer))
} else {
opts = append(
opts, logger.WithOutput(
zerolog.ConsoleWriter{
Out: context.App.Writer,
TimeFormat: time.RFC3339,
},
),
)
}
log = logger.New(
opts...,
)
context.Context = log.WithContext(context.Context)
return nil
},
Commands: []*cli.Command{
&cli.Command{
Name: "proxy",
Usage: "Start a proxy server",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "remote",
Usage: "Remote to proxy request to",
Value: "http://localhost:8080",
Destination: &rawConfig.remote,
},
&cli.StringSliceFlag{
Name: "files",
Usage: "Files to watch for changes",
DefaultText: cli.NewStringSlice("public/**/*.html", "static/*.svg").String(),
Aliases: []string{"f"},
Destination: &rawConfig.patterns,
},
},
Action: func(context *cli.Context) error {
cfg, err := rawConfig.Parse()
if err != nil {
return cli.Exit(err, 1)
}
cfg.StaticFS = StaticFS
cfg.ErrorTemplate = ErrorTemplate
p, err := proxy.NewFromConfig(cfg)
if err != nil {
return cli.Exit(err, 1)
}
if err := p.Start(context.Context); err != nil {
return cli.Exit(err, 1)
}
return nil
},
},
&cli.Command{
Name: "reload",
Usage: "Reload client listening on PORT (default 3000)",
Action: func(context *cli.Context) error {
if rawConfig.port < 0 || rawConfig.port > 65535 {
return cli.Exit("Invalid port", 1)
}
resp, err := http.Get("http://localhost:" + strconv.Itoa(rawConfig.port) + "/gosynchro/reload")
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return cli.Exit("Failed to reload", 1)
}
return nil
},
},
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal().Err(err).Msg("error")
}
}