-
-
Save suzuken/0f318976a6ba976b9c56a90ec3082574 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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