Calculator Restful API with GO

aditya goel
3 min readFeb 11, 2022

--

In case you are landing here directly, it’s strongly suggested that you go and read through this for fundamentals.

In this blog, we shall be looking at following concepts :- Launching Maths Calculator as Restful API with JSON req/resp in GO.

Question :- Demonstrate the handler that receives a request for a maths operation in a JSON format and sends back a JSON response.

Step #1.) First, we define the following imports And of course, we need to import the encoding through json package.

Step #2.) structures for the request and the response.

  • 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.

Step #3.) Now, we define the handler :-

  • 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.

Step #4.) Don’t forget to mount your new handler. This time everyone going to /math on our server, the math handler is going to get called.

Step #5.) Let’s go back to our server and we start it. I’m going to use the Postman to make a request :-

Let’s test it again with some sample value :-

That’s all in this section. If you liked reading this blog, kindly do press on clap button multiple times, to indicate your appreciation. We would see you in next series.

References :-

--

--