|
1 | 1 | package infrastructure
|
2 | 2 |
|
3 | 3 | import (
|
4 |
| - "encoding/base64" |
5 | 4 | "io"
|
6 |
| - "net/http" |
7 | 5 | "os"
|
8 | 6 |
|
9 | 7 | "github.com/gin-gonic/gin"
|
10 | 8 | metrics "github.com/penglongli/gin-metrics/ginmetrics"
|
11 | 9 |
|
12 | 10 | "github.com/oswaldom-code/api-template-gin/pkg/config"
|
| 11 | + "github.com/oswaldom-code/api-template-gin/pkg/log" |
13 | 12 | "github.com/oswaldom-code/api-template-gin/src/adapters/http/rest/handlers"
|
| 13 | + "github.com/oswaldom-code/api-template-gin/src/adapters/http/rest/infrastructure/middlewares" |
| 14 | + "github.com/oswaldom-code/api-template-gin/src/adapters/http/rest/infrastructure/routes" |
14 | 15 | )
|
15 | 16 |
|
16 |
| -var basicAuthorizationMiddleware MiddlewareFunc = func(c *gin.Context) { |
17 |
| - // get token from header |
18 |
| - token := c.GetHeader("Authorization") |
19 |
| - // validate token |
20 |
| - if token != "Basic "+base64.StdEncoding.EncodeToString([]byte(config.GetAuthenticationKey().Secret)) { |
21 |
| - // response unauthorized status code |
22 |
| - c.Redirect(http.StatusFound, "/authorization") |
23 |
| - } |
24 |
| -} |
25 |
| - |
26 | 17 | func setMetrics(router *gin.Engine) {
|
27 |
| - // get global Monitor object |
28 | 18 | monitor := metrics.GetMonitor()
|
29 |
| - // +optional set metric path, default /debug/metrics |
| 19 | + if monitor == nil { |
| 20 | + log.Error("[ERROR] No se pudo obtener el monitor de métricas") |
| 21 | + return |
| 22 | + } |
| 23 | + |
30 | 24 | monitor.SetMetricPath("/metrics")
|
31 |
| - // +optional set slow time, default 5s |
32 |
| - monitor.SetSlowTime(10) |
33 |
| - // +optional set request duration, default {0.1, 0.3, 1.2, 5, 10} |
34 |
| - // used to p95, p99 |
35 |
| - monitor.SetDuration([]float64{0.1, 0.3, 1.2, 5, 10}) |
| 25 | + slowTime := int32(5) |
| 26 | + monitor.SetSlowTime(slowTime) // default is 5 seconds TODO: make it configurable |
| 27 | + durationThresholds := []float64{0.5, 1, 3, 5, 10} |
| 28 | + monitor.SetDuration(durationThresholds) |
| 29 | + |
36 | 30 | monitor.Use(router)
|
| 31 | + |
| 32 | + log.Info("Métricas configuradas correctamente", log.Fields{ |
| 33 | + "metric_path": "/metrics", |
| 34 | + "slow_time": slowTime, |
| 35 | + "duration_percentiles": durationThresholds, |
| 36 | + }) |
37 | 37 | }
|
38 | 38 |
|
39 | 39 | // NewGinServer creates a new Gin server.
|
40 |
| -func NewGinServer(handler ServerInterface) *gin.Engine { |
| 40 | +func NewGinServer(handler routes.ServerInterface) *gin.Engine { |
41 | 41 | // get configuration
|
42 | 42 | serverConfig := config.GetServerConfig()
|
43 | 43 | // validate parameters configuration
|
44 | 44 | if ok := serverConfig.Validate(); ok != nil {
|
45 | 45 | panic("[ERROR] server configuration is not valid")
|
46 | 46 | }
|
47 | 47 |
|
48 |
| - // set gin mode (debug or release) |
| 48 | + log.Info("Running in mode: ", log.Fields{"mode": serverConfig.Mode}) |
49 | 49 | gin.SetMode(serverConfig.Mode)
|
| 50 | + |
50 | 51 | // if debug mode is release write the logs to a file
|
51 | 52 | if serverConfig.Mode == "release" {
|
52 | 53 | // Disable Console Color, you don't need console color when writing the logs to file.
|
53 | 54 | gin.DisableConsoleColor()
|
54 |
| - // Logging to a file. // TODO: add current date to log file name |
| 55 | + |
| 56 | + if err := os.MkdirAll("log", os.ModePerm); err != nil { |
| 57 | + log.Error("[ERROR] failed to create log directory", log.Fields{"error": err}) |
| 58 | + return nil |
| 59 | + } |
| 60 | + |
55 | 61 | f, ok := os.Create("log/error.log")
|
56 | 62 | if ok != nil {
|
57 |
| - panic("[ERROR] error creating log file") |
| 63 | + log.Error("[ERROR] error creating log file", log.Fields{"error": ok}) |
| 64 | + return nil |
58 | 65 | }
|
59 |
| - gin.DefaultWriter = io.MultiWriter(f) |
| 66 | + defer f.Close() |
| 67 | + |
| 68 | + // Usa un writer para los logs de Gin y tu paquete de logs |
| 69 | + multiWriter := io.MultiWriter(f, os.Stdout) // También puedes redirigir a stdout o a tu logger personalizado |
| 70 | + gin.DefaultWriter = multiWriter |
60 | 71 | }
|
61 | 72 |
|
62 | 73 | // create routes
|
63 | 74 | router := gin.Default()
|
64 |
| - // set metrics |
| 75 | + if router == nil { |
| 76 | + log.Error("[ERROR] failed to create gin router") |
| 77 | + return nil |
| 78 | + } |
| 79 | + |
65 | 80 | setMetrics(router)
|
66 |
| - // set middleware |
67 |
| - ginServerOptions := GinServerOptions{BaseURL: "/"} |
68 |
| - ginServerOptions.Middlewares = append(ginServerOptions.Middlewares, basicAuthorizationMiddleware) |
| 81 | + |
| 82 | + ginServerOptions := routes.GinServerOptions{BaseURL: "/"} |
| 83 | + ginServerOptions.Middlewares = append(ginServerOptions.Middlewares, middlewares.BasicAuthorizationMiddleware) |
| 84 | + |
69 | 85 | // register Handler, router and middleware to gin
|
70 |
| - RegisterHandlersWithOptions(router, handler, ginServerOptions) |
| 86 | + routes.RegisterHandlersWithOptions(router, handler, ginServerOptions) |
| 87 | + |
71 | 88 | return router
|
72 | 89 | }
|
73 | 90 |
|
|
0 commit comments