Adding 'Advanced JSON Customization' section in the README.md. Creating a runtime type (internal/data/runtime.go) to show how we can customize a JSON field.
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 56s

This commit is contained in:
Maxime Delporte
2025-10-21 16:26:06 +02:00
parent e7944c3117
commit cc588a1dc0
2 changed files with 51 additions and 0 deletions

33
internal/data/runtime.go Normal file
View File

@@ -0,0 +1,33 @@
package data
import (
"fmt"
"strconv"
)
// Runtime
/*
Declare a custom Runtime type, which has the underlying type int32
(the same as our Movie struct field)
*/
type Runtime int32
// MarshalJSON
/*
Implement a MarshalJSON() method on the Runtime type so that it satisfies
the json.Marshaler interface. This should return the JSON-encoded value
for the movie runtime (in our case, it will return string in the format
"<runtime> mins").
*/
func (r Runtime) MarshalJSON() ([]byte, error) {
// Generate a string containing the movie runtime in the required format.
jsonValue := fmt.Sprintf("%d mins", r)
// Use the strconv.Quote() function on the string to wrap it in double
// quotes. It needs to be surrounded by double quotes in order to be
// a valid *JSON string*.
quotedJSONValue := strconv.Quote(jsonValue)
// Convert the quoted string value to a byte slice and return it.
return []byte(quotedJSONValue), nil
}