Guest User

Untitled

a guest
Mar 18th, 2018
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. import (
  2. "fmt"
  3. "encoding/json"
  4. "github.com/gorilla/mux"
  5. "log"
  6. "net/http"
  7. )
  8.  
  9. type Calculate struct {
  10. Operand1 string `json:"Operand1,omitempty"`
  11. Operand2 string `json:"Operand2,omitempty"`
  12. Operator string `json:"Operator,omitempty"`
  13. }
  14.  
  15. type Answer struct {
  16. Res string `json:"Res,omitempty"`
  17. }
  18.  
  19.  
  20. func do_Calculation(w http.ResponseWriter, r *http.Request) {
  21. var cal Calculate
  22. var ans Answer
  23. fmt.Println("Request Reached")
  24. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  25. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  26. w.Header().Set("Access-Control-Allow-Origin", "*")
  27. w.WriteHeader(http.StatusOK)
  28. json.NewDecoder(r.Body).Decode(&cal)
  29. // my stuff
  30. // res := do_Operations(convertToFloat(cal.Operand1),convertToFloat(cal.Operand2),cal.Operator)
  31. // ans = Answer{Res: floattostrwithprec(res, 4)}
  32. json.NewEncoder(w).Encode(ans)
  33. }
  34.  
  35.  
  36.  
  37. // main function to boot up everything
  38. func main() {
  39. router := mux.NewRouter()
  40. router.HandleFunc("/calculate", do_Calculation).Methods("POST")
  41. fmt.Println("Server online at port :8000")
  42. log.Fatal(http.ListenAndServe(":8000", router))
  43. }
  44.  
  45. var data = JSON.stringify({
  46. "Operand1": "2.6",
  47. "Operand2": "2.3334",
  48. "Operator": "+"
  49. });
  50.  
  51. var xhr = new XMLHttpRequest();
  52. xhr.withCredentials = true;
  53.  
  54. xhr.addEventListener("readystatechange", function () {
  55. if (this.readyState === 4) {
  56. console.log(this.responseText);
  57. }
  58. });
  59.  
  60. xhr.open("POST", "http://127.0.0.1:8000/calculate");
  61. xhr.setRequestHeader("Content-Type", "application/json");
  62.  
  63. xhr.send(data);
Add Comment
Please, Sign In to add comment