-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
91 lines (76 loc) · 2.24 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
package main
import (
"context"
"database/sql"
"flag"
"github.com/amrHassanAbdallah/tahweelaway/api"
"github.com/amrHassanAbdallah/tahweelaway/persistence"
"github.com/amrHassanAbdallah/tahweelaway/service"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
_ "github.com/lib/pq"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type Logger = *zap.SugaredLogger
var log Logger
func init() {
core := zap.NewProductionConfig()
core.EncoderConfig.TimeKey = "timestamp"
core.EncoderConfig.MessageKey = "message"
core.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
customLog, _ := core.Build()
log = customLog.WithOptions(zap.AddCallerSkip(1)).Sugar()
}
func main() {
var (
postgresURL = flag.String("postgresql-connection", "postgresql://root:secret@postgres:5432/tahweelaway?sslmode=disable", "DSN for postgres")
listen = flag.String("listen", ":8111", "Listen specified address.")
)
flag.Parse()
ctx, cancel := context.WithCancel(context.Background())
conn, err := sql.Open("postgres", *postgresURL)
if err != nil {
log.Fatalw("cannot connect to db:", err)
}
persistenceLayer, err := persistence.NewStore(ctx, conn)
if err != nil {
log.Fatalw("failed to initate the persistence layer", err)
}
thService := service.NewService(persistenceLayer)
server := api.NewServer(thService)
r := chi.NewRouter()
r.Route("/api/v1", func(r chi.Router) {
r.Use(middleware.Timeout(time.Duration(20) * time.Second))
api.HandlerFromMux(server, r)
})
r.Get("/api/v1/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
srv := &http.Server{
Handler: r,
Addr: *listen,
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
// ES is a http.Handler, so you can pass it directly to your mux
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalw("server failed to start", "error", err)
}
}()
log.Infof("server started on port %v", *listen)
<-done
log.Info("server terminating...")
if err := srv.Shutdown(ctx); err != nil {
log.Errorw("server terminating failed", "err", err)
}
// cleanup: closing db...etc
cancel()
log.Info("exited")
}