-
Notifications
You must be signed in to change notification settings - Fork 135
/
handler.go
60 lines (48 loc) · 1.63 KB
/
handler.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
package main
import (
"fmt"
"os"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/mvrilo/go-redoc"
ginredoc "github.com/mvrilo/go-redoc/gin"
"golang-program-structure/common/middleware"
"golang-program-structure/service"
)
func NewHandler(config *service.Config) *gin.Engine {
h := gin.New()
// Header preservation during redirect differs between Google and Apple
// To be safe, do no automatic redirects
h.RedirectTrailingSlash = false
h.RedirectFixedPath = false
// The status route is open
h.GET("/status", config.Status)
// Add a CORS middleware handler
corsConfig := cors.DefaultConfig()
corsConfig.AllowAllOrigins = true
h.Use(cors.New(corsConfig))
// Add the fallback handler to catch any panic and return a 500 to the client
h.Use(gin.CustomRecovery(config.PanicRecovery))
// Add the request logging middleware handler to all service routes
requestLogger := middleware.NewRequestLogger(config.Logger)
h.Use(requestLogger.Middleware)
// Setup default routes
service.SetupDefaultEndpoints(h, config)
// Setup custom routes
service.AddRoutes(h, config)
// Add the handler to serve the redoc
specFile := "./docs/swagger.json"
if _, err := os.Stat(specFile); err == nil {
docs := redoc.Redoc{
Title: "Docs",
Description: "Documentation",
SpecFile: "./docs/swagger.json",
SpecPath: fmt.Sprintf("/v%s/%s/docs/openapi.json", config.Version, config.ServiceName),
DocsPath: fmt.Sprintf("/v%s/%s/docs", config.Version, config.ServiceName),
}
h.Use(ginredoc.New(docs))
} else {
config.Logger.Warnf("Swagger file not found at %s, skipping redoc init", specFile)
}
return h
}