-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
257 lines (219 loc) · 7.06 KB
/
Copy pathutils.go
File metadata and controls
257 lines (219 loc) · 7.06 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package main
import (
"compress/gzip"
"fmt"
"net/http"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
)
type gzipResponseWriter struct {
http.ResponseWriter
writer *gzip.Writer
}
func (w gzipResponseWriter) Write(data []byte) (int, error) { return w.writer.Write(data) }
// gzipHTML compresses dynamic HTML when the front proxy has not already done so.
func gzipHTML(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
w.Header().Add("Vary", "Accept-Encoding")
gz := gzip.NewWriter(w)
defer func() {
_ = gz.Close()
}()
next(gzipResponseWriter{ResponseWriter: w, writer: gz}, r)
}
func slugifyTitle(title string) string {
// Convert to lowercase
slug := strings.ToLower(title)
// Replace any non-alphanumeric characters (except hyphens) with a hyphen
reg := regexp.MustCompile(`[^a-z0-9]+`)
slug = reg.ReplaceAllString(slug, "-")
// Remove leading and trailing hyphens
slug = strings.Trim(slug, "-")
return slug
}
func GetTitle(titleSlug string) string {
return titleSlug + " - " + "Brian R. Bondy"
}
func directToHttps(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if r.Host == "localhost:8080" {
next(w, r)
return
}
isHTTPS := r.URL.Scheme == "https" || strings.HasPrefix(r.Proto, "HTTPS") || r.Header.Get("X-Forwarded-Proto") == "https"
if isHTTPS && r.Host == "brianbondy.com" {
next(w, r)
return
}
// Use a fixed hostname rather than the request Host header so every public
// URL resolves to the site's single canonical origin.
http.Redirect(w, r, siteURL+r.URL.RequestURI(), http.StatusPermanentRedirect)
}
// canonicalURL returns the preferred public URL for a rendered page.
func canonicalURL(data interface{}) string {
pathBySlug := map[string]string{
"home": "/",
"all": "/all",
"filters": "/blog/filters",
"running": "/running",
"pictures": "/pictures",
"projects": "/projects",
"interviews": "/interviews",
"cheatsheets": "/cheatsheets",
"about.markdown": "/about",
"advice.markdown": "/advice",
"contact.markdown": "/contact",
"resume.markdown": "/resume",
"books": "/books",
}
v := reflect.ValueOf(data)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() == reflect.Map {
if page := v.MapIndex(reflect.ValueOf("Page")); page.IsValid() {
return canonicalURL(page.Interface())
}
}
if v.Kind() != reflect.Struct {
return ""
}
if shareURL := v.FieldByName("ShareUrl"); shareURL.IsValid() && shareURL.Kind() == reflect.String && shareURL.String() != "" {
return siteURL + shareURL.String()
}
if slug := v.FieldByName("MarkdownSlug"); slug.IsValid() && slug.Kind() == reflect.String {
return siteURL + pathBySlug[slug.String()]
}
return ""
}
func extractFirstParagraph(content string) string {
// First try to find content between first <p> tags
re := regexp.MustCompile(`<p>(.*?)</p>`)
matches := re.FindStringSubmatch(content)
if len(matches) > 1 {
// Get the content inside the first <p> tags
preview := matches[1]
// Remove any remaining HTML tags
tagRegex := regexp.MustCompile(`<[^>]*>`)
preview = tagRegex.ReplaceAllString(preview, "")
if preview != "" {
// If preview is too long, truncate it
if len(preview) > 300 {
// Try to cut at a word boundary
lastSpace := strings.LastIndex(preview[:300], " ")
if lastSpace > 0 {
preview = preview[:lastSpace] + "..."
} else {
preview = preview[:300] + "..."
}
}
return preview
}
}
// If no paragraph found or it was empty, remove all HTML tags from content
tagRegex := regexp.MustCompile(`<[^>]*>`)
cleanContent := tagRegex.ReplaceAllString(content, " ")
// Remove extra whitespace
cleanContent = strings.Join(strings.Fields(cleanContent), " ")
// Take first 300 characters or less
if len(cleanContent) > 300 {
lastSpace := strings.LastIndex(cleanContent[:300], " ")
if lastSpace > 0 {
cleanContent = cleanContent[:lastSpace] + "..."
} else {
cleanContent = cleanContent[:300] + "..."
}
}
return cleanContent
}
func getImageMimeType(imagePath string) string {
ext := strings.ToLower(filepath.Ext(imagePath))
switch ext {
case ".png":
return "image/png"
case ".webp":
return "image/webp"
case ".jpg", ".jpeg":
return "image/jpeg"
case ".gif":
return "image/gif"
default:
return ""
}
}
const responsiveImageSizes = "(max-width: 800px) calc(100vw - 44px), 756px"
// responsiveImageSizesFor returns the sizes attribute for an image slot. It
// defaults to the article body width; templates rendering smaller slots (such
// as gallery thumbnails) pass their own value so browsers pick a smaller
// srcset candidate.
func responsiveImageSizesFor(override ...string) string {
if len(override) > 0 && override[0] != "" {
return override[0]
}
return responsiveImageSizes
}
func responsiveImageSrcset(src string) string {
ext := strings.ToLower(filepath.Ext(src))
if !strings.HasPrefix(src, "/static/") || (ext != ".jpg" && ext != ".jpeg" && ext != ".png" && ext != ".webp") {
return ""
}
base := strings.TrimSuffix(src, filepath.Ext(src))
variants := make([]string, 0, 3)
for _, width := range []int{640, 960, 1200} {
variant := fmt.Sprintf("%s-%d.webp", base, width)
if _, err := os.Stat(strings.TrimPrefix(variant, "/")); err == nil {
variants = append(variants, fmt.Sprintf("%s %dw", variant, width))
}
}
return strings.Join(variants, ", ")
}
// Image optimization functions for PageSpeed improvements.
func optimizeImageTag(imgTag string) string {
// Extract src attribute
srcRegex := regexp.MustCompile(`src=["']([^"']+)["']`)
srcMatch := srcRegex.FindStringSubmatch(imgTag)
if len(srcMatch) < 2 {
return imgTag
}
src := srcMatch[1]
// Skip data URLs and external URLs
if strings.HasPrefix(src, "data:") || strings.HasPrefix(src, "http") {
return imgTag
}
// Only process static images
if !strings.HasPrefix(src, "/static/") {
return imgTag
}
if strings.ToLower(filepath.Ext(src)) == ".gif" {
return imgTag
}
responsiveImg := imgTag
// Add loading="lazy" if not already present
if !strings.Contains(responsiveImg, `loading="`) {
responsiveImg = strings.Replace(responsiveImg, ">", ` loading="lazy">`, 1)
}
if !strings.Contains(responsiveImg, "data-lightbox-src=") {
responsiveImg = strings.Replace(responsiveImg, ">", ` data-lightbox-src="`+src+`">`, 1)
}
if srcset := responsiveImageSrcset(src); srcset != "" && !strings.Contains(responsiveImg, "srcset=") {
responsiveImg = strings.Replace(responsiveImg, ">", ` srcset="`+srcset+`" sizes="`+responsiveImageSizes+`">`, 1)
}
// Add decoding="async" for better performance
if !strings.Contains(responsiveImg, `decoding="`) {
responsiveImg = strings.Replace(responsiveImg, ">", ` decoding="async">`, 1)
}
return responsiveImg
}
func optimizeImagesInContent(content string) string {
// Find all img tags
imgRegex := regexp.MustCompile(`<img[^>]+>`)
return imgRegex.ReplaceAllStringFunc(content, func(match string) string {
return optimizeImageTag(match)
})
}