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.

--

--

--

Software Engineer for Big Data distributed systems

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Feren OS January 2021 Snapshot — a spit and polish snapshot

Flutter: People Counter App

Difference between a hard link and a symbolic link

Access files offline in Teams mobile

How to Rerun Failed Test Cases in Cucumber.

Introducing Ownly’s 100M OWN Allocation for Community Rewards this Q4 2021

SpecFlow Tips: Baseclass or Context Injection

CS373 Spring 2022: William Johnston

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

More from Medium

Building Micro-services with GO | Part2

JWT tokens & Go (Golang): Easy explanation

Golang: Start 7 web frameworks with same set of codes

Five Minutes to Start Learning Unit Test in Golang