From 319fab3da96870d89efcecdd0b1e0b309f65b125 Mon Sep 17 00:00:00 2001 From: Noah Petherbridge Date: Thu, 21 Dec 2023 17:30:34 -0800 Subject: [PATCH] Fix type assertions in FormatNumberShort --- pkg/templates/error_pages.go | 8 +++++++- pkg/templates/template_funcs.go | 16 +++++++++++++--- pkg/templates/templates_test.go | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 pkg/templates/templates_test.go diff --git a/pkg/templates/error_pages.go b/pkg/templates/error_pages.go index a42a8b5..065b27b 100644 --- a/pkg/templates/error_pages.go +++ b/pkg/templates/error_pages.go @@ -2,6 +2,8 @@ package templates import ( "net/http" + + "code.nonshy.com/nonshy/website/pkg/log" ) // NotFoundPage is an HTTP handler for 404 pages. @@ -15,7 +17,11 @@ var ForbiddenPage = func() http.HandlerFunc { }() func MakeErrorPage(header string, message string, statusCode int) http.HandlerFunc { - tmpl := Must("errors/error.html") + tmpl, err := LoadTemplate("errors/error.html") + if err != nil { + log.Error("MakeErrorPage(%s): %s", header, err) + return nil + } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(statusCode) if err := tmpl.Execute(w, r, map[string]interface{}{ diff --git a/pkg/templates/template_funcs.go b/pkg/templates/template_funcs.go index c64aed6..a34a037 100644 --- a/pkg/templates/template_funcs.go +++ b/pkg/templates/template_funcs.go @@ -114,9 +114,19 @@ func SincePrettyCoarse() func(time.Time) template.HTML { func FormatNumberShort() func(v interface{}) template.HTML { return func(v interface{}) template.HTML { var number int64 - switch v.(type) { - case int, int64, uint, uint64: - number = v.(int64) + switch t := v.(type) { + case int: + number = int64(t) + case int64: + number = int64(t) + case uint: + number = int64(t) + case uint64: + number = int64(t) + case float32: + number = int64(t) + case float64: + number = int64(t) default: return template.HTML("#INVALID#") } diff --git a/pkg/templates/templates_test.go b/pkg/templates/templates_test.go new file mode 100644 index 0000000..8977a78 --- /dev/null +++ b/pkg/templates/templates_test.go @@ -0,0 +1,33 @@ +package templates_test + +import ( + "html/template" + "testing" + + "code.nonshy.com/nonshy/website/pkg/templates" +) + +func TestNumberF(t *testing.T) { + // The underlying utility.FormatNumberShort already has thorough tests, + // this one will test the interface{} type conversions. + var tests = []struct { + In interface{} + Expect template.HTML + }{ + {int(0), "0"}, + {int64(0), "0"}, + {uint64(0), "0"}, + {uint(0), "0"}, + {int(123), "123"}, + {int64(123), "123"}, + {uint64(123), "123"}, + {uint(123), "123"}, + } + + for _, test := range tests { + actual := templates.FormatNumberShort()(test.In) + if actual != test.Expect { + t.Errorf("Expected %d to be '%s' but got '%s'", test.In, test.Expect, actual) + } + } +}