Skip to content

JSON marshaling for HTTP APIs

JSON marshaling is the process of converting native Go data structures (like structs and slices) into JSON format for transmission via an HTTP server.^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md] In Go, the encoding/json package is used to handle this serialization, allowing applications to serve data over web endpoints.^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]

Sending Data (Serialization)

To serve data through an API, native data types such as structs must be converted into a byte slice containing JSON.^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]

This is typically achieved using the json.Marshal function within an HTTP handler function^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]:

videoBytes, err := json.Marshal(videos)
if err != nil {
    panic(err)
}
w.Write(videoBytes)

The Write method of the http.ResponseWriter then sends the resulting bytes to the client.^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]

Receiving Data (Deserialization)

When a client sends data via an HTTP POST request, the server reads the request body and converts the JSON payload back into Go objects.^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]

This involves reading the body into a byte slice and then using json.Unmarshal to populate the target data structure^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]:

body, err := ioutil.ReadAll(r.Body)
// ...
var videos []video
err = json.Unmarshal(body, &videos)

This step allows the server to validate the incoming data against the API contract defined by the struct.^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]

Error Handling and Validation

Proper marshaling requires robust error handling. If the input data is malformed or the JSON structure does not match the expected Go types, the unmarshaling process will fail.^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]

Instead of causing the server to crash, it is best practice to catch these errors and return an appropriate HTTP status code, such as 400 Bad Request, to the client^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md].

  • [[Go HTTP server]]
  • [[Structs]]
  • [[API]]

Sources

^[400-devops-09-scripting-language-golang-introduction-part-3http-readme.md]