field_converter.go 772 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package rest
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. var (
  7. fieldConverters = make(map[string]*FieldConverter)
  8. )
  9. type FieldConverter struct {
  10. Pack func(any) any
  11. Unpack func(any) (any, error)
  12. }
  13. func RegisterFieldConverter(name string, converter *FieldConverter) {
  14. fieldConverters[name] = converter
  15. }
  16. func init() {
  17. RegisterFieldConverter(
  18. "time.Time",
  19. &FieldConverter{
  20. Pack: func(v any) any {
  21. t := v.(time.Time)
  22. return t.Format("02.01.2006 15:04")
  23. },
  24. Unpack: func(val any) (any, error) {
  25. ts, check := val.(string)
  26. if !check {
  27. return nil, fmt.Errorf("expected string")
  28. }
  29. layout := "02.01.2006 15:04"
  30. parsedTime, err := time.Parse(layout, ts)
  31. if err != nil {
  32. return nil, err
  33. }
  34. return parsedTime, nil
  35. },
  36. },
  37. )
  38. }