github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/internal/web/utils/schema/schema.go (about) 1 //nolint:gochecknoglobals,gochecknoinits 2 package schema 3 4 import ( 5 "net/url" 6 "reflect" 7 "time" 8 9 "github.com/gorilla/schema" 10 ) 11 12 var ( 13 encoder = schema.NewEncoder() 14 decoder = schema.NewDecoder() 15 ) 16 17 var invalidDecodeValue = reflect.Value{} 18 19 func init() { 20 encoder.SetAliasTag("json") 21 encoder.RegisterEncoder(time.Time{}, func(v reflect.Value) string { 22 t := v.Interface().(time.Time) //nolint:forcetypeassert 23 return t.Format(time.RFC3339) 24 }) 25 26 decoder.SetAliasTag("json") 27 decoder.IgnoreUnknownKeys(true) 28 decoder.RegisterConverter(time.Time{}, func(s string) reflect.Value { 29 if time, err := time.Parse(time.RFC3339, s); err == nil { 30 return reflect.ValueOf(time) 31 } 32 return invalidDecodeValue 33 }) 34 } 35 36 func Encode(src interface{}, dst url.Values) error { 37 return encoder.Encode(src, dst) 38 } 39 40 func Decode(dst interface{}, src url.Values) error { 41 return decoder.Decode(dst, src) 42 }