72 lines
1.3 KiB
Go
72 lines
1.3 KiB
Go
|
package html
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"errors"
|
||
|
"reflect"
|
||
|
"unicode/utf8"
|
||
|
)
|
||
|
|
||
|
func dump(args ...interface{}) (string, error) {
|
||
|
out := ""
|
||
|
for _, a := range args {
|
||
|
str, err := json.MarshalIndent(a, "", " ")
|
||
|
if err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
out += string(str) + "\n"
|
||
|
}
|
||
|
return out, nil
|
||
|
}
|
||
|
|
||
|
func increment(value int) int {
|
||
|
return value + 1
|
||
|
}
|
||
|
|
||
|
func ellipsis(str string, max int) string {
|
||
|
if utf8.RuneCountInString(str) > max {
|
||
|
return string([]rune(str)[0:(max-3)]) + "..."
|
||
|
}
|
||
|
return str
|
||
|
}
|
||
|
|
||
|
func customMap(values ...interface{}) (map[string]interface{}, error) {
|
||
|
if len(values)%2 != 0 {
|
||
|
return nil, errors.New("invalid custoMmap call")
|
||
|
}
|
||
|
customMap := make(map[string]interface{}, len(values)/2)
|
||
|
for i := 0; i < len(values); i += 2 {
|
||
|
key, ok := values[i].(string)
|
||
|
if !ok {
|
||
|
return nil, errors.New("map keys must be strings")
|
||
|
}
|
||
|
customMap[key] = values[i+1]
|
||
|
}
|
||
|
return customMap, nil
|
||
|
}
|
||
|
|
||
|
func defaultVal(src interface{}, defaultValue interface{}) interface{} {
|
||
|
switch typ := src.(type) {
|
||
|
case string:
|
||
|
if typ == "" {
|
||
|
return defaultValue
|
||
|
}
|
||
|
default:
|
||
|
if src == nil {
|
||
|
return defaultValue
|
||
|
}
|
||
|
}
|
||
|
return src
|
||
|
}
|
||
|
|
||
|
func has(v interface{}, name string) bool {
|
||
|
rv := reflect.ValueOf(v)
|
||
|
if rv.Kind() == reflect.Ptr {
|
||
|
rv = rv.Elem()
|
||
|
}
|
||
|
if rv.Kind() != reflect.Struct {
|
||
|
return false
|
||
|
}
|
||
|
return rv.FieldByName(name).IsValid()
|
||
|
}
|