Created
March 5, 2022 20:04
-
-
Save arshamalh/040ed4c5525fa0ee301206122a8e329e to your computer and use it in GitHub Desktop.
Simple calculator API server in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"math" | |
"net/http" | |
// go get "github.com/gorilla/mux" | |
"github.com/gorilla/mux" | |
) | |
type MathObject struct { | |
Operand string `json:"operand"` | |
FirstNumber int `json:"first_number"` | |
SecondNumber int `json:"second_number"` | |
} | |
type ResponseObject struct { | |
Message string `json:"message"` | |
Result float64 `json:"result"` | |
Code int `json:"code"` | |
} | |
func (ro *ResponseObject) assignSuccessResponse(result float64) { | |
ro.Result = result | |
ro.Code = 200 | |
ro.Message = "Result calculated successfully!" | |
} | |
func (ro *ResponseObject) assignErrorResponse(code int, msg string) { | |
ro.Code = code | |
ro.Message = msg | |
} | |
func main() { | |
myRouter := mux.NewRouter().StrictSlash(true) | |
myRouter.HandleFunc("/", handleHomePage) | |
myRouter.HandleFunc("/math", handleMath) | |
http.ListenAndServe(":70", myRouter) | |
} | |
func handleHomePage(w http.ResponseWriter, req *http.Request) { | |
fmt.Fprint(w, "Hello friend!\nIt's calculator app!") | |
} | |
func handleMath(w http.ResponseWriter, req *http.Request) { | |
request := &MathObject{} | |
defer req.Body.Close() | |
err := json.NewDecoder(req.Body).Decode(request) | |
if err != nil { | |
fmt.Println("Error Decoding request body!", err) | |
} | |
response := &ResponseObject{} | |
switch request.Operand { | |
case "+": | |
response.assignSuccessResponse( | |
float64(request.FirstNumber + request.SecondNumber), | |
) | |
case "-": | |
response.assignSuccessResponse( | |
float64(request.FirstNumber - request.SecondNumber), | |
) | |
case "*": | |
response.assignSuccessResponse( | |
float64(request.FirstNumber * request.SecondNumber), | |
) | |
case "/": | |
if request.SecondNumber == 0 { | |
response.assignErrorResponse(400, "Bad Request: Division by zero is impossible!") | |
} else { | |
response.assignSuccessResponse(float64(request.FirstNumber) / float64(request.SecondNumber)) | |
} | |
case "^": | |
response.assignSuccessResponse(math.Pow(float64(request.FirstNumber), float64(request.SecondNumber))) | |
default: | |
response.assignErrorResponse(400, "Bad Request: Operand is not defined!") | |
} | |
json.NewEncoder(w).Encode(response) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment