Skip to content

Instantly share code, notes, and snippets.

@suzuken suzuken/a.go
Created Apr 18, 2017

Embed
What would you like to do?
package main
import (
"errors"
"fmt"
"reflect"
"time"
"github.com/lestrrat/go-urlenc"
)
type Bar struct {
T MaybeTime `urlenc:"t,omitempty,string"`
}
type MaybeTime struct {
Valid bool
T time.Time
}
func (m MaybeTime) Value() interface{} {
return m.T
}
func (m *MaybeTime) Set(v interface{}) error {
switch v.(type) {
case string:
m.Valid = true
t, err := time.Parse(`2006-01-02`, v.(string))
if err != nil {
return err
}
m.T = t
case time.Time:
m.Valid = true
m.T = v.(time.Time)
default:
return errors.New("expected string (got: " + reflect.TypeOf(v).String() + ")")
}
return nil
}
func main() {
const src = `t=2017-01-01`
var m Bar
err := urlenc.Unmarshal([]byte(src), &m)
if err != nil {
panic(err)
}
fmt.Printf("v = %+v\n", m)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.