-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.go
227 lines (182 loc) · 5.11 KB
/
web.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"encoding/json"
"fmt"
"io/fs"
"maps"
"os"
"path"
"path/filepath"
"slices"
"strings"
"github.com/gofiber/fiber/v2"
logger_middleware "github.com/gofiber/fiber/v2/middleware/logger"
"raznar.id/static-serve-metadata/config"
"raznar.id/static-serve-metadata/logger"
)
type Metadata struct {
Tag string `json:"tag"`
Content string
}
type SEOData struct {
URL string `json:"url"`
Default bool `json:"default"`
Template bool `json:"template"`
Metadata []Metadata `json:"metadata"`
}
type GroupSEO struct {
// key: lang code
SeoContents []SEOData
SeoDefaultContents SEOData
SeoTemplateContents SEOData
}
func (g GroupSEO) GetDataByURL(url string) SEOData {
for _, ctn := range g.SeoContents {
logger.System.DebugInfo(ctn.URL, url)
if ctn.URL == url {
return ctn
}
}
logger.System.DebugInfo("not found, giving the default")
return g.SeoDefaultContents
}
func (s SEOData) IsEmpty() bool {
return s.URL == ""
}
func (s SEOData) CollectMetadataString() string {
metadataList := []string{}
for _, mtd := range s.Metadata {
metadataList = append(metadataList, mtd.ConvertToHTML())
}
// indent 4 spaces.
return strings.Join(metadataList, "\n ")
}
func (s Metadata) ConvertToHTML() string {
return fmt.Sprintf("<meta name=\"%s\" content=\"%s\">", s.Tag, s.Content)
}
func handleWeb(ac *config.AppConfig, mapSEO map[string]GroupSEO, fileContent []byte) func(c *fiber.Ctx) (err error) {
defaultLang := getDefaultLang(ac)
return func(c *fiber.Ctx) (err error) {
fileCtn := string(fileContent)
geoHeader := c.Get(ac.SeoConfig.GeoHeader)
wPath := c.Path()
langCode := getLangCode(ac, geoHeader)
if langCode == "" {
langCode = defaultLang
}
groupSEO := mapSEO[langCode]
logger.System.DebugInfo("lang ", langCode)
logger.System.DebugInfo("path: ", wPath)
seoData := groupSEO.GetDataByURL(wPath)
fileCtn = strings.Replace(fileCtn, "<!-- seo header -->", groupSEO.SeoTemplateContents.CollectMetadataString() + "\n" + seoData.CollectMetadataString(), 1)
c.Set("Cache-Control", fmt.Sprintf("public, max-age=%d", ac.WebConfig.MaxAge))
c.Set("Content-Type", "text/html")
return c.SendString(fileCtn)
}
}
func getLangCode(ac *config.AppConfig, country string) (lang string) {
for k, v := range ac.SeoConfig.Languages {
if slices.Contains(v.Country, country) {
lang = k
return
}
}
return
}
func getDefaultLang(ac *config.AppConfig) (defaultLang string) {
for k, v := range ac.SeoConfig.Languages {
if v.Default {
defaultLang = k
break
}
}
return
}
func loadSEO(ac *config.AppConfig) (map[string]GroupSEO, error) {
groupSeo := make(map[string]GroupSEO)
for lang := range maps.Keys(ac.SeoConfig.Languages) {
langDirectory := path.Join(ac.SeoConfig.DataPath, lang)
seoContents, err := loadSeoContents(langDirectory)
if err != nil {
return groupSeo, err
}
groupSeo[lang] = GroupSEO{SeoContents: seoContents}
}
for lang, content := range groupSeo {
for _, seo := range content.SeoContents {
if seo.Default {
content.SeoDefaultContents = seo
break
}
}
groupSeo[lang] = content
}
for lang, content := range groupSeo {
for _, seo := range content.SeoContents {
if seo.Template {
content.SeoTemplateContents = seo
break
}
}
groupSeo[lang] = content
}
return groupSeo, nil
}
func loadSeoContents(directory string) ([]SEOData, error) {
var seoContents []SEOData
// Walk through all files and directories
err := filepath.WalkDir(directory, func(filePath string, d fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("error accessing %s: %w", filePath, err)
}
// Skip directories
if d.IsDir() {
return nil
}
// Read file content
fileContent, err := os.ReadFile(filePath)
if err != nil {
logger.System.LogWarn("Failed to read file:", filePath, "Error:", err)
return nil // Continue with the next file
}
// Parse JSON
var seoDataList []SEOData
if err := json.Unmarshal(fileContent, &seoDataList); err != nil {
logger.System.LogWarn("Failed to parse JSON in file:", filePath, "Error:", err)
return nil // Continue with the next file
}
logger.System.DebugInfo("filename:", d.Name())
logger.System.DebugInfo("data:", seoDataList)
seoContents = append(seoContents, seoDataList...)
return nil
})
if err != nil {
return nil, fmt.Errorf("error walking directory %s: %w", directory, err)
}
return seoContents, nil
}
func RunWeb(ac *config.AppConfig) (err error) {
webConf := ac.WebConfig
fConf := fiber.Config{}
fConf.TrustedProxies = webConf.TrustedProxies
if len(fConf.TrustedProxies) > 0 {
fConf.EnableTrustedProxyCheck = true
fConf.ProxyHeader = webConf.ProxyHeader
}
fileContent, err := os.ReadFile(path.Join(webConf.DataPath, webConf.IndexFile))
if err != nil {
return
}
mapSeo, err := loadSEO(ac)
if err != nil {
return
}
webApp := fiber.New(fConf)
webApp.Use(logger_middleware.New())
webHandler := handleWeb(ac, mapSeo, fileContent)
webApp.Get("/", webHandler)
webApp.Static("/", webConf.DataPath)
webApp.Get("*", webHandler)
err = webApp.Listen(fmt.Sprintf("%s:%s", webConf.Bind, webConf.Port))
return
}