Just a quick one!
Go has a new API for JSON and I’ve gone through and upgraded Eir’s endpoints to use it.
Here are some of the changes for a few different usages of encoding/json v1:
Swapping the import
import (
"bytes"
"context"
- "encoding/json"
+ "encoding/json/jsontext"
+ "encoding/json/v2"
"log"
Writing directly to an io.Writer
func JSONResponse(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
- json.NewEncoder(w).Encode(data)
+ json.MarshalWrite(w, data)
}
Encoding through a jsontext.Encoder
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
- _ = json.NewEncoder(w).Encode(users)
+ _ = json.MarshalEncode(jsontext.NewEncoder(w), users)
Decoding from a stream
var req LoginRequest
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ if err := json.UnmarshalDecode(jsontext.NewDecoder(r.Body), &req); err != nil {
utils.BadRequest(w, utils.MsgInvalidRequestBody)
return
}
Reading directly from an io.Reader and rejecting unknown fields
- dec := json.NewDecoder(r.Body)
- dec.DisallowUnknownFields()
- if err := dec.Decode(&reqBody); err != nil && !errors.Is(err, io.EOF) {
+ if err := json.UnmarshalRead(r.Body, &reqBody, json.RejectUnknownMembers(true)); err != nil {
utils.ErrorResponseWithContext(r, w, http.StatusBadRequest, "Invalid JSON in request body", err, userID, map[string]interface{}{
"endpoint": "/v1/meditations",
})
Indented output
- enc := json.NewEncoder(os.Stdout)
- enc.SetIndent("", " ")
- if err := enc.Encode(parts); err != nil {
+ if err := json.MarshalWrite(os.Stdout, parts, jsontext.WithIndent(" ")); err != nil {
json.RawMessage -> jsontext.Value
// Validate it's valid JSON (schema is enforced by API)
- var check json.RawMessage
+ var check jsontext.Value
if err := json.Unmarshal([]byte(text), &check); err != nil {
Potentially less tiny impact
Even if the code changes themselves are small, some updates with v2 may be worth keeping in mind:
- Field names become case sensitive. E.g., need to make sure the client sends JSON request bodies in the right case for decoding on the backend.
- Nil slices and maps come out as valid JSON as opposed to
null(generally what we want anyway - I was able to remove an additional workaround I’d had to use for this earlier with v1). Related: seeomitemptyandomitzeroproperties as well. - No trailing newline added with v2
json.MarshalWrite(), butjson.MarshalEncode()does. Worth keeping in mind for output consistency between the two.