Skip to content

Instantly share code, notes, and snippets.

@thwarted
Created February 3, 2015 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thwarted/8d4bb84c29a567972e9d to your computer and use it in GitHub Desktop.
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
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