-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
259 lines (230 loc) · 6.7 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package main
import (
"context"
"embed"
"flag"
"io/fs"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/mattn/go-colorable"
"github.com/topi314/chroma/v2/formatters"
"github.com/topi314/chroma/v2/formatters/html"
"github.com/topi314/chroma/v2/lexers"
"github.com/topi314/chroma/v2/styles"
"github.com/topi314/gomigrate"
"github.com/topi314/gomigrate/drivers/postgres"
"github.com/topi314/gomigrate/drivers/sqlite"
"github.com/topi314/tint"
meternoop "go.opentelemetry.io/otel/metric/noop"
tracenoop "go.opentelemetry.io/otel/trace/noop"
"github.com/topi314/gobin/v2/internal/ver"
"github.com/topi314/gobin/v2/server"
"github.com/topi314/gobin/v2/server/database"
)
//go:generate go run github.com/a-h/templ/cmd/templ@latest generate
// These variables are set via the -ldflags option in go build
var (
Name = "gobin"
Namespace = "github.com/topi314/gobin/v2"
Version = "unknown"
Commit = "unknown"
BuildTime = "unknown"
)
var (
//go:embed server/assets
Assets embed.FS
//go:embed server/migrations
Migrations embed.FS
//go:embed styles
Styles embed.FS
)
func main() {
cfgPath := flag.String("config", "gobin.toml", "path to gobin.toml")
flag.Parse()
cfg, err := server.LoadConfig(*cfgPath)
if err != nil {
slog.Error("Error while loading config", tint.Err(err))
return
}
setupLogger(cfg.Log)
buildTime, _ := time.Parse(time.RFC3339, BuildTime)
slog.Info("Starting Gobin...", slog.String("version", Version), slog.String("commit", Commit), slog.Time("build-time", buildTime))
slog.Info("Config", slog.String("config", cfg.String()))
var (
tracer = tracenoop.NewTracerProvider().Tracer(Name)
meter = meternoop.NewMeterProvider().Meter(Name)
)
if cfg.Otel != nil {
tracer, err = newTracer(*cfg.Otel)
if err != nil {
slog.Error("Error while creating tracer", tint.Err(err))
return
}
meter, err = newMeter(*cfg.Otel)
if err != nil {
slog.Error("Error while creating meter", tint.Err(err))
return
}
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
db, err := database.New(ctx, cfg.Database)
if err != nil {
slog.Error("Error while connecting to database", tint.Err(err))
return
}
defer func() {
if closeErr := db.Close(); closeErr != nil {
slog.Error("Error while closing database", tint.Err(closeErr))
}
}()
var driver gomigrate.NewDriver
switch cfg.Database.Type {
case database.TypePostgres:
driver = postgres.New
case database.TypeSQLite:
driver = sqlite.New
}
if err = gomigrate.Migrate(ctx, db, driver, Migrations, gomigrate.WithDirectory("server/migrations")); err != nil {
slog.Error("Error while migrating database", tint.Err(err))
return
}
signer, err := jose.NewSigner(jose.SigningKey{
Algorithm: jose.HS512,
Key: []byte(cfg.JWTSecret),
}, nil)
if err != nil {
slog.Error("Error while creating signer", tint.Err(err))
return
}
var assets http.FileSystem
if cfg.DevMode {
slog.Info("Development mode enabled")
assets = http.Dir("server")
} else {
sub, err := fs.Sub(Assets, "server")
if err != nil {
slog.Error("Failed to get sub fs for embedded assets", tint.Err(err))
return
}
assets = http.FS(sub)
}
loadEmbeddedStyles()
loadLocalStyles(cfg.CustomStyles)
styles.Fallback = styles.Get(cfg.DefaultStyle)
lexers.Fallback = lexers.Get("plaintext")
htmlFormatter := html.New(
html.WithClasses(true),
html.ClassPrefix("ch-"),
html.Standalone(false),
html.InlineCode(false),
html.WithNopPreWrapper(),
html.WithLineNumbers(true),
html.WithLinkableLineNumbers(true, "L"),
html.TabWidth(4),
)
standaloneHTMLFormatter := html.New(
html.Standalone(true),
html.WithLineNumbers(true),
html.WithLinkableLineNumbers(true, "L"),
html.TabWidth(4),
)
formatters.Register("html", htmlFormatter)
formatters.Register("html-standalone", standaloneHTMLFormatter)
s := server.NewServer(ver.FormatBuildVersion(Version, Commit, buildTime), cfg.DevMode, cfg, db, signer, tracer, meter, assets, htmlFormatter, standaloneHTMLFormatter)
slog.Info("Gobin started...", slog.String("address", cfg.ListenAddr))
go s.Start()
defer s.Close()
si := make(chan os.Signal, 1)
signal.Notify(si, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-si
}
const (
ansiFaint = "\033[2m"
ansiWhiteBold = "\033[37;1m"
ansiYellowBold = "\033[33;1m"
ansiCyanBold = "\033[36;1m"
ansiCyanBoldFaint = "\033[36;1;2m"
ansiRedFaint = "\033[31;2m"
ansiRedBold = "\033[31;1m"
ansiRed = "\033[31m"
ansiYellow = "\033[33m"
ansiGreen = "\033[32m"
ansiMagenta = "\033[35m"
)
func setupLogger(cfg server.LogConfig) {
var handler slog.Handler
switch cfg.Format {
case server.LogFormatJSON:
handler = slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
AddSource: cfg.AddSource,
Level: cfg.Level,
})
case server.LogFormatText:
handler = tint.NewHandler(colorable.NewColorable(os.Stdout), &tint.Options{
AddSource: cfg.AddSource,
Level: cfg.Level,
NoColor: cfg.NoColor,
LevelColors: map[slog.Level]string{
slog.LevelDebug: ansiMagenta,
slog.LevelInfo: ansiGreen,
slog.LevelWarn: ansiYellow,
slog.LevelError: ansiRed,
},
Colors: map[tint.Kind]string{
tint.KindTime: ansiYellowBold,
tint.KindSourceFile: ansiCyanBold,
tint.KindSourceSeparator: ansiCyanBoldFaint,
tint.KindSourceLine: ansiCyanBold,
tint.KindMessage: ansiWhiteBold,
tint.KindKey: ansiFaint,
tint.KindSeparator: ansiFaint,
tint.KindValue: ansiWhiteBold,
tint.KindErrorKey: ansiRedFaint,
tint.KindErrorSeparator: ansiFaint,
tint.KindErrorValue: ansiRedBold,
},
})
default:
slog.Error("Unknown log format", slog.String("format", string(cfg.Format)))
os.Exit(-1)
}
slog.SetDefault(slog.New(handler))
}
func loadEmbeddedStyles() {
slog.Info("Loading embedded styles")
stylesSub, err := fs.Sub(Styles, "styles")
if err != nil {
slog.Error("Failed to get sub fs for embedded styles", tint.Err(err))
return
}
cStyles, err := styles.LoadFromFS(stylesSub)
if err != nil {
slog.Error("Failed to load embedded styles", tint.Err(err))
return
}
for _, style := range cStyles {
slog.Debug("Loaded embedded style", slog.String("name", style.Name))
styles.Register(style)
}
}
func loadLocalStyles(stylesDir string) {
if stylesDir == "" {
return
}
slog.Info("Loading local styles", slog.String("dir", stylesDir))
cStyles, err := styles.LoadFromFS(os.DirFS(stylesDir))
if err != nil {
slog.Error("Failed to load local styles", tint.Err(err))
return
}
for _, style := range cStyles {
slog.Debug("Loaded local style", slog.String("name", style.Name))
styles.Register(style)
}
}