-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrouter.go
97 lines (79 loc) · 2.14 KB
/
router.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
97
package routes
import (
"html/template"
"net/http"
"sync"
"github.com/gin-contrib/cache"
"github.com/gin-contrib/cache/persistence"
"github.com/gin-gonic/gin"
)
func HealthCheckHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
}
var (
templateCache map[string]*template.Template
templateCacheMux sync.RWMutex
store persistence.CacheStore
)
func init() {
// Initialize template cache
templateCache = make(map[string]*template.Template)
// Create a memory store for caching rendered pages
store = persistence.NewInMemoryStore(60) // Cache for 60 seconds
}
// preloadTemplates parses all templates during initialization
func preloadTemplates() error {
templateCacheMux.Lock()
defer templateCacheMux.Unlock()
templates, err := template.ParseGlob("public/*.tmpl.html")
if err != nil {
return err
}
for _, t := range templates.Templates() {
templateCache[t.Name()] = t
}
return nil
}
func renderizarTemplate(templateName string) gin.HandlerFunc {
// Use template caching
return cache.CachePage(store, 60, func(c *gin.Context) {
templateCacheMux.RLock()
tmpl, exists := templateCache[templateName]
templateCacheMux.RUnlock()
if !exists {
c.String(http.StatusInternalServerError, "Template not found")
return
}
c.Header("Content-Type", "text/html")
c.Status(http.StatusOK)
tmpl.Execute(c.Writer, nil)
})
}
// Essa função permite que crie vários servers com diferentes portas (sempre checar o .env)
func criarRouter() (http.Handler, error) {
// Parse templates during router creation
if err := preloadTemplates(); err != nil {
return nil, err
}
gin.SetMode(gin.ReleaseMode)
router := gin.New()
// Use more performant middlewares
router.Use(
gin.Recovery(),
gin.Logger(),
)
// Routes
router.GET("/", renderizarTemplate("index.tmpl.html"))
router.StaticFile("/css/index.css", "./public/css/index.css")
router.GET("/health_check", HealthCheckHandler)
return router, nil
}
// Inicialização dos servers retornando a mensagem deles
func MdwRouter_01() (http.Handler, error) {
return criarRouter()
}
func MdwRouter_02() (http.Handler, error) {
return criarRouter()
}