From dbd1c6eee8071f43d0e9b6c12c7c2da9a42c9678 Mon Sep 17 00:00:00 2001 From: lbenedar Date: Tue, 17 Mar 2026 12:53:48 +0300 Subject: [PATCH] ch4.4 --- cmd/api/movies.go | 8 ++++---- internal/data/runtime.go | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/cmd/api/movies.go b/cmd/api/movies.go index 547174e..467cd70 100644 --- a/cmd/api/movies.go +++ b/cmd/api/movies.go @@ -10,10 +10,10 @@ import ( func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Request) { var input struct { - Title string `json:"title"` - Year int32 `json:"year"` - Runtime int32 `json:"runtime"` - Genres []string `json:"genres"` + Title string `json:"title"` + Year int32 `json:"year"` + Runtime data.Runtime `json:"runtime"` + Genres []string `json:"genres"` } err := app.readJSON(w, r, &input) diff --git a/internal/data/runtime.go b/internal/data/runtime.go index 85295bb..59e6260 100644 --- a/internal/data/runtime.go +++ b/internal/data/runtime.go @@ -1,10 +1,14 @@ package data import ( + "errors" "fmt" "strconv" + "strings" ) +var ErrInvalidRuntimeFormat = errors.New("invalid runtime format") + type Runtime int32 func (r Runtime) MarshalJSON() ([]byte, error) { @@ -13,3 +17,23 @@ func (r Runtime) MarshalJSON() ([]byte, error) { quotedJSONValue := strconv.Quote(jsonValue) return []byte(quotedJSONValue), nil } + +func (r *Runtime) UnmarshalJSON(jsonValue []byte) error { + unquotedJSONValue, err := strconv.Unquote(string(jsonValue)) + + if err != nil { + return ErrInvalidRuntimeFormat + } + + parts := strings.Split(unquotedJSONValue, " ") + if len(parts) != 2 || parts[1] != "mins" { + return ErrInvalidRuntimeFormat + } + + i, err := strconv.ParseInt(parts[0], 10, 32) + if err != nil { + return ErrInvalidRuntimeFormat + } + *r = Runtime(i) + return nil +}