12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- package rest
- import (
- "fmt"
- "time"
- )
- var (
- fieldConverters = make(map[string]*FieldConverter)
- )
- type FieldConverter struct {
- Pack func(any) any
- Unpack func(any) (any, error)
- }
- func RegisterFieldConverter(name string, converter *FieldConverter) {
- fieldConverters[name] = converter
- }
- func init() {
- RegisterFieldConverter(
- "time.Time",
- &FieldConverter{
- Pack: func(v any) any {
- t := v.(time.Time)
- return t.Format("02.01.2006 15:04")
- },
- Unpack: func(val any) (any, error) {
- ts, check := val.(string)
- if !check {
- return nil, fmt.Errorf("expected string")
- }
- layout := "02.01.2006 15:04"
- parsedTime, err := time.Parse(layout, ts)
- if err != nil {
- return nil, err
- }
- return parsedTime, nil
- },
- },
- )
- }
|