bouncer/internal/format/table/prop.go

62 lines
1.1 KiB
Go
Raw Normal View History

2023-04-24 20:52:12 +02:00
package table
import (
"encoding/json"
"fmt"
"reflect"
"forge.cadoles.com/cadoles/bouncer/internal/format"
"github.com/pkg/errors"
)
const (
hintCompactModeMaxColumnWidth format.PropHintName = "compactModeMaxColumnWidth"
)
func WithCompactModeMaxColumnWidth(max int) format.PropHintFunc {
return format.WithPropHint(hintCompactModeMaxColumnWidth, max)
}
func getProps(d any) []format.Prop {
props := make([]format.Prop, 0)
v := reflect.Indirect(reflect.ValueOf(d))
typeOf := v.Type()
for i := 0; i < v.NumField(); i++ {
name := typeOf.Field(i).Name
props = append(props, format.NewProp(name, name))
}
return props
}
func getFieldValue(obj any, name string) string {
v := reflect.Indirect(reflect.ValueOf(obj))
fieldValue := v.FieldByName(name)
if !fieldValue.IsValid() {
return ""
}
switch fieldValue.Kind() {
case reflect.Map:
fallthrough
case reflect.Struct:
fallthrough
case reflect.Slice:
fallthrough
case reflect.Interface:
json, err := json.Marshal(fieldValue.Interface())
if err != nil {
panic(errors.WithStack(err))
}
return string(json)
default:
return fmt.Sprintf("%v", fieldValue)
}
}