-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
161 lines (140 loc) · 3.84 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
package main
import (
"context"
_ "embed"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"runtime"
"syscall"
"time"
"github.com/ardanlabs/conf/v3"
_ "go.uber.org/automaxprocs"
)
const serviceName = "lingon"
// //go:embed embed
// webapp embed.FS
//go:embed embed/index.html
var indexhtml []byte
//
// init function to register types to runtime.NewScheme() in another file
//
func main() {
log := makeLogger(os.Stderr)
if err := run(log); err != nil {
log.Error("run", "err", err)
os.Exit(1) //nolint:gocritic
}
}
func run(log *slog.Logger) error {
cfg := struct {
conf.Version
Port int `conf:"default:8080,env:PORT"`
Host string `conf:"default:0.0.0.0"`
HealthPath string `conf:"default:/healthz"`
VersionPath string `conf:"default:/version"`
ReadTimeout time.Duration `conf:"default:5s"`
WriteTimeout time.Duration `conf:"default:10s"`
IdleTimeout time.Duration `conf:"default:120s"`
ShutdownTimeout time.Duration `conf:"default:5s"`
}{
Version: conf.Version{
Build: commit,
Desc: serviceName + "web service",
},
}
const prefix = serviceName
help, err := conf.Parse(prefix, &cfg)
if err != nil {
if errors.Is(err, conf.ErrHelpWanted) {
fmt.Println(help)
return nil
}
return fmt.Errorf("parsing config: %w", err)
}
// Closing signal
stopChan := make(chan os.Signal, 1)
signal.Notify(
stopChan,
// syscall.SIGKILL, // never gets caught on POSIX
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
)
ms := &runtime.MemStats{}
cfgStr, err := conf.String(&cfg)
if err != nil {
return fmt.Errorf("config: %w", err)
}
runtime.ReadMemStats(ms)
log.Info(
fmt.Sprintf("Starting service... %d", time.Now().UTC().Unix()),
slog.Int("CPU cores", runtime.NumCPU()),
slog.String("Available Memory", fmt.Sprintf("%d MB", ms.Sys/1024)),
slog.String("config", cfgStr),
)
defer log.Info("Service stopped")
sm := http.NewServeMux()
sm.HandleFunc("/convert", convert(log))
sm.HandleFunc(cfg.VersionPath, VersionInfo)
sm.HandleFunc(cfg.HealthPath, healthz)
//
// // static files when embedding a whole directory
// // but we only want to serve index.html
//
// static, err := fs.Sub(webapp, "embed")
// if err != nil {
// return fmt.Errorf("getting webapp: %w", err)
// }
// sm.Handle("/", http.FileServer(http.FS(static)))
sm.Handle("/", byteHandler(indexhtml))
srv := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
Handler: sm,
DisableGeneralOptionsHandler: false,
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: cfg.WriteTimeout,
ReadTimeout: cfg.ReadTimeout,
ReadHeaderTimeout: cfg.ReadTimeout,
IdleTimeout: cfg.IdleTimeout,
}
go func() {
if zerr := srv.ListenAndServe(); zerr != nil && !errors.Is(zerr, http.ErrServerClosed) {
log.Error("failed to start server: %v", "err", zerr)
panic(zerr)
}
}()
<-stopChan
ctxShutDown, cancel := context.WithTimeout(context.Background(), time.Minute)
defer func() { cancel() }()
log.Info("shutting down the service...")
if err = srv.Shutdown(ctxShutDown); err != nil {
log.Error("server Shutdown Failed", "err", err)
}
return nil
}
func healthz(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, "ok")
}
func byteHandler(b []byte) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(b)
}
}
// makeLogger returns a logger that writes to w [io.Writer]. If w is nil, os.Stderr is used.
// Timestamp is removed and directory from the source's filename is shown.
func makeLogger(w io.Writer) *slog.Logger {
if w == nil {
w = os.Stderr
}
return slog.New(
slog.NewJSONHandler(w, &slog.HandlerOptions{AddSource: true}).WithAttrs(
[]slog.Attr{slog.String("app", serviceName)},
),
)
}