-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
102 lines (87 loc) · 2.01 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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"time"
"github.com/rs/zerolog"
)
func main() {
conf, err := ParseArgsStrict(os.Args)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
return
}
var l zerolog.Logger
if conf.LogJson {
l = zerolog.New(os.Stdout).With().Timestamp().Logger()
} else {
l = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339, NoColor: conf.NoColor}).With().Timestamp().Logger()
}
if conf.Store == nil {
conf.Store = &StoreConfig{
Kind: "files",
Path: "vcpkg-cache",
Opts: map[string]string{},
}
l.Info().Str("store", conf.Store.String()).Msg("use default store")
}
store, err := NewStore(conf.Store)
if err != nil {
l.Fatal().Err(err).Msg("failed to initialize a store")
return
}
defer func() {
err := store.Close()
if err != nil {
l.Error().Err(err).Msg("failed to close the store")
}
}()
handler := &Handler{
Store: store,
Log: l,
IsReadable: true,
IsWritable: true,
}
if conf.ReadOnly {
handler.IsWritable = false
l.Info().Msg("upload disabled")
} else if conf.WriteOnly {
handler.IsReadable = false
l.Info().Msg("download disabled")
}
addr := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
server := &http.Server{
Addr: addr,
Handler: handler,
}
server_closed := make(chan struct{})
defer close(server_closed)
go func() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
for {
select {
case <-server_closed:
return
case sig := <-signals:
l.Warn().Str("signal", sig.String()).Msg("shutdown the server")
if err := server.Shutdown(context.Background()); err != nil {
l.Error().Err(err).Msg("failed to shutdown the server")
}
}
}
}()
l.Info().Str("addr", addr).Msg("start server")
if err := server.ListenAndServe(); err != nil {
if errors.Is(err, http.ErrServerClosed) {
l.Info().Msg("server closed gracefully")
} else {
l.Error().Err(err).Msg("unexpected server close")
}
}
}