Skip to content

Latest commit

 

History

History

10

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

The encoding/json package

In this lab, we'll be modifying our service to accept a json payload as input and return a json payload as output.

  1. Create an IpsumResp struct containing a single string field Ipsum.
    Note: Capitalization is important here. The encoding/json package cannot access fields that are unexported (lowercase).
  2. At the end of your ipsumHandler, remove the call to fmt.Fprint.
  3. In it's place, create a new json.Encoder initialized with the http.ResponseWriter.
  4. Create an instance of your IpsumResp type, set the Ipsum field, and pass it to your encoder's Encode function.
  5. If the encoding fails, write a http.StatusInternalServerError header, and print out an error message.
  6. Test your webservice to verify that you are now returning a json payload.
  7. Now create an IpsumReq type with two int fields: Wordsand SentenceLength Note: again, casing is important
  8. At the beginning of ipsumHandler, create an instance of IpsumReq and a json.Decoder from the Body of http.Request
  9. Use your decoder's decode method to populate your instance of IpsumReq from the request body.
  10. If the decoding fails, write a http.StatusBadRequest header, and print out an error message.