-
Notifications
You must be signed in to change notification settings - Fork 0
/
Setup.go
93 lines (75 loc) · 2.01 KB
/
Setup.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
package app
import (
"fmt"
"io/fs"
"net/http"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/dadobos/pokemongotemplates/internal/infrastructure"
"github.com/gin-gonic/gin"
)
type ApplicationState struct {
HTTPServer *http.Server
Handler *gin.Engine
Config *infrastructure.ApplicationEnvironment
}
type ApplicationServer struct {
State ApplicationState
}
var templateFunctionMap = template.FuncMap{
"GetCurrentYear": infrastructure.GetCurrentYear,
"GetPrevPagePokemons": infrastructure.GetPrevPagePokemons,
"GetNextPagePokemons": infrastructure.GetNextPagePokemons,
}
func (s *ApplicationServer) registerHandlers() {
var files []string
templateLocation := fmt.Sprintf("%s/web/templates", s.State.Config.TemplateLocation)
err := filepath.Walk(templateLocation, func(path string, info fs.FileInfo, err error) error {
if strings.HasSuffix(path, ".gohtml") {
files = append(files, path)
}
return nil
})
if err != nil {
panic(err.Error())
}
s.State.Handler.SetFuncMap(templateFunctionMap)
s.State.Handler.LoadHTMLFiles(files...)
s.State.Handler.GET("/", s.pageHandler())
s.State.Handler.GET("/pagination", s.paginationPageHandler())
s.State.Handler.GET("/form/send-pagination", s.slugSendPaginationRequestHandler())
}
func NewApplicationServer(userOptions *ApplicationState) *ApplicationServer {
state := userOptions
if state == nil {
state = &ApplicationState{}
}
if state.Handler == nil {
gin.SetMode(gin.ReleaseMode)
state.Handler = gin.Default()
}
if state.HTTPServer == nil {
state.HTTPServer = &http.Server{
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 100 * time.Second,
Addr: ":8080",
Handler: state.Handler,
}
}
if state.Config == nil {
config := infrastructure.GetConfig()
state.Config = &config
}
s := ApplicationServer{
State: ApplicationState{
HTTPServer: state.HTTPServer,
Handler: state.Handler,
Config: state.Config,
},
}
s.registerHandlers()
return &s
}