-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
96 lines (81 loc) · 2.21 KB
/
server.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
package server
import (
"context"
"net/http"
"time"
chiPrometheus "github.com/766b/chi-prometheus"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
httpSwagger "github.com/swaggo/http-swagger"
"go.uber.org/fx"
"github.com/golangsrilanka/go-puso/api/router"
"github.com/golangsrilanka/go-puso/config"
_ "github.com/golangsrilanka/go-puso/docs"
)
// @title Go Puso
// @version 0.0.1
// @description Golang Sri Lanka template repo
// @contact.name Golang Sri Lanka
// @contact.email golangsrilanka@mail.com
// @host golangsrilanka.github.io/go-puso
// @BasePath /api/v1
var RunServerCmd = &cobra.Command{
Use: "server",
Short: "start go-puso server",
Run: func(cmd *cobra.Command, args []string) {
fx.New(
fx.Supply(cmd),
Init,
fx.Invoke(Run),
).Run()
},
}
func Run(lc fx.Lifecycle, ro *router.Router) {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: false,
MaxAge: 300,
}))
port := config.GetEnv("server.PORT")
if port == "" {
port = "8080"
}
r.Use(chiPrometheus.NewMiddleware("go-puso"))
r.Handle("/metrics", promhttp.Handler())
r.Mount("/swagger", httpSwagger.Handler(
httpSwagger.URL("http://localhost:"+port+"/swagger/doc.json"),
))
r.Mount("/healthz", router.HealthRoute())
r.Mount("/api/v1", ro.Route())
svc := http.Server{
Handler: r,
Addr: ":" + port,
ReadTimeout: time.Second * 20,
WriteTimeout: time.Second * 20,
}
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
go func() {
log.Println("Server running on port: " + port)
err := svc.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
return nil
},
OnStop: func(ctx context.Context) error {
log.Println("Server is starting to shutdown....")
return svc.Shutdown(ctx)
},
})
}