![]() Implementing that cleanly while using the json.Encoder pattern is quite difficult. Imagine, for example, that you want to set a Cache-Control header on a successful response, but not set a Cache-Control header if the JSON encoding fails and you have to return an error response. When we call json.NewEncoder(w).Encode(data) the JSON is created and written to the http.ResponseWriter in a single step, which means there’s no opportunity to set HTTP response headers conditionally based on whether the Encode() method returns an error or not. This pattern works, and it’s very neat and elegant, but if you consider it carefully you might notice a slight problem… ![]() "net/http" ) func ( app * application ) healthcheckHandler ( w http. Like so: File: cmd/api/healthcheck.go package main import ( "encoding/json" // New import ![]() Let’s jump in and update our healthcheckHandler so that it uses json.Marshal() to generate a JSON response directly from a Go map - instead of using a fixed-format string like we were before. This effectively means that we’re able to pass any Go type to Marshal() as the v parameter. Note: The v parameter in the above method has the type any. The function signature looks like this: func Marshal ( v any ) ( byte, error ) The way that json.Marshal() works is conceptually quite simple - you pass a native Go object to it as a parameter, and it returns a JSON representation of that object in a byte slice. We’ll explain how both approaches work in this chapter, but - for the purpose of sending JSON in a HTTP response - using json.Marshal() is generally the better choice. You can either call the json.Marshal() function, or you can declare and use a json.Encoder type. Let’s move on to something a bit more exciting and look at how to encode native Go objects (like maps, structs and slices) to JSON.Īt a high-level, Go’s encoding/json package provides two options for encoding things to JSON.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |