package data import ( "errors" "fmt" "strconv" "strings" ) var ErrInvalidRuntimeFormat = errors.New("invalid runtime format, should be something like '102 mins'") type Runtime int32 func (r Runtime) MarshalJSON() ([]byte, error) { jsonValue := fmt.Sprintf("%d mins", r) quotedJSONValue := strconv.Quote(jsonValue) return []byte(quotedJSONValue), nil } func (r *Runtime) UnmarshalJSON(jsonValue []byte) error { unquoJSONValue, err := strconv.Unquote(string(jsonValue)) if err != nil { return ErrInvalidRuntimeFormat } jsonParts := strings.Split(unquoJSONValue, " ") if len(jsonParts) != 2 || (jsonParts[1] != "mins" && jsonParts[1] != "minutes") { return ErrInvalidRuntimeFormat } i, err := strconv.ParseInt(jsonParts[0], 10, 32) if err != nil { return ErrInvalidRuntimeFormat } *r = Runtime(i) return nil }