-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.go
More file actions
1117 lines (993 loc) · 29.1 KB
/
Copy pathhandlers.go
File metadata and controls
1117 lines (993 loc) · 29.1 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/bbondy/go-brianbondy/data"
"github.com/codegangsta/negroni"
"github.com/gorilla/feeds"
"github.com/gorilla/mux"
)
const (
layoutISO = "2006-01-02"
layoutUS = "January 2, 2006"
siteURL = "https://brianbondy.com"
)
// getErrorMessageForCode returns a user-friendly message for a given HTTP error code.
func getErrorMessageForCode(code int) string {
switch code {
case http.StatusNotFound:
return "Move along. Move along."
case http.StatusInternalServerError:
return "An unexpected server error occurred. Please try again later."
case http.StatusBadRequest:
return "The request could not be understood by the server."
case http.StatusForbidden:
return "You do not have permission to access this page."
case http.StatusUnauthorized:
return "You are not authorized to view this page."
case http.StatusMethodNotAllowed:
return "The method is not allowed for the requested URL."
case http.StatusRequestTimeout:
return "The request timed out. Please try again."
case http.StatusTooManyRequests:
return "You have made too many requests. Please slow down."
case http.StatusServiceUnavailable:
return "The service is temporarily unavailable. Please try again later."
case http.StatusGatewayTimeout:
return "The server did not receive a timely response."
default:
return "An error occurred."
}
}
func errorPage(w http.ResponseWriter, message string, slug string) {
errorPageWithStatus(w, message, slug, http.StatusNotFound)
}
func errorPageWithStatus(w http.ResponseWriter, message string, slug string, statusCode int) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(statusCode)
var title string
switch statusCode {
case http.StatusNotFound:
title = "These aren't the pages you're looking for."
case http.StatusInternalServerError:
title = "Server Error"
case http.StatusBadRequest:
title = "Bad Request"
case http.StatusForbidden:
title = "Access Forbidden"
case http.StatusUnauthorized:
title = "Unauthorized"
case http.StatusMethodNotAllowed:
title = "Method Not Allowed"
case http.StatusRequestTimeout:
title = "Request Timeout"
case http.StatusTooManyRequests:
title = "Too Many Requests"
case http.StatusServiceUnavailable:
title = "Service Unavailable"
case http.StatusGatewayTimeout:
title = "Gateway Timeout"
default:
title = "Error"
}
if message == "" {
message = getErrorMessageForCode(statusCode)
}
p := &data.SimpleMarkdownPage{
Title: title,
Content: message,
MarkdownSlug: slug,
ErrorCode: statusCode,
}
err := executeTemplate(w, "error", p)
if err != nil {
log.Printf("Error executing error page template: %v", err)
return
}
}
func parseIntParam(w http.ResponseWriter, value string, name string, slug string) (int, bool) {
if value == "" {
return 0, true
}
parsed, err := strconv.Atoi(value)
if err != nil {
errorPageWithStatus(w, fmt.Sprintf("Invalid %s value", name), slug, http.StatusBadRequest)
return 0, false
}
return parsed, true
}
func testErrorHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
errorCodeStr := vars["errorcode"]
errorCode, err := strconv.Atoi(errorCodeStr)
if err != nil {
http.Error(w, "Invalid error code", http.StatusBadRequest)
return
}
// Validate that it's a 4xx or 5xx error code
if errorCode < 400 || errorCode >= 600 {
http.Error(w, "Error code must be between 400-599", http.StatusBadRequest)
return
}
message := getErrorMessageForCode(errorCode)
errorPageWithStatus(w, message, "", errorCode)
}
func getMarkdownTemplateHandler(titleSlug string, markdownSlug string, fbShareUrl string) *negroni.Negroni {
handler := func(w http.ResponseWriter, r *http.Request) {
p := &data.SimpleMarkdownPage{
Title: GetTitle(titleSlug),
Content: getMarkdownData(markdownSlug),
MarkdownSlug: markdownSlug,
ShareUrl: fbShareUrl,
}
err := executeTemplate(w, "simpleMarkdown", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
return negroni.New(
negroni.HandlerFunc(directToHttps),
negroni.Wrap(http.HandlerFunc(handler)))
}
func runningHandler(w http.ResponseWriter, r *http.Request) {
runs, err := data.GetRuns()
if err != nil {
errorPage(w, "Unable to load run data", "running")
return
}
// Keep the initial page compact; the all-time view remains available in the selector.
yearFilter := r.URL.Query().Get("year")
if yearFilter == "" {
yearFilter = "365"
}
// Get Strava totals for selected view
totalRuns, totalDistanceKm, totalElevationM, totalTimeMinutes, err := data.GetStravaRunTotalsFor(yearFilter)
if err != nil {
totalRuns = 0
totalDistanceKm = 0
totalElevationM = 0
totalTimeMinutes = 0
}
timeDays, timeHours, timeMinutes := data.SplitMinutesToDaysHoursMinutes(totalTimeMinutes)
// Generate 2D contribution graph with month and day labels
contributionGraph2D, err := data.GenerateContributionGraph2D(yearFilter)
if err != nil {
contributionGraph2D = nil
}
graphJSON := template.JS(`{"startDate":"","weeks":0,"activeDays":{}}`)
if contributionGraph2D != nil {
encoded, marshalErr := json.Marshal(contributionGraph2D.CanvasData())
if marshalErr == nil {
graphJSON = template.JS(encoded)
}
}
// Remove debug print
// if contributionGraph2D != nil {
// log.Printf("DEBUG: runs=%d, weeks=%d, days=%d", len(runs), contributionGraph2D.Weeks, contributionGraph2D.Days)
// } else {
// log.Printf("DEBUG: contributionGraph2D is nil")
// }
stravaTotals := data.StravaRunTotals{
TotalRuns: totalRuns,
TotalDistanceKm: totalDistanceKm,
TotalElevationM: totalElevationM,
TotalTimeDays: timeDays,
TotalTimeHours: timeHours,
TotalTimeMinutes: timeMinutes,
}
// Get activity type breakdown for the selected year filter
activityBreakdown, err := data.GetActivityTypeBreakdown(yearFilter)
if err != nil {
activityBreakdown = []data.ActivityTypeBreakdown{}
}
p := &data.RunningPage{
Title: GetTitle("Running"),
MarkdownSlug: "running",
Runs: runs,
ContributionGraph: nil, // not used in new template
StravaRunTotals: stravaTotals,
ActivityTypeBreakdown: activityBreakdown,
}
// Get last updated date
lastUpdated, err := data.GetLastUpdatedDate()
if err != nil {
lastUpdated = "Unknown"
}
// Pass the 2D graph as a separate variable
err = executeTemplate(w, "running", map[string]interface{}{
"MarkdownSlug": p.MarkdownSlug,
"Page": p,
"ContributionGraph2D": contributionGraph2D,
"Years": func() []int {
if contributionGraph2D != nil {
return contributionGraph2D.Years
}
return nil
}(),
"SelectedYear": yearFilter,
"LastUpdatedDate": lastUpdated,
"GraphJSON": graphJSON,
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// runsForDateHandler handles AJAX requests for runs on a specific date
func runsForDateHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
date := r.URL.Query().Get("date")
if date == "" {
http.Error(w, "Date parameter required", http.StatusBadRequest)
return
}
runs, err := data.GetRunsForDate(date)
if err != nil {
http.Error(w, "Unable to load runs for date", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(runs); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// optionalFloatParam reads a query parameter that may be absent.
func optionalFloatParam(query url.Values, name string) (*float64, error) {
raw := query.Get(name)
if raw == "" {
return nil, nil
}
value, err := strconv.ParseFloat(raw, 64)
if err != nil {
return nil, fmt.Errorf("invalid %s", name)
}
return &value, nil
}
// optionalIntParam reads a query parameter that may be absent.
func optionalIntParam(query url.Values, name string) (*int, error) {
raw := query.Get(name)
if raw == "" {
return nil, nil
}
value, err := strconv.Atoi(raw)
if err != nil {
return nil, fmt.Errorf("invalid %s", name)
}
return &value, nil
}
// runningTotalsHandler keeps calendar filtering client-light: the client sends
// the active activity types and day metric bounds, and gets back the totals for
// the days those filters highlight.
func runningTotalsHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
types := make(map[string]bool)
for _, typ := range strings.Split(query.Get("types"), ",") {
if typ != "" {
types[typ] = true
}
}
var metrics data.RunMetricFilter
var err error
for _, param := range []struct {
name string
target **float64
}{
{"minKm", &metrics.MinDistanceKm},
{"maxKm", &metrics.MaxDistanceKm},
} {
if *param.target, err = optionalFloatParam(query, param.name); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
for _, param := range []struct {
name string
target **int
}{
{"minMinutes", &metrics.MinDurationMin},
{"maxMinutes", &metrics.MaxDurationMin},
{"minElevation", &metrics.MinElevationM},
{"maxElevation", &metrics.MaxElevationM},
} {
if *param.target, err = optionalIntParam(query, param.name); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
if len(types) == 0 && metrics.IsZero() {
http.Error(w, "At least one activity type or metric bound is required", http.StatusBadRequest)
return
}
count, distance, elevation, minutes, err := data.GetStravaRunTotalsFiltered(query.Get("year"), types, metrics)
if err != nil {
http.Error(w, "Unable to load activity totals", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"activities": count, "distanceKm": distance, "elevationM": elevation, "minutes": minutes,
})
}
func projectsHandler(w http.ResponseWriter, r *http.Request) {
projects, err := data.GetProjects()
if err != nil {
errorPage(w, "Unable to load project data", "projects")
return
}
// Build a map of blog post IDs to blog post data for use in the template
blogPostMap := make(map[int]data.BlogPost)
for _, post := range blogPosts {
blogPostMap[post.Id] = post
}
p := struct {
Title string
MarkdownSlug string
Projects data.Projects
BlogPostMap map[int]data.BlogPost
}{
Title: GetTitle("Projects"),
MarkdownSlug: "projects",
Projects: projects,
BlogPostMap: blogPostMap,
}
err = executeTemplate(w, "projects", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func cheatsheetsHandler(w http.ResponseWriter, r *http.Request) {
cheatsheets, err := data.GetCheatsheets()
if err != nil {
errorPage(w, "Unable to load cheatsheets", "cheatsheets")
return
}
p := struct {
Title string
MarkdownSlug string
Cheatsheets data.Cheatsheets
}{
Title: GetTitle("Cheatsheets"),
MarkdownSlug: "cheatsheets",
Cheatsheets: cheatsheets,
}
err = executeTemplate(w, "cheatsheets", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func cheatsheetHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
slug := vars["slug"]
if slug == "" {
errorPageWithStatus(w, "Cheatsheet not found", "cheatsheets", http.StatusNotFound)
return
}
cheatsheets, err := data.GetCheatsheets()
if err != nil {
errorPage(w, "Unable to load cheatsheets", "cheatsheets")
return
}
var found *data.Cheatsheet
for i := range cheatsheets {
if cheatsheets[i].Slug == slug {
found = &cheatsheets[i]
break
}
}
if found == nil {
errorPageWithStatus(w, "Cheatsheet not found", "cheatsheets", http.StatusNotFound)
return
}
p := &data.SimpleMarkdownPage{
Title: GetTitle(found.Title),
Content: getMarkdownData("cheatsheets/" + slug + ".md"),
MarkdownSlug: "cheatsheets",
ShareUrl: "/cheatsheets/" + slug,
}
err = executeTemplate(w, "simpleMarkdown", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func interviewsHandler(w http.ResponseWriter, r *http.Request) {
interviews, err := data.GetInterviews()
if err != nil {
errorPage(w, "Unable to load interview data", "interviews")
return
}
p := struct {
Title string
MarkdownSlug string
Interviews data.Interviews
}{
Title: GetTitle("Interviews"),
MarkdownSlug: "interviews",
Interviews: interviews,
}
err = executeTemplate(w, "interviews", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func generateRSSHandler(w http.ResponseWriter, r *http.Request) {
feed := &feeds.Feed{
Title: "Brian R. Bondy's Blog",
Link: &feeds.Link{Href: siteURL},
Description: "Brian R. Bondy's Blog - Coding, Running, and Life",
Author: &feeds.Author{Name: "Brian R. Bondy"},
Created: time.Now(),
Image: &feeds.Image{
Url: siteURL + "/static/img/avatar.png",
Title: "Brian R. Bondy's Blog",
Link: siteURL,
Width: 200,
Height: 200,
},
}
var items []*feeds.Item
for _, post := range blogPosts {
parsedDate, _ := time.Parse(layoutISO, post.Created)
fullContent := getMarkdownData("blog/" + strconv.Itoa(post.Id) + ".markdown")
// Try to get description from content first
description := extractFirstParagraph(fullContent)
// If description is empty, use post.Description as fallback
if description == "" && post.Description != nil {
description = *post.Description
}
// If still empty, use a default description
if description == "" {
description = "Read more about " + post.Title
}
// Create the full URL for both link and guid
postURL := fmt.Sprintf("%s/blog/%d/%s", siteURL, post.Id, slugifyTitle(post.Title))
guidURL := fmt.Sprintf("%s/blog/%d", siteURL, post.Id)
item := &feeds.Item{
Title: post.Title,
Link: &feeds.Link{Href: postURL},
Description: description,
Author: &feeds.Author{Name: "Brian R. Bondy"},
Created: parsedDate,
Id: guidURL, // This sets the GUID
}
// Add image enclosure if available
if post.ImagePath != nil && *post.ImagePath != "" {
imagePath := *post.ImagePath
if !strings.HasPrefix(imagePath, "/") {
imagePath = "/" + imagePath
}
imageURL := siteURL + imagePath
mimeType := getImageMimeType(imagePath)
if mimeType != "" {
item.Enclosure = &feeds.Enclosure{
Url: imageURL,
Type: mimeType,
Length: "0", // Setting length to 0 as we don't have the file size
}
}
}
items = append(items, item)
}
feed.Items = items
rss, err := feed.ToRss()
if err != nil {
http.Error(w, "Error generating RSS feed", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/xml")
_, err = w.Write([]byte(rss))
if err != nil {
log.Printf("Error writing response: %v", err)
}
}
type sitemapURLSet struct {
XMLName xml.Name `xml:"urlset"`
XMLNS string `xml:"xmlns,attr"`
URLs []sitemapURL `xml:"url"`
}
type sitemapURL struct {
Location string `xml:"loc"`
LastMod string `xml:"lastmod,omitempty"`
}
func generateSitemapHandler(w http.ResponseWriter, _ *http.Request) {
paths := []string{
"/",
"/about",
"/advice",
"/all",
"/books",
"/cheatsheets",
"/contact",
"/interviews",
"/pictures",
"/projects",
"/resume",
"/running",
}
urls := make([]sitemapURL, 0, len(paths)+len(blogPosts))
for _, path := range paths {
urls = append(urls, sitemapURL{Location: siteURL + path})
}
for _, post := range blogPosts {
urls = append(urls, sitemapURL{
Location: siteURL + "/blog/" + strconv.Itoa(post.Id) + "/" + slugifyTitle(post.Title),
LastMod: post.Created,
})
}
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
if _, err := w.Write([]byte(xml.Header)); err != nil {
log.Printf("Error writing sitemap XML header: %v", err)
return
}
if err := xml.NewEncoder(w).Encode(sitemapURLSet{
XMLNS: "http://www.sitemaps.org/schemas/sitemap/0.9",
URLs: urls,
}); err != nil {
log.Printf("Error generating sitemap: %v", err)
}
}
func robotsHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if _, err := fmt.Fprintf(w, "User-agent: *\nAllow: /\n\nSitemap: %s/sitemap.xml\n", siteURL); err != nil {
log.Printf("Error writing robots.txt: %v", err)
}
}
func filtersPageHandler(w http.ResponseWriter, r *http.Request) {
current_year := time.Now().Year()
start_year := 2005
year_range := make([]int, current_year-start_year+1)
for i := range year_range {
year_range[i] = current_year - i
}
p := &data.FiltersPage{
Title: GetTitle("Filters"),
Content: "Test content - filters",
TagCountMap: tagCountMap,
SortedTags: sortedTags,
TagGroups: buildTagGroups(tagCountMap),
MarkdownSlug: "filters",
Years: year_range,
}
err := executeTemplate(w, "filters", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func tagRedirectHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
tag := vars["tag"]
year := 0
if yearStr := r.URL.Query().Get("year"); yearStr != "" {
year, _ = strconv.Atoi(yearStr)
}
// Get filtered posts
filteredPosts := getFilteredPosts(tag, year)
if len(filteredPosts) > 0 {
// Redirect to the first post with the tag/year filters as query params
firstPost := filteredPosts[0]
target := fmt.Sprintf("/blog/%d/%s?tag=%s",
firstPost.Id,
slugifyTitle(firstPost.Title),
tag)
if year != 0 {
target += fmt.Sprintf("&year=%d", year)
}
http.Redirect(w, r, target, http.StatusFound)
return
}
// If no posts found, show error
errorPage(w, "No blog posts found with that tag", "blog")
}
func redirectHandler(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
replacements := map[string]string{
"/blog/page/": "/page/",
"/blog/tagged/": "/tagged/",
"/blog/posted/": "/posted/",
}
for from, to := range replacements {
path = strings.ReplaceAll(path, from, to)
}
http.Redirect(w, r, path, http.StatusFound)
}
func paginationRedirectHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
page, ok := parseIntParam(w, vars["page"], "page", "blog")
if !ok {
return
}
// Get tag and year from query parameters
tag := r.URL.Query().Get("tag")
year := 0
if yearStr := r.URL.Query().Get("year"); yearStr != "" {
parsedYear, parseOk := parseIntParam(w, yearStr, "year", "blog")
if !parseOk {
return
}
year = parsedYear
}
// Get filtered posts
filteredPosts := getFilteredPosts(tag, year)
// Convert page number to post index (0-based)
postIndex := page - 1
if postIndex < 0 || postIndex >= len(filteredPosts) {
errorPage(w, "Invalid page number", "blog")
return
}
// Redirect to the post at that index
post := filteredPosts[postIndex]
target := fmt.Sprintf("/blog/%d/%s",
post.Id,
slugifyTitle(post.Title))
// Add query parameters if present
params := make([]string, 0)
if page > 0 {
params = append(params, fmt.Sprintf("page=%d", page))
}
if tag != "" {
params = append(params, fmt.Sprintf("tag=%s", tag))
}
if year != 0 {
params = append(params, fmt.Sprintf("year=%d", year))
}
if len(params) > 0 {
target += "?" + strings.Join(params, "&")
}
http.Redirect(w, r, target, http.StatusFound)
}
func blogIdRedirectHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, ok := parseIntParam(w, vars["id"], "id", "blog")
if !ok {
return
}
if post, ok := blogPostIdMap[id]; ok {
// Build the canonical URL with the slug
target := fmt.Sprintf("/blog/%d/%s", id, slugifyTitle(post.Title))
// Preserve any query parameters
if r.URL.RawQuery != "" {
target += "?" + r.URL.RawQuery
}
http.Redirect(w, r, target, http.StatusMovedPermanently)
return
}
errorPage(w, "Blog post not found", "blog")
}
func yearRedirectHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
year, ok := parseIntParam(w, vars["year"], "year", "blog")
if !ok {
return
}
// Get tag from query parameters
tag := r.URL.Query().Get("tag")
// Get filtered posts
filteredPosts := getFilteredPosts(tag, year)
if len(filteredPosts) > 0 {
// Redirect to the first post with the year filter as query param
firstPost := filteredPosts[0]
target := fmt.Sprintf("/blog/%d/%s?year=%d",
firstPost.Id,
slugifyTitle(firstPost.Title),
year)
// Add tag if present
if tag != "" {
target += fmt.Sprintf("&tag=%s", tag)
}
http.Redirect(w, r, target, http.StatusFound)
return
}
// If no posts found, show error
errorPage(w, "No blog posts found for that year", "blog")
}
func homePageHandler(w http.ResponseWriter, r *http.Request) {
const previewCount = 4
// Get the most recent posts for preview cards
previewPosts := make([]data.BlogPostPreview, 0, previewCount)
for i := 0; i < previewCount && i < len(blogPosts); i++ {
post := blogPosts[i]
parsedDate, _ := time.Parse(layoutISO, post.Created)
fullContent := getMarkdownData("blog/" + strconv.Itoa(post.Id) + ".markdown")
preview := extractFirstParagraph(fullContent)
previewPosts = append(previewPosts, data.BlogPostPreview{
BlogPost: post,
Preview: template.HTML(preview),
PostDate: parsedDate.Format(layoutUS),
PostUrl: fmt.Sprintf("/blog/%d/%s", post.Id, slugifyTitle(post.Title)),
ReadingTime: post.ReadingTime,
})
}
// Get all posts for the list
allPosts := make([]data.BlogPostPreview, 0, len(blogPosts))
for _, post := range blogPosts {
parsedDate, _ := time.Parse(layoutISO, post.Created)
allPosts = append(allPosts, data.BlogPostPreview{
BlogPost: post,
PostDate: parsedDate.Format(layoutUS),
PostUrl: fmt.Sprintf("/blog/%d/%s", post.Id, slugifyTitle(post.Title)),
ReadingTime: post.ReadingTime,
})
}
p := &data.HomePage{
Title: "Brian R. Bondy",
Posts: previewPosts,
AllPosts: allPosts,
MarkdownSlug: "home",
}
err := executeTemplate(w, "home", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func allPostsHandler(w http.ResponseWriter, r *http.Request) {
// Get tag and year from query parameters
tag := r.URL.Query().Get("tag")
year := 0
if yearStr := r.URL.Query().Get("year"); yearStr != "" {
parsedYear, parseOk := parseIntParam(w, yearStr, "year", "blog")
if !parseOk {
return
}
year = parsedYear
}
// Get filtered posts based on tag and/or year
filteredPosts := getFilteredPosts(tag, year)
allPosts := make([]data.BlogPostPreview, 0, len(filteredPosts))
for _, post := range filteredPosts {
parsedDate, _ := time.Parse(layoutISO, post.Created)
allPosts = append(allPosts, data.BlogPostPreview{
BlogPost: post,
PostDate: parsedDate.Format(layoutUS),
PostUrl: fmt.Sprintf("/blog/%d/%s", post.Id, slugifyTitle(post.Title)),
ReadingTime: post.ReadingTime,
})
}
title := "All Blog Posts"
if tag != "" {
title = fmt.Sprintf("Blog Posts Tagged with \"%s\"", tag)
}
if year != 0 {
if tag != "" {
title = fmt.Sprintf("Blog Posts from %d Tagged with \"%s\"", year, tag)
} else {
title = fmt.Sprintf("Blog Posts from %d", year)
}
}
p := &data.AllPostsPage{
Title: GetTitle(title),
Posts: allPosts,
MarkdownSlug: "all",
Tag: tag,
Year: year,
}
err := executeTemplate(w, "allPosts", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// Keeps it simple with 1 blog post per page
func blogPostPageHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
// Get tag and year from either URL vars or query parameters
tag := vars["tag"]
year := 0
// If not in URL vars, check query parameters
if tag == "" {
tag = r.URL.Query().Get("tag")
}
if yearStr := r.URL.Query().Get("year"); yearStr != "" {
parsedYear, parseOk := parseIntParam(w, yearStr, "year", "blog")
if !parseOk {
return
}
year = parsedYear
} else if yearStr, ok := vars["year"]; ok {
parsedYear, parseOk := parseIntParam(w, yearStr, "year", "blog")
if !parseOk {
return
}
year = parsedYear
}
filteredBlogPosts := getFilteredPosts(tag, year)
// Handle individual blog post view
if idStr, ok := vars["id"]; ok {
id, parseOk := parseIntParam(w, idStr, "id", "blog")
if !parseOk {
return
}
if foundPost, ok := blogPostIdMap[id]; ok {
// Get the filtered posts based on tag/year
filteredPosts := getFilteredPosts(tag, year)
currentIndex := -1
for i, post := range filteredPosts {
if post.Id == id {
currentIndex = i
break
}
}
var nextPost, prevPost *data.BlogPost
if currentIndex > 0 {
prevPost = &filteredPosts[currentIndex-1]
}
if currentIndex < len(filteredPosts)-1 {
nextPost = &filteredPosts[currentIndex+1]
}
parsedDate, _ := time.Parse(layoutISO, foundPost.Created)
p := &data.BlogPostPage{
Title: GetTitle(foundPost.Title),
BlogPost: foundPost,
BlogPostBody: getMarkdownData("blog/" + strconv.Itoa(foundPost.Id) + ".markdown"),
BlogPostDate: parsedDate.Format(layoutUS),
ReadingTime: foundPost.ReadingTime,
NextPost: nextPost,
PrevPost: prevPost,
Tag: tag,
Year: year,
ImagePath: derefString(foundPost.ImagePath),
Description: derefString(foundPost.Description),
ShareUrl: fmt.Sprintf("/blog/%d/%s", foundPost.Id, slugifyTitle(foundPost.Title)),
MarkdownSlug: "blog",
}
err := executeTemplate(w, "blogPost", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
errorPage(w, "No blog posts for this query", "blog")
}
// Handle root URL or other listing pages
if len(filteredBlogPosts) > 0 {
post := filteredBlogPosts[0]
parsedDate, _ := time.Parse(layoutISO, post.Created)
// Set up next post for the first post
var nextPost *data.BlogPost
if len(filteredBlogPosts) > 1 {
nextPost = &filteredBlogPosts[1]
}
p := &data.BlogPostPage{
Title: GetTitle("Blog posts"),
BlogPost: post,
BlogPostBody: getMarkdownData("blog/" + strconv.Itoa(post.Id) + ".markdown"),
BlogPostDate: parsedDate.Format(layoutUS),
ReadingTime: post.ReadingTime,
NextPost: nextPost,
Tag: tag,
Year: year,
ImagePath: derefString(post.ImagePath),
Description: derefString(post.Description),
MarkdownSlug: "blog",
}
err := executeTemplate(w, "blogPost", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
errorPage(w, "No blog posts found", "blog")
}