forked from jsteenb2/mess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
96 lines (79 loc) · 2.65 KB
/
http.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"
"os"
"strconv"
"strings"
firebase "firebase.google.com/go/v4"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/common/auth"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/common/logs"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/sirupsen/logrus"
"google.golang.org/api/option"
)
func RunHTTPServer(createHandler func(router chi.Router) http.Handler) {
RunHTTPServerOnAddr(":"+os.Getenv("PORT"), createHandler)
}
func RunHTTPServerOnAddr(addr string, createHandler func(router chi.Router) http.Handler) {
apiRouter := chi.NewRouter()
setMiddlewares(apiRouter)
rootRouter := chi.NewRouter()
// we are mounting all APIs under /api path
rootRouter.Mount("/api", createHandler(apiRouter))
logrus.Info("Starting HTTP server")
err := http.ListenAndServe(addr, rootRouter)
if err != nil {
logrus.WithError(err).Panic("Unable to start HTTP server")
}
}
func setMiddlewares(router *chi.Mux) {
router.Use(middleware.RequestID)
router.Use(middleware.RealIP)
router.Use(logs.NewStructuredLogger(logrus.StandardLogger()))
router.Use(middleware.Recoverer)
addCorsMiddleware(router)
addAuthMiddleware(router)
router.Use(
middleware.SetHeader("X-Content-Type-Options", "nosniff"),
middleware.SetHeader("X-Frame-Options", "deny"),
)
router.Use(middleware.NoCache)
}
func addAuthMiddleware(router *chi.Mux) {
if mockAuth, _ := strconv.ParseBool(os.Getenv("MOCK_AUTH")); mockAuth {
router.Use(auth.HttpMockMiddleware)
return
}
var opts []option.ClientOption
if file := os.Getenv("SERVICE_ACCOUNT_FILE"); file != "" {
opts = append(opts, option.WithCredentialsFile(file))
}
config := &firebase.Config{ProjectID: os.Getenv("GCP_PROJECT")}
firebaseApp, err := firebase.NewApp(context.Background(), config, opts...)
if err != nil {
logrus.Fatalf("error initializing app: %v\n", err)
}
authClient, err := firebaseApp.Auth(context.Background())
if err != nil {
logrus.WithError(err).Fatal("Unable to create firebase Auth client")
}
router.Use(auth.FirebaseHttpMiddleware{authClient}.Middleware)
}
func addCorsMiddleware(router *chi.Mux) {
allowedOrigins := strings.Split(os.Getenv("CORS_ALLOWED_ORIGINS"), ";")
if len(allowedOrigins) == 0 {
return
}
corsMiddleware := cors.New(cors.Options{
AllowedOrigins: allowedOrigins,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
})
router.Use(corsMiddleware.Handler)
}