Calculator Restful API with GO

  • The request has an operand, like plus, minus, a left and a right side of the operand.
  • The response has an error value and a result.
  • The handler again receives an http.ResponseWriter and a pointer to a request.
  • We defer the Body.Close to make sure it’s closed.
  • The first step is to create a new json decoder and an empty request.
  • Next, we try to decode the request. If there is an error, we use the http.Error to send the error back with the appropriate error value. Otherwise, we do the work.
  • We create a response and then depending on the operand, if it’s a plus, we’ll do a plus operation, if it’s a minus, we’ll do a minus operation, et cetera, et cetera. And in the case of division, if we are asked to divide by zero, we will return an error. The same if it’s an unknown operation, the response and error.
  • The final step is to encode the result. We set the Content-Type header to application/json and if there was an error, we are going to write http BadRequest status and at the end, we’re going to encode the response in a json format into w. If you failed encoding, we’re just going to log that we failed to encode.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
aditya goel

aditya goel

Software Engineer for Big Data distributed systems