ch4.4
This commit is contained in:
@@ -10,10 +10,10 @@ import (
|
|||||||
|
|
||||||
func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Request) {
|
func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
var input struct {
|
var input struct {
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Year int32 `json:"year"`
|
Year int32 `json:"year"`
|
||||||
Runtime int32 `json:"runtime"`
|
Runtime data.Runtime `json:"runtime"`
|
||||||
Genres []string `json:"genres"`
|
Genres []string `json:"genres"`
|
||||||
}
|
}
|
||||||
|
|
||||||
err := app.readJSON(w, r, &input)
|
err := app.readJSON(w, r, &input)
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
package data
|
package data
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ErrInvalidRuntimeFormat = errors.New("invalid runtime format")
|
||||||
|
|
||||||
type Runtime int32
|
type Runtime int32
|
||||||
|
|
||||||
func (r Runtime) MarshalJSON() ([]byte, error) {
|
func (r Runtime) MarshalJSON() ([]byte, error) {
|
||||||
@@ -13,3 +17,23 @@ func (r Runtime) MarshalJSON() ([]byte, error) {
|
|||||||
quotedJSONValue := strconv.Quote(jsonValue)
|
quotedJSONValue := strconv.Quote(jsonValue)
|
||||||
return []byte(quotedJSONValue), nil
|
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
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user