Fix type assertions in FormatNumberShort

This commit is contained in:
Noah Petherbridge 2023-12-21 17:30:34 -08:00
parent b43fec144b
commit 319fab3da9
3 changed files with 53 additions and 4 deletions

View File

@ -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{}{

View File

@ -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#")
}

View File

@ -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)
}
}
}