-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapi.go
More file actions
71 lines (55 loc) · 1.6 KB
/
Copy pathapi.go
File metadata and controls
71 lines (55 loc) · 1.6 KB
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
package main
import (
"context"
"flag"
"fmt"
"net/http"
"time"
"github.com/sirupsen/logrus"
_ "github.com/uptrace/go-realworld-example-app/blog"
"github.com/uptrace/go-realworld-example-app/httputil"
_ "github.com/uptrace/go-realworld-example-app/org"
"github.com/uptrace/go-realworld-example-app/rwe"
"github.com/uptrace/go-realworld-example-app/xconfig"
)
var listenFlag = flag.String("listen", ":8000", "listen address")
func main() {
flag.Parse()
ctx := context.Background()
cfg, err := xconfig.LoadConfig("api")
if err != nil {
logrus.WithContext(ctx).WithError(err).Fatal("LoadConfig failed")
}
ctx = rwe.Init(ctx, cfg)
defer rwe.Exit(ctx)
var handler http.Handler
handler = rwe.Router
handler = httputil.PanicHandler{Next: handler}
logrus.WithContext(ctx).
WithField("env", cfg.Env).
WithField("addr", *listenFlag).
Info("serving...")
serveHTTP(ctx, handler)
}
func serveHTTP(ctx context.Context, handler http.Handler) {
srv := &http.Server{
Addr: *listenFlag,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
Handler: handler,
}
go func() {
if err := srv.ListenAndServe(); err != nil && !isServerClosed(err) {
logrus.WithContext(ctx).WithError(err).Error("ListenAndServe failed")
}
}()
fmt.Println(rwe.WaitExitSignal())
if err := srv.Shutdown(ctx); err != nil {
logrus.WithContext(ctx).WithError(err).Error("srv.Shutdown failed")
}
}
//------------------------------------------------------------------------------
func isServerClosed(err error) bool {
return err.Error() == "http: Server closed"
}