Format the response

In each web service request handler, we use the setFormat function in conjunction with the getFormat function to format the response data. We are simply using JSON in our example code, it is easy to see how we could extend our implementation to include formats such as XML and CSV.

(We're still in interfaces/webservice_helpers.go.):

func setFormat(format string, data interface{}) ([]byte, error) {   var apiOutput []byte   if format == "json" {      output, err := json.Marshal(data)      if err != nil {         return nil, errors.Wrap(err, "unable to marshal data to json")      }      apiOutput = output   } else {      Error.Printf("invalid data format encountered")      apiOutput = ErrorResponse   }   return apiOutput, nil}

The handler helpers are similar in format. Let’s ...

Get Learning Functional Programming in Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.