|
15 seconds ago | |
---|---|---|
bin | 4 weeks ago | |
cmd/api | 15 seconds ago | |
internal | 52 minutes ago | |
migrations | 4 weeks ago | |
.air.toml | 4 weeks ago | |
.drone.yaml | 4 weeks ago | |
.gitignore | 4 weeks ago | |
Makefile | 4 weeks ago | |
NOTES.md | 4 weeks ago | |
README.md | 4 weeks ago | |
go.mod | 4 weeks ago | |
go.sum | 4 weeks ago |
README.md
pulley
A Golang HTTP API
Routes
Uses CleanURLs
Method | URL Pattern | Handler | Action |
---|---|---|---|
GET | /v1/healthcheck | healthcheckHandler | Show application information |
GET | /v1/movies | listMoviesHandler | Show the details of all movies |
POST | /v1/movies | createMovieHandler | Create a new movie |
GET | /v1/movies/:id | showMovieHandler | Show the details of a specific movie |
PUT | /v1/movies/:id | editMovieHandler | Update the details of a specific movie |
DELETE | /v1/movies/:id | deleteMovieHandler | Delete a specific movie |
Go JSON Mapping Reference
Go type | JSON type |
---|---|
bool | JSON boolean |
string | JSON string |
int*, uint*, float*, rune | JSON number |
arrays, non-nil slices | JSON array |
structs, non-nil maps | JSON object |
nil pointers, interface values, slices, maps | JSON null |
chan, func, complex* | Not supported |
time.Time | RFC3339-format JSON string |
[]byte | Base64-encoded JSON string |
- Go
time.Time
values (which are actually a struct behind the scenes) will be encoded as a JSON string in RFC 3339 format like "2020-11-08T06:27:59+01:00", rather than as a JSON object. - A
[]byte
slice will be encoded as a base64-encoded JSON string, rather than as a JSON array. So, for example, a byte slice of[]byte{'h','e','l','l','o'}
would appear as "aGVsbG8=" in the JSON output. The base64 encoding uses padding and the standard character set. - Encoding of nested objects is supported. So, for example, if you have a slice of structs in Go that will encode to an array of objects in JSON.
- Channels, functions and complex number types cannot be encoded. If you try to do so, you’ll get a json.
UnsupportedTypeError
error at runtime. - Any pointer values will encode as the value pointed to.
- Struct fields MUST be exported for them to be serialize
- If a struct field doesn’t have an explicit value set, then the JSON-encoding of the zero value for the field will appear in the output.
- It’s also possible to control the visibility of individual struct fields in the JSON by using the
omitzero
and-
struct tag directives.- The
-
(hyphen) directive can be used when you never want a particular struct field to appear in the JSON output. This is useful for fields that contain internal system information that isn’t relevant to your users, or sensitive information that you don’t want to expose (like the hash of a password) - In contrast, the omitzero directive hides a field in the JSON output if and only if the value is the zero value for the field type. If you want to use omitzero and not change the key name then you can leave it blank in the struct tag — like this:
json:",omitzero"
. Notice that the leading comma is still required.
- The
- An older
omiteby creating a custom envelope map with the underlying type map[string]any.mpty
struct field( Go <= 1.23) has some "stranger" behaviors that overlap with omitzero.omitempty
will not omit structs, even if all the struct fields have their zero value.omitempty
will not omit time.Time types, even if they have their zero value. Note that this is because the time.Time type is actually a struct behind-the-scenes, so this is really just a special case of the bullet point above.omitempty
will not omit arrays, even if they have their zero value.omitempty
will omit empty slices and maps (that is, initialized slices and maps with length zero) as well as nil slices and maps.
- A final, less-frequently-used, struct tag directive is
string
. You can use this on individual struct fields to force the data to be represented as a string in the JSON output.- Note that the string directive will only work on struct fields which have
int*
,uint*
,float*
orbool
types. For any other type of struct field it will have no effect.
- Note that the string directive will only work on struct fields which have
- Check out the [appendix chapter](file:///home/toor/Desktop/lets-go-further-v1.24.1/lets-go-further.html/21. 04-json-encoding-nuances.html) for additional nuances on encoding types.
The pattern err := json.NewEncoder(w).Encode(data)
looks elegant but creates issues when needing to coditionally set headers in response to an error. The performance difference between json.Marshal
and json.Encoder
are so small(tiny more mem and 1 extra alloc) that it's just cleaner to use json.Marshal
.
How Go Marshals JSON
When Go is encoding a particular type to JSON, it looks to see if the type has a MarshalJSON() method implemented on it. If it has, then Go will call this method to determine how to encode it.
Here is the interface
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
If the type doesn’t have a MarshalJSON() method, then Go will fall back to trying to encode it to JSON based on its own internal set of rules.
Enveloping Respsonses
{
"movie": {
"id": 123,
"title": "Casablanca",
"runtime": 102,
"genres": [
"drama",
"romance",
"war"
],
"version":1
}
}
Enveloping response data like this isn’t strictly necessary, and whether you choose to do so is partly a matter of style and taste. But there are a few tangible benefits:
- Including a key name (like "movie") at the top-level of the JSON helps make the response more self-documenting. For any humans who see the response out of context, it is a bit easier to understand what the data relates to.
- It reduces the risk of errors on the client side, because it’s harder to accidentally process one response thinking that it is something different. To get at the data, a client must explicitly reference it via the "movie" key.
- If we always envelope the data returned by our API, then we mitigate a security vulnerability in older browsers which can arise if you return a JSON array as a response.