From ff2749ed2c1819a7cd8172d6588c0488ef26bf0f Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Sat, 12 Apr 2025 10:59:15 -0400 Subject: [PATCH] Example custom type to JSON --- internal/data/movies.go | 12 +++++++++--- internal/data/types.go | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 internal/data/types.go diff --git a/internal/data/movies.go b/internal/data/movies.go index 81cf52c..c080a19 100644 --- a/internal/data/movies.go +++ b/internal/data/movies.go @@ -9,7 +9,13 @@ type Movie struct { CreatedAt time.Time `json:"-"` // omits always Title string `json:"title"` Year int32 `json:"year,omitzero"` - Runtime int32 `json:"runtime,omitzero"` - Genres []string `json:"genres,omitzero"` - Version int32 `json:"version"` + // Runtime int32 `json:"runtime,omitzero"` + // Use the Runtime type instead of int32. Note that the omitzero directive will + // still work on this: if the Runtime field has the underlying value 0, then it will + // be considered zero and omitted -- and the MarshalJSON() method we just made + // won't be called at all. + // VSCode will complain though about reflection issue + Runtime Runtime `json:"runtime,omitzero` + Genres []string `json:"genres,omitzero"` + Version int32 `json:"version"` } diff --git a/internal/data/types.go b/internal/data/types.go new file mode 100644 index 0000000..9e732c1 --- /dev/null +++ b/internal/data/types.go @@ -0,0 +1,27 @@ +package data + +import ( + "fmt" + "strconv" +) + +// Declare a custom Runtime type, which has the underlying int32 type +type Runtime int32 + +// The rule about pointers vs. values for receivers is that value methods +// can be invoked on pointers and values, but pointer methods can only +// be invoked on pointers. + +// Implements json.Marshaler interface. +func (r Runtime) MarshalJSON() ([]byte, error) { + // Generate a string containing the movie runtime + jsonValue := fmt.Sprintf("%d mins", r) + + //Use strconv.Quote() function on the string to wrap it in double quotes + // necessary to be valid json + quotedJSONValue := strconv.Quote(jsonValue) + + // convert the string to byte slice and return it + + return []byte(quotedJSONValue), nil +}