-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert.go
47 lines (40 loc) · 1.33 KB
/
assert.go
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
package tplfuncs
import (
"fmt"
htmlTemplate "html/template"
textTemplate "text/template"
)
// AssertHelpers returns a text template FuncMap with assert functions
func AssertHelpers() textTemplate.FuncMap {
return textTemplate.FuncMap{
"assertString": assertStringFunc,
"assertInt": assertIntFunc,
"assertFloat": assertFloatFunc,
}
}
// AssertHelpersHTML returns an HTML template FuncMap with assert functions
func AssertHelpersHTML() htmlTemplate.FuncMap {
return htmlTemplate.FuncMap(AssertHelpers())
}
func assertTypeFunc[T any](msg string, input interface{}) error {
_, ok := input.(T)
if !ok {
return fmt.Errorf(msg, input, input)
}
return nil
}
// Doc: `assertString` makes sure the given variable is of type string.
func assertStringFunc(input interface{}) error {
msg := fmt.Sprintf("not a string: %+v (type %T)", input, input)
return assertTypeFunc[string](msg, input)
}
// Doc: `assertInt` makes sure the given variable is of type int.
func assertIntFunc(input interface{}) error {
msg := fmt.Sprintf("not an int: %+v (type %T)", input, input)
return assertTypeFunc[string](msg, input)
}
// Doc: `assertFloat` makes sure the given variable is of type float64.
func assertFloatFunc(input interface{}) error {
msg := fmt.Sprintf("not a float: %+v (type %T)", input, input)
return assertTypeFunc[string](msg, input)
}