Created
February 3, 2015 19:37
-
-
Save thwarted/8d4bb84c29a567972e9d to your computer and use it in GitHub Desktop.
example of matching a format and returning an error in go from JSON parsing
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
type ZipP4 string | |
func (z *ZipP4) MarshalJSON() ([]byte, error) { | |
return []byte(fmt.Sprintf(`"%s"`, *z)), nil | |
} | |
func (z *ZipP4) UnmarshalJSON(b []byte) (err error) { | |
if z == nil { | |
return errors.New("ZipP4: UnmarshalJSON on nil pointer") | |
} | |
if matched, _ := regexp.MatchString(`^"[0-9]{5}[0-9]{4}"$`, string(b)); matched == false { | |
return errors.New("zipcode+4 format must be zzzzzpppp") | |
} | |
*z = ZipP4(string(b[1:10])) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment