-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.go
More file actions
209 lines (176 loc) · 4.75 KB
/
web.go
File metadata and controls
209 lines (176 loc) · 4.75 KB
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
package main
import (
"encoding/json"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"raznar.id/static-serve-metadata/config"
)
type Metadata struct {
Tag string `json:"tag"`
Content string `json:"content"`
}
type SEOData struct {
URL string `json:"url"`
Default bool `json:"default"`
Template bool `json:"template"`
Metadata []Metadata `json:"metadata"`
Title string `json:"title"`
Prefix string `json:"prefix"`
}
type GroupSEO struct {
SeoContents []SEOData
SeoDefaultContents SEOData
SeoTemplateContents SEOData
}
func (g GroupSEO) GetDataByURL(url string) SEOData {
url = strings.TrimSuffix(url, "/")
for _, data := range g.SeoContents {
seoURL := strings.TrimSuffix(path.Join(data.Prefix, data.URL), "/")
if seoURL == url {
return data
}
}
return g.SeoDefaultContents
}
func (g GroupSEO) GetTitle() string {
return g.SeoTemplateContents.Title
}
func (s SEOData) GetTitle() string {
return s.Title
}
func (s SEOData) CollectMetadataString() string {
var tags []string
for _, m := range s.Metadata {
tags = append(tags, m.ToHTML())
}
return strings.Join(tags, "\n ")
}
func (m Metadata) ToHTML() string {
return fmt.Sprintf(`<meta name="%s" content="%s">`, m.Tag, m.Content)
}
func handleWeb(ac *config.Config, mapSEO map[string]GroupSEO, fileContent []byte) fiber.Handler {
defaultLang := getDefaultLang(ac)
templateHTML := string(fileContent)
return func(c *fiber.Ctx) error {
lang := getLangCode(ac, c.Get(ac.SeoConfig.GeoHeader), c.Path())
if lang == "" {
lang = defaultLang
}
seoGroup := mapSEO[lang]
seo := seoGroup.GetDataByURL(c.Path())
// Compose metadata
metadata := seoGroup.SeoTemplateContents.CollectMetadataString() + "\n" + seo.CollectMetadataString()
// Replace placeholders
content := strings.Replace(templateHTML, "<!-- seo header -->", metadata, 1)
title := seo.GetTitle()
if title == "" {
title = seoGroup.GetTitle()
}
content = strings.Replace(content, "<!-- title -->", title, 1)
c.Set("Cache-Control", fmt.Sprintf("public, max-age=%d", ac.WebConfig.MaxAge))
c.Set("Content-Type", "text/html")
return c.SendString(content)
}
}
func getLangCode(ac *config.Config, country, path string) string {
for lang, config := range ac.SeoConfig.Languages {
if contains(config.Country, country) || strings.HasPrefix(path, config.Prefix) {
return lang
}
}
return ""
}
func contains(slice []string, val string) bool {
for _, s := range slice {
if s == val {
return true
}
}
return false
}
func getDefaultLang(ac *config.Config) string {
for lang, cfg := range ac.SeoConfig.Languages {
if cfg.Default {
return lang
}
}
return "default"
}
func loadSEO(ac *config.Config) (map[string]GroupSEO, error) {
result := make(map[string]GroupSEO)
for lang := range ac.SeoConfig.Languages {
dir := path.Join(ac.SeoConfig.DataPath, lang)
data, err := loadSeoContents(dir)
if err != nil {
return nil, fmt.Errorf("loading SEO data for %s: %w", lang, err)
}
group := GroupSEO{SeoContents: data}
for _, seo := range data {
if seo.Default && group.SeoDefaultContents.URL == "" {
group.SeoDefaultContents = seo
}
if seo.Template && group.SeoTemplateContents.URL == "" {
group.SeoTemplateContents = seo
}
}
result[lang] = group
}
return result, nil
}
func loadSeoContents(dir string) ([]SEOData, error) {
var contents []SEOData
err := filepath.WalkDir(dir, func(filePath string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
raw, err := os.ReadFile(filePath)
if err != nil {
return nil
}
var parsed []SEOData
if err := json.Unmarshal(raw, &parsed); err == nil {
contents = append(contents, parsed...)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("error walking dir %s: %w", dir, err)
}
return contents, nil
}
func RunWeb(ac *config.Config) error {
webConf := ac.WebConfig
app := fiber.New(fiber.Config{
TrustedProxies: webConf.TrustedProxies,
EnableTrustedProxyCheck: len(webConf.TrustedProxies) > 0,
ProxyHeader: webConf.ProxyHeader,
})
app.Use(logger.New())
fileContent, err := os.ReadFile(path.Join(webConf.DataPath, webConf.IndexFile))
if err != nil {
return err
}
handler := func(c *fiber.Ctx) error {
return c.Type("html").Send(fileContent)
}
if !ac.WebConfig.StaticOnly {
fmt.Println("Running with SEO")
mapSEO, err := loadSEO(ac)
if err != nil {
return err
}
handler = handleWeb(ac, mapSEO, fileContent)
} else {
fmt.Println("Running only static.")
}
app.Get("/", handler)
app.Static("/", webConf.DataPath)
app.Get("*", handler)
return app.Listen(fmt.Sprintf("%s:%s", webConf.Bind, webConf.Port))
}