Go Code Examples: json.Encoder and json.Decoder

These are the code examples to encode/decode json for both client and server sides.

Let’s start with the server side.

Decode Requests

Define Request Parameters: First, you define the struct which represents request parameters.

type UserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
}

json.Decoder: In the request handler, create a decoder with the request body and call the decode method with the pointer of the struct.

func handler(w http.ResponseWriter, r *http.Request) {
var req UserRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
// process with the request parameters
}

Encode Response

Define Response Struct: Likewise, you’ll define the response struct.

type UserResponse struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}

json.Encoder: In the request handler, create an encoder with ResponseWriter, and call the encode method with the response instance.

func handler(w http.ResponseWriter, r *http.Request) {        ...        resp := UserResponse{
ID: 123,
Name: req.Name,
Email: req.Email,
}
err := json.NewEncoder(w).Encode(resp)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}

Now we move on to the client side.

Encode Request

Define Request Struct: Again, we start with defining the request struct.

type UserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
}

json.Encoder: Use bytes.Buffer as a space to write out the json string.

func PostUser(url string, user UserRequest) (*UserResponse, error) {
b := new(bytes.Buffer)
err := json.NewEncoder(b).Encode(user)
if err != nil {
return nil, err
}
resp, err := http.Post(url, "application/json", b)
if err != nil {
return nil, err
}
// decode response
}

Decode Response

Define Response Struct: Pretty much same as the previous one:)

type UserResponse struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}

json.Decoder: Create a decoder with the response body, and call decode with the struct to return.

func PostUser(url string, user UserRequest) (*UserResponse, error) {      ...      var userResp *UserResponse
err = json.NewDecoder(resp.Body).Decode(userResp)
if err != nil {
return nil, err
}
return userResp, nil
}

References

--

--