Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import (
- "fmt"
- "encoding/json"
- "github.com/gorilla/mux"
- "log"
- "net/http"
- )
- type Calculate struct {
- Operand1 string `json:"Operand1,omitempty"`
- Operand2 string `json:"Operand2,omitempty"`
- Operator string `json:"Operator,omitempty"`
- }
- type Answer struct {
- Res string `json:"Res,omitempty"`
- }
- func do_Calculation(w http.ResponseWriter, r *http.Request) {
- var cal Calculate
- var ans Answer
- fmt.Println("Request Reached")
- w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
- w.Header().Set("Content-Type", "application/json; charset=UTF-8")
- w.Header().Set("Access-Control-Allow-Origin", "*")
- w.WriteHeader(http.StatusOK)
- json.NewDecoder(r.Body).Decode(&cal)
- // my stuff
- // res := do_Operations(convertToFloat(cal.Operand1),convertToFloat(cal.Operand2),cal.Operator)
- // ans = Answer{Res: floattostrwithprec(res, 4)}
- json.NewEncoder(w).Encode(ans)
- }
- // main function to boot up everything
- func main() {
- router := mux.NewRouter()
- router.HandleFunc("/calculate", do_Calculation).Methods("POST")
- fmt.Println("Server online at port :8000")
- log.Fatal(http.ListenAndServe(":8000", router))
- }
- var data = JSON.stringify({
- "Operand1": "2.6",
- "Operand2": "2.3334",
- "Operator": "+"
- });
- var xhr = new XMLHttpRequest();
- xhr.withCredentials = true;
- xhr.addEventListener("readystatechange", function () {
- if (this.readyState === 4) {
- console.log(this.responseText);
- }
- });
- xhr.open("POST", "http://127.0.0.1:8000/calculate");
- xhr.setRequestHeader("Content-Type", "application/json");
- xhr.send(data);
Add Comment
Please, Sign In to add comment