func upd_K(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { key, _ := strconv.Atoi(p.ByName("key")) value := p.ByName("value") data[key] = value rw.WriteHeader(http.StatusCreated) fmt.Fprint(rw, "200") }
func getTrip(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { tripId := p.ByName("trip_id") session, err := mgo.Dial("mongodb://*****:*****@ds045064.mongolab.com:45064/planner") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("planner").C("trip") trip := Trip{} err = c.Find(bson.M{"id": tripId}).One(&trip) if err != nil { fmt.Fprint(rw, "Data not found") return } createTripResponse := CreateTripResponse{} createTripResponse.Id = trip.Id createTripResponse.Status = trip.Status createTripResponse.Starting_from_location_id = trip.Starting_from_location_id createTripResponse.Best_route_location_ids = trip.Best_route_location_ids createTripResponse.Total_uber_costs = trip.Total_uber_costs createTripResponse.Total_uber_duration = trip.Total_uber_duration createTripResponse.Total_distance = trip.Total_distance getTripJson, err := json.Marshal(createTripResponse) if err != nil { log.Fatal(err) } rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusCreated) fmt.Fprint(rw, string(getTripJson)) }
func deleteLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { id := bson.ObjectIdHex(p.ByName("locationID")) err := collection.RemoveId(id) if err != nil { fmt.Printf("got an error deleting a doc %v\n") } rw.WriteHeader(200) }
//PutKey to insert value in a map func (uc MyController) PutKey(w http.ResponseWriter, r *http.Request, p httprouter.Params) { id := p.ByName("id") val := p.ByName("value") eid, _ := strconv.Atoi(id) myMap[eid] = val fmt.Println(myMap) w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) }
func putLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { locationId := p.ByName("location_id") updateLocationRequest := new(UpdateLocationRequest) decoder := json.NewDecoder(req.Body) error := decoder.Decode(&updateLocationRequest) if error != nil { log.Println(error.Error()) http.Error(rw, error.Error(), http.StatusInternalServerError) return } location := Location{} address := Address{updateLocationRequest.Address, updateLocationRequest.City, updateLocationRequest.State, updateLocationRequest.Zip, location} session, err := mgo.Dial("mongodb://*****:*****@ds045064.mongolab.com:45064/planner") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("planner").C("user") result := User{} err = c.Find(bson.M{"userid": locationId}).One(&result) if err != nil { log.Fatal(err) } userName := result.Name user := User{locationId, userName, address} getCoordinates(&user.UserAddress) colQuerier := bson.M{"userid": locationId} change := bson.M{"$set": bson.M{"useraddress": user.UserAddress}} err = c.Update(colQuerier, change) if err != nil { panic(err) } result2 := User{} err = c.Find(bson.M{"userid": locationId}).One(&result2) if err != nil { log.Fatal(err) } outgoingJSON, err := json.Marshal(result2) if err != nil { log.Fatal(err) } rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusCreated) fmt.Fprint(rw, string(outgoingJSON)) }
func getLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { id := bson.ObjectIdHex(p.ByName("locationID")) err := collection.FindId(id).One(&locRes) if err != nil { fmt.Printf("error finding a doc %v\n") } rw.Header().Set("Content-Type", "application/json; charset=UTF-8") rw.WriteHeader(200) json.NewEncoder(rw).Encode(locRes) }
func get_K(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { key, _ := strconv.Atoi(p.ByName("key")) pair := new(Pair) pair.Key = key pair.Value = data[key] oj, err := json.Marshal(pair) if err != nil { //log.Println(error.Error()) http.Error(rw, err.Error(), http.StatusInternalServerError) return } rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusCreated) fmt.Fprint(rw, string(oj)) }
func deleteLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { locationId, _ := strconv.Atoi(p.ByName("location_id")) session, err := mgo.Dial("mongodb://*****:*****@ds045064.mongolab.com:45064/planner") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("planner").C("user") err = c.Remove(bson.M{"userid": locationId}) if err != nil { log.Fatal(err) } rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusCreated) fmt.Fprint(rw, "User Location deleted successfully") }
func handlePutRequests(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { k, _ := strconv.Atoi(p.ByName("key")) value := p.ByName("value") url := "http://localhost:" + getServerForClient(k) + "/keys/" + strconv.Itoa(k) + "/" + value req, err := http.NewRequest("PUT", url, nil) client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() var data interface{} body, _ := ioutil.ReadAll(resp.Body) json.Unmarshal(body, &data) var m = data.(interface{}).(float64) fmt.Fprint(rw, m) }
//DeleteLocation to delete a location func DeleteLocation(w http.ResponseWriter, r *http.Request, p httprouter.Params) { id := p.ByName("idno") oid, _ := strconv.Atoi(id) session, err := mgo.Dial("mongodb://*****:*****@ds041144.mongolab.com:41144/mongo_db") checkError(err) defer session.Close() //insert values in mongo_db session.SetMode(mgo.Monotonic, true) err = session.DB("mongo_db").C("location").RemoveId(oid) if err != nil { panic(err) } w.WriteHeader(200) }
func GetTrip(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { tripDetails := TripDetails{} id := bson.ObjectIdHex(p.ByName("trip_id")) err := collection.FindId(id).One(&tripDetails) if err != nil { fmt.Printf("got error While Searching document %v\n") } if tripDetails.ID == "" { fmt.Fprintf(rw, "LocationID not valid") } else { tripDetails.NextDestinationLocationID = "" tripDetails.UberWaitTime = "" rw.Header().Set("Content-Type", "application/json; charset=UTF-8") rw.Header().Set("Access-Control-Allow-Origin", "*") rw.WriteHeader(200) json.NewEncoder(rw).Encode(tripDetails) } }
func GetKey(rw http.ResponseWriter, request *http.Request, p httprouter.Params) { out := a1 index := i1 port := strings.Split(request.Host, ":") if port[1] == "3001" { out = a2 index = i2 } else if port[1] == "3002" { out = a3 index = i3 } key, _ := strconv.Atoi(p.ByName("key_id")) for i := 0; i < index; i++ { if out[i].Key == key { result, _ := json.Marshal(out[i]) fmt.Fprintln(rw, string(result)) } } }
func PutKeys(rw http.ResponseWriter, request *http.Request, p httprouter.Params) { port := strings.Split(request.Host, ":") key, _ := strconv.Atoi(p.ByName("key_id")) if port[1] == "3000" { a1 = append(a1, KeyVal{key, p.ByName("value")}) i1++ } else if port[1] == "3001" { a2 = append(a2, KeyVal{key, p.ByName("value")}) i2++ } else { a3 = append(a3, KeyVal{key, p.ByName("value")}) i3++ } }
func updateLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { var tempLocRes LocationRes var locRes LocationRes id := bson.ObjectIdHex(p.ByName("locationID")) err := collection.FindId(id).One(&locRes) if err != nil { fmt.Printf("error finding a doc %v\n") } tempLocRes.Name = locRes.Name tempLocRes.Address = locRes.Address tempLocRes.City = locRes.City tempLocRes.State = locRes.State tempLocRes.Zip = locRes.Zip decoder := json.NewDecoder(req.Body) err = decoder.Decode(&tempLocRes) if err != nil { fmt.Errorf("Error in decoding the Input: %v", err) } address := tempLocRes.Address + " " + tempLocRes.City + " " + tempLocRes.State + " " + tempLocRes.Zip address = strings.Replace(address, " ", "%20", -1) locationDetails := getGoogleLoc(address) tempLocRes.Coordinate.Lat = locationDetails.Results[0].Geometry.Location.Lat tempLocRes.Coordinate.Lng = locationDetails.Results[0].Geometry.Location.Lng err = collection.UpdateId(id, tempLocRes) if err != nil { fmt.Printf("got an error updating a doc %v\n") } err = collection.FindId(id).One(&locRes) if err != nil { fmt.Printf("got an error finding a doc %v\n") } rw.Header().Set("Content-Type", "application/json; charset=UTF-8") rw.WriteHeader(201) json.NewEncoder(rw).Encode(locRes) }
func getLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { locationId := p.ByName("location_id") session, err := mgo.Dial("mongodb://*****:*****@ds045064.mongolab.com:45064/planner") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("planner").C("user") result := User{} err = c.Find(bson.M{"userid": locationId}).One(&result) if err != nil { fmt.Fprint(rw, "Data not found") return } outgoingJSON, err := json.Marshal(result) if err != nil { log.Fatal(err) } rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusCreated) fmt.Fprint(rw, string(outgoingJSON)) }
//GetLocation to get location func GetLocation(w http.ResponseWriter, r *http.Request, p httprouter.Params) { id := p.ByName("idno") oid, _ := strconv.Atoi(id) //establish mongodb connection session, err := mgo.Dial("mongodb://*****:*****@ds041144.mongolab.com:41144/mongo_db") checkError(err) defer session.Close() //insert values in mongo_db session.SetMode(mgo.Monotonic, true) c := session.DB(DbName).C(DbCollection) resultResponse := Resp1{} err = c.FindId(oid).One(&resultResponse) uj, _ := json.Marshal(resultResponse) // Write content-type, statuscode, payload w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s", uj) }
//GetKey to display single key value func (uc MyController) GetKey(w http.ResponseWriter, r *http.Request, p httprouter.Params) { id := p.ByName("id") eid, _ := strconv.Atoi(id) var key int var val string fmt.Println("in GET", myMap) for key, val = range myMap { if key == eid { val = myMap[key] break } } uj := DataCache{ DataCachekey: key, DataCachevalue: val, } result, _ := json.Marshal(uj) w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s", result) }
func handleGetRequests(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { k, _ := strconv.Atoi(p.ByName("key")) resp, err := http.Get("http://localhost:" + getServerForClient(k) + "/keys/" + strconv.Itoa(k)) if err == nil { var data interface{} body, _ := ioutil.ReadAll(resp.Body) json.Unmarshal(body, &data) var m = data.(map[string]interface{}) mapData := new(MapData) mapData.Key = int(m["Key"].(float64)) mapData.Value = m["Value"].(string) outgoingJSON, err := json.Marshal(mapData) if err != nil { //log.Println(error.Error()) http.Error(rw, err.Error(), http.StatusInternalServerError) return } rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusCreated) fmt.Fprint(rw, string(outgoingJSON)) } else { fmt.Println(err) } }
func UpdateTrip(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { tripDetails := TripDetails{} locationDetails := LocationRes{} id := bson.ObjectIdHex(p.ByName("trip_id")) err := collection.FindId(id).One(&tripDetails) if err != nil { fmt.Printf("got error while searching a trip %v\n") } currentLocationID := tripDetails.StartingFromLocationID if tripDetails.NextDestinationLocationID == tripDetails.StartingFromLocationID { tripDetails.Status = "trip completed" tripDetails.NextDestinationLocationID = "" tripDetails.StartingFromLocationID = "" tripDetails.UberWaitTime = "" } else { if tripDetails.Status == "requesting..." { if len(tripDetails.BestRouteLocationIds) > 1 { currentLocationID = tripDetails.BestRouteLocationIds[0] x := tripDetails.BestRouteLocationIds[1:len(tripDetails.BestRouteLocationIds)] tripDetails.BestRouteLocationIds = x tripDetails.NextDestinationLocationID = tripDetails.BestRouteLocationIds[0] } else { tripDetails.BestRouteLocationIds = nil currentLocationID = tripDetails.NextDestinationLocationID tripDetails.NextDestinationLocationID = tripDetails.StartingFromLocationID } } else if tripDetails.Status == "planning..." { tripDetails.NextDestinationLocationID = tripDetails.BestRouteLocationIds[0] tripDetails.Status = "requesting..." } url := fmt.Sprintf("http://localhost:8080/locations/%s", currentLocationID) client := http.Client{Timeout: timeout} res, err := client.Get(url) if err != nil { fmt.Errorf("Cannot read localhost LocationsAPI: %v", err) } defer res.Body.Close() decoder := json.NewDecoder(res.Body) err = decoder.Decode(&locationDetails) if err != nil { fmt.Errorf("Error in Google Location JSON: %v", err) } startLat := locationDetails.Coordinate.Lat startLng := locationDetails.Coordinate.Lng url = fmt.Sprintf("http://localhost:8080/locations/%s", tripDetails.NextDestinationLocationID) client = http.Client{Timeout: timeout} res, err = client.Get(url) if err != nil { fmt.Errorf("Error in localhost Google LocationsAPI: %v", err) } defer res.Body.Close() decoder = json.NewDecoder(res.Body) err = decoder.Decode(&locationDetails) if err != nil { fmt.Errorf("Error in Google Location JSON: %v", err) } tripDetails.UberWaitTime = UberRideRequest(startLat, startLng, locationDetails.Coordinate.Lat, locationDetails.Coordinate.Lng) if len(tripDetails.BestRouteLocationIds) == 0 { tripDetails.NextDestinationLocationID = tripDetails.StartingFromLocationID } } //update the request in database err = collection.UpdateId(id, tripDetails) if err != nil { fmt.Printf("got error while updating document %v\n") } rw.Header().Set("Content-Type", "application/json; charset=UTF-8") rw.WriteHeader(200) json.NewEncoder(rw).Encode(tripDetails) fmt.Println("Hiiii!!!!!") }
func updateTrip(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { tripId := p.ByName("trip_id") session, err := mgo.Dial("mongodb://*****:*****@ds045064.mongolab.com:45064/planner") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("planner").C("trip") tripResult := Trip{} err = c.Find(bson.M{"id": tripId}).One(&tripResult) if err != nil { fmt.Fprint(rw, "Data not found") return } if tripResult.Next == len(tripResult.Best_route_location_ids) { fmt.Println("h") //rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusCreated) /*updateTripJson, err := json.Marshal(updateTripResponse) if err != nil { log.Fatal(err) }*/ fmt.Fprint(rw, "Trip is Finised. You have covered all the locations.") return } locationArr := make([]Location, 2) var locId string for i := 0; i < 2; i++ { location := new(Location) if i == 0 { if tripResult.Next == 0 { locId = tripResult.Starting_from_location_id } else { locId = tripResult.Best_route_location_ids[tripResult.Next-1] } } else { locId = tripResult.Best_route_location_ids[tripResult.Next] } resp, err := http.Get("http://*****:*****@ds045064.mongolab.com:45064/planner") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c = session.DB("planner").C("trip") trip := Trip{} trip.Id = tripId var status string if tripResult.Next == len(tripResult.Best_route_location_ids)-1 { status = "finished" } else { status = "requesting" } counter := tripResult.Next + 1 colQuerier := bson.M{"id": tripId} change := bson.M{"$set": bson.M{"uber_wait_time_eta": 0, "next": counter, "status": status}} err = c.Update(colQuerier, change) if err != nil { panic(err) } updateTripResponse := UpdateTripResponse{} updateTripResponse.Id = tripId updateTripResponse.Status = status updateTripResponse.Starting_from_location_id = tripResult.Starting_from_location_id updateTripResponse.Next_destination_location_id = tripResult.Best_route_location_ids[counter-1] updateTripResponse.Best_route_location_ids = tripResult.Best_route_location_ids updateTripResponse.Total_uber_costs = tripResult.Total_uber_costs updateTripResponse.Total_uber_duration = tripResult.Total_uber_duration updateTripResponse.Total_distance = tripResult.Total_distance updateTripResponse.Uber_wait_time_eta = int(eta) rw.Header().Set("Content-Type", "application/json") rw.WriteHeader(http.StatusCreated) updateTripJson, err := json.Marshal(updateTripResponse) if err != nil { log.Fatal(err) } fmt.Fprint(rw, string(updateTripJson)) }
func hello(rw http.ResponseWriter, req *http.Request, p httprouter.Params) { fmt.Fprintf(rw, "Hello, %s!\n", p.ByName("name")) }
//UpdateLocation to update address of location func UpdateLocation(w http.ResponseWriter, r *http.Request, p httprouter.Params) { id := p.ByName("idno") oid, _ := strconv.Atoi(id) request2 := Req2{} response1 := Resp1{} response2 := Resp1{} json.NewDecoder(r.Body).Decode(&request2) //get coordinates from google maps api // Get json data from google maps api var googleMaps Gmaps var urlGoogleMaps string var buffer bytes.Buffer buffer.WriteString("http://maps.google.com/maps/api/geocode/json?address=") buffer.WriteString(strings.Replace(request2.Address, " ", "+", -1)) buffer.WriteString(",+") buffer.WriteString(strings.Replace(request2.City, " ", "+", -1)) buffer.WriteString(",+") buffer.WriteString(request2.State) buffer.WriteString(",+") buffer.WriteString(request2.Zip) buffer.WriteString("&sensor=false") urlGoogleMaps = buffer.String() //fmt.Println(urlGoogleMaps) response, err := http.Get(urlGoogleMaps) if err != nil { fmt.Printf("%s", err) os.Exit(1) } defer response.Body.Close() contents, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Println("error in reading response body") fmt.Printf("%s", err) os.Exit(1) } json.Unmarshal([]byte(contents), &googleMaps) //establish mongodb connection session, err := mgo.Dial("mongodb://*****:*****@ds041144.mongolab.com:41144/mongo_db") checkError(err) defer session.Close() //update values in mongo_db //session.SetMode(mgo.Monotonic, true) c := session.DB(DbName).C(DbCollection) err = c.FindId(oid).One(&response2) response2.Address = request2.Address response2.City = request2.City response2.State = request2.State response2.Zip = request2.Zip response2.Coordinate.Lat = googleMaps.Results[0].Geometry.Location.Lat response2.Coordinate.Lng = googleMaps.Results[0].Geometry.Location.Lng err = c.Update(bson.M{"_id": oid}, response2) checkError(err) //get all values from mongodb err = c.FindId(oid).One(&response1) uj, _ := json.Marshal(response1) // Write content-type, statuscode, payload w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s", uj) }
//RequestACar function to request a car for the next destination func RequestACar(w http.ResponseWriter, r *http.Request, p httprouter.Params) { id := p.ByName("tripid") oid, _ := strconv.Atoi(id) //establish mongodb connection session, err := mgo.Dial("mongodb://*****:*****@ds041144.mongolab.com:41144/mongo_db") checkError(err) defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB(DbName).C(DbCollection) resultResponse := Resp1{} err = c.FindId(oid).One(&resultResponse) checkError(err) responseDB1 := ResponseDB{} resp2 := Resp2{} var respUber1 RespUber if t == 0 { err = c.FindId(resultResponse.StartingFromLocationID).One(&responseDB1) startLatitude := strconv.FormatFloat(responseDB1.Coordinate.Lat, 'g', -1, 64) startLongitude := strconv.FormatFloat(responseDB1.Coordinate.Lng, 'g', -1, 64) err = c.FindId(resultResponse.BestRouteLocationIds[t]).One(&responseDB1) endLatitude := strconv.FormatFloat(responseDB1.Coordinate.Lat, 'g', -1, 64) endLongitude := strconv.FormatFloat(responseDB1.Coordinate.Lng, 'g', -1, 64) var jsonStr = []byte(`{"start_latitude":"` + startLatitude + `","start_longitude":"` + startLongitude + `","end_latitude":"` + endLatitude + `","end_longitude":"` + endLongitude + `","product_id":"a1111c8c-c720-46c3-8534-2fcdd730040d"}`) urlreq := "https://sandbox-api.uber.com/v1/requests" req, err := http.NewRequest("POST", urlreq, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsicHJvZmlsZSIsImhpc3RvcnkiLCJoaXN0b3J5X2xpdGUiXSwic3ViIjoiZjQwMDI4ZjEtNmVmMy00N2QxLWFiOTMtNzlkYWNhNWQ2ZmRhIiwiaXNzIjoidWJlci11czEiLCJqdGkiOiI2NWJmYmQ4NS0wNWZjLTQ2MzUtODRjYS00YzIyOGI1YjgyNTMiLCJleHAiOjE0NTA3NTg4MTMsImlhdCI6MTQ0ODE2NjgxMiwidWFjdCI6ImVFcW40WXRLMmc4NHZOcWZCVUNOdkVQc252aE5ROCIsIm5iZiI6MTQ0ODE2NjcyMiwiYXVkIjoiYnRNSUFXbkpEQzdnUF85SzhfQzBxUjI2VWlNQmx5b2UifQ.CBm5HucgCKwOi-MkWdLKaJ9NMMnfCpHo1gjQ17VkYRFgMDanxPeQYjDZUhWUlKsb3wJmYdWs5CYeVbeFcKm_huIC5DmjNJ4QRODx3-XgetKdfHBwAwuWkUypTfMswOlWV1JONmZur9YBTHHqBIqLbcNKKj7HUtvMvQv0w-Dm29XuSoJtIMnQkDzBqyxUGQjkWcv1WjSqJAsFDUo_m8S6bSSWOR7xQFhQCm4gXH_wZ3JKaPv6bqOkfyUfwZ5YqFZzT5ybWhd6ZoLcUiFRsBZPfAqPA0WgHIdrdeS2DKGcrjboBjL4MOjS9yT5BWdT59RrBZQy19650Q1MqRxf1fSW_A") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) checkError(err) defer resp.Body.Close() contents, errmesg := ioutil.ReadAll(resp.Body) checkError(errmesg) json.Unmarshal([]byte(contents), &respUber1) jsonStr = []byte(`{"status": "accepted"}`) var buffer bytes.Buffer buffer.WriteString("https://sandbox-api.uber.com/v1/sandbox/requests?") buffer.WriteString(respUber1.RequestID) urlreq = buffer.String() req, err = http.NewRequest("POST", urlreq, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsicHJvZmlsZSIsImhpc3RvcnkiLCJoaXN0b3J5X2xpdGUiXSwic3ViIjoiZjQwMDI4ZjEtNmVmMy00N2QxLWFiOTMtNzlkYWNhNWQ2ZmRhIiwiaXNzIjoidWJlci11czEiLCJqdGkiOiI2NWJmYmQ4NS0wNWZjLTQ2MzUtODRjYS00YzIyOGI1YjgyNTMiLCJleHAiOjE0NTA3NTg4MTMsImlhdCI6MTQ0ODE2NjgxMiwidWFjdCI6ImVFcW40WXRLMmc4NHZOcWZCVUNOdkVQc252aE5ROCIsIm5iZiI6MTQ0ODE2NjcyMiwiYXVkIjoiYnRNSUFXbkpEQzdnUF85SzhfQzBxUjI2VWlNQmx5b2UifQ.CBm5HucgCKwOi-MkWdLKaJ9NMMnfCpHo1gjQ17VkYRFgMDanxPeQYjDZUhWUlKsb3wJmYdWs5CYeVbeFcKm_huIC5DmjNJ4QRODx3-XgetKdfHBwAwuWkUypTfMswOlWV1JONmZur9YBTHHqBIqLbcNKKj7HUtvMvQv0w-Dm29XuSoJtIMnQkDzBqyxUGQjkWcv1WjSqJAsFDUo_m8S6bSSWOR7xQFhQCm4gXH_wZ3JKaPv6bqOkfyUfwZ5YqFZzT5ybWhd6ZoLcUiFRsBZPfAqPA0WgHIdrdeS2DKGcrjboBjL4MOjS9yT5BWdT59RrBZQy19650Q1MqRxf1fSW_A") req.Header.Set("Content-Type", "application/json") client = &http.Client{} resp, err = client.Do(req) checkError(err) resp2.ID = resultResponse.ID resp2.NextDestinationLocationID = resultResponse.BestRouteLocationIds[t] resp2.StartingFromLocationID = resultResponse.StartingFromLocationID resp2.TotalDistance = resultResponse.TotalDistance resp2.TotalUberCosts = resultResponse.TotalUberCosts resp2.TotalUberDuration = resultResponse.TotalUberDuration resp2.UberWaitTimeEta = respUber1.Eta for i := 0; i < len(resultResponse.BestRouteLocationIds); i++ { resp2.BestRouteLocationIds = append(resp2.BestRouteLocationIds, resultResponse.BestRouteLocationIds[i]) } nextDestLocID = resultResponse.BestRouteLocationIds[t+1] t = t + 1 if nextDestLocID == resultResponse.StartingFromLocationID { resp2.Status = "completed" // Marshal provided interface into JSON structure uj, _ := json.Marshal(resp2) // Write content-type, statuscode, payload w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s", uj) os.Exit(1) } else { resp2.Status = "requesting" // Marshal provided interface into JSON structure uj, _ := json.Marshal(resp2) // Write content-type, statuscode, payload w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s", uj) } } else if t < len(resultResponse.BestRouteLocationIds)-1 && t != 0 { err = c.FindId(resultResponse.BestRouteLocationIds[t]).One(&responseDB1) startLatitude := strconv.FormatFloat(responseDB1.Coordinate.Lat, 'g', -1, 64) startLongitude := strconv.FormatFloat(responseDB1.Coordinate.Lng, 'g', -1, 64) err = c.FindId(resultResponse.BestRouteLocationIds[t+1]).One(&responseDB1) endLatitude := strconv.FormatFloat(responseDB1.Coordinate.Lat, 'g', -1, 64) endLongitude := strconv.FormatFloat(responseDB1.Coordinate.Lng, 'g', -1, 64) var jsonStr = []byte(`{"start_latitude":"` + startLatitude + `","start_longitude":"` + startLongitude + `","end_latitude":"` + endLatitude + `","end_longitude":"` + endLongitude + `","product_id":"a1111c8c-c720-46c3-8534-2fcdd730040d"}`) urlreq := "https://sandbox-api.uber.com/v1/requests" req, err := http.NewRequest("POST", urlreq, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsicHJvZmlsZSIsImhpc3RvcnkiLCJoaXN0b3J5X2xpdGUiXSwic3ViIjoiZjQwMDI4ZjEtNmVmMy00N2QxLWFiOTMtNzlkYWNhNWQ2ZmRhIiwiaXNzIjoidWJlci11czEiLCJqdGkiOiI2NWJmYmQ4NS0wNWZjLTQ2MzUtODRjYS00YzIyOGI1YjgyNTMiLCJleHAiOjE0NTA3NTg4MTMsImlhdCI6MTQ0ODE2NjgxMiwidWFjdCI6ImVFcW40WXRLMmc4NHZOcWZCVUNOdkVQc252aE5ROCIsIm5iZiI6MTQ0ODE2NjcyMiwiYXVkIjoiYnRNSUFXbkpEQzdnUF85SzhfQzBxUjI2VWlNQmx5b2UifQ.CBm5HucgCKwOi-MkWdLKaJ9NMMnfCpHo1gjQ17VkYRFgMDanxPeQYjDZUhWUlKsb3wJmYdWs5CYeVbeFcKm_huIC5DmjNJ4QRODx3-XgetKdfHBwAwuWkUypTfMswOlWV1JONmZur9YBTHHqBIqLbcNKKj7HUtvMvQv0w-Dm29XuSoJtIMnQkDzBqyxUGQjkWcv1WjSqJAsFDUo_m8S6bSSWOR7xQFhQCm4gXH_wZ3JKaPv6bqOkfyUfwZ5YqFZzT5ybWhd6ZoLcUiFRsBZPfAqPA0WgHIdrdeS2DKGcrjboBjL4MOjS9yT5BWdT59RrBZQy19650Q1MqRxf1fSW_A") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) checkError(err) defer resp.Body.Close() contents, errmesg := ioutil.ReadAll(resp.Body) checkError(errmesg) json.Unmarshal([]byte(contents), &respUber1) jsonStr = []byte(`{"status": "accepted"}`) var buffer bytes.Buffer buffer.WriteString("https://sandbox-api.uber.com/v1/sandbox/requests?") buffer.WriteString(respUber1.RequestID) urlreq = buffer.String() req, err = http.NewRequest("POST", urlreq, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsicHJvZmlsZSIsImhpc3RvcnkiLCJoaXN0b3J5X2xpdGUiXSwic3ViIjoiZjQwMDI4ZjEtNmVmMy00N2QxLWFiOTMtNzlkYWNhNWQ2ZmRhIiwiaXNzIjoidWJlci11czEiLCJqdGkiOiI2NWJmYmQ4NS0wNWZjLTQ2MzUtODRjYS00YzIyOGI1YjgyNTMiLCJleHAiOjE0NTA3NTg4MTMsImlhdCI6MTQ0ODE2NjgxMiwidWFjdCI6ImVFcW40WXRLMmc4NHZOcWZCVUNOdkVQc252aE5ROCIsIm5iZiI6MTQ0ODE2NjcyMiwiYXVkIjoiYnRNSUFXbkpEQzdnUF85SzhfQzBxUjI2VWlNQmx5b2UifQ.CBm5HucgCKwOi-MkWdLKaJ9NMMnfCpHo1gjQ17VkYRFgMDanxPeQYjDZUhWUlKsb3wJmYdWs5CYeVbeFcKm_huIC5DmjNJ4QRODx3-XgetKdfHBwAwuWkUypTfMswOlWV1JONmZur9YBTHHqBIqLbcNKKj7HUtvMvQv0w-Dm29XuSoJtIMnQkDzBqyxUGQjkWcv1WjSqJAsFDUo_m8S6bSSWOR7xQFhQCm4gXH_wZ3JKaPv6bqOkfyUfwZ5YqFZzT5ybWhd6ZoLcUiFRsBZPfAqPA0WgHIdrdeS2DKGcrjboBjL4MOjS9yT5BWdT59RrBZQy19650Q1MqRxf1fSW_A") req.Header.Set("Content-Type", "application/json") client = &http.Client{} resp, err = client.Do(req) checkError(err) resp2.ID = resultResponse.ID resp2.NextDestinationLocationID = resultResponse.BestRouteLocationIds[t] resp2.StartingFromLocationID = resultResponse.StartingFromLocationID resp2.TotalDistance = resultResponse.TotalDistance resp2.TotalUberCosts = resultResponse.TotalUberCosts resp2.TotalUberDuration = resultResponse.TotalUberDuration resp2.UberWaitTimeEta = respUber1.Eta for i := 0; i < len(resultResponse.BestRouteLocationIds); i++ { resp2.BestRouteLocationIds = append(resp2.BestRouteLocationIds, resultResponse.BestRouteLocationIds[i]) } if t+1 >= len(resultResponse.BestRouteLocationIds) { nextDestLocID = resultResponse.BestRouteLocationIds[t] } else { nextDestLocID = resultResponse.BestRouteLocationIds[t+1] } t = t + 1 if nextDestLocID == resultResponse.StartingFromLocationID { resp2.Status = "completed" // Marshal provided interface into JSON structure uj, _ := json.Marshal(resp2) // Write content-type, statuscode, payload w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s", uj) } else { resp2.Status = "requesting" // Marshal provided interface into JSON structure uj, _ := json.Marshal(resp2) // Write content-type, statuscode, payload w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s", uj) } } else if t >= len(resultResponse.BestRouteLocationIds) { err = c.FindId(resultResponse.BestRouteLocationIds[t-1]).One(&responseDB1) startLatitude := strconv.FormatFloat(responseDB1.Coordinate.Lat, 'g', -1, 64) startLongitude := strconv.FormatFloat(responseDB1.Coordinate.Lng, 'g', -1, 64) err = c.FindId(resultResponse.StartingFromLocationID).One(&responseDB1) endLatitude := strconv.FormatFloat(responseDB1.Coordinate.Lat, 'g', -1, 64) endLongitude := strconv.FormatFloat(responseDB1.Coordinate.Lng, 'g', -1, 64) var jsonStr = []byte(`{"start_latitude":"` + startLatitude + `","start_longitude":"` + startLongitude + `","end_latitude":"` + endLatitude + `","end_longitude":"` + endLongitude + `","product_id":"a1111c8c-c720-46c3-8534-2fcdd730040d"}`) urlreq := "https://sandbox-api.uber.com/v1/requests" req, err := http.NewRequest("POST", urlreq, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsicHJvZmlsZSIsImhpc3RvcnkiLCJoaXN0b3J5X2xpdGUiXSwic3ViIjoiZjQwMDI4ZjEtNmVmMy00N2QxLWFiOTMtNzlkYWNhNWQ2ZmRhIiwiaXNzIjoidWJlci11czEiLCJqdGkiOiI2NWJmYmQ4NS0wNWZjLTQ2MzUtODRjYS00YzIyOGI1YjgyNTMiLCJleHAiOjE0NTA3NTg4MTMsImlhdCI6MTQ0ODE2NjgxMiwidWFjdCI6ImVFcW40WXRLMmc4NHZOcWZCVUNOdkVQc252aE5ROCIsIm5iZiI6MTQ0ODE2NjcyMiwiYXVkIjoiYnRNSUFXbkpEQzdnUF85SzhfQzBxUjI2VWlNQmx5b2UifQ.CBm5HucgCKwOi-MkWdLKaJ9NMMnfCpHo1gjQ17VkYRFgMDanxPeQYjDZUhWUlKsb3wJmYdWs5CYeVbeFcKm_huIC5DmjNJ4QRODx3-XgetKdfHBwAwuWkUypTfMswOlWV1JONmZur9YBTHHqBIqLbcNKKj7HUtvMvQv0w-Dm29XuSoJtIMnQkDzBqyxUGQjkWcv1WjSqJAsFDUo_m8S6bSSWOR7xQFhQCm4gXH_wZ3JKaPv6bqOkfyUfwZ5YqFZzT5ybWhd6ZoLcUiFRsBZPfAqPA0WgHIdrdeS2DKGcrjboBjL4MOjS9yT5BWdT59RrBZQy19650Q1MqRxf1fSW_A") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) checkError(err) defer resp.Body.Close() contents, errmesg := ioutil.ReadAll(resp.Body) checkError(errmesg) json.Unmarshal([]byte(contents), &respUber1) jsonStr = []byte(`{"status": "accepted"}`) var buffer bytes.Buffer buffer.WriteString("https://sandbox-api.uber.com/v1/sandbox/requests?") buffer.WriteString(respUber1.RequestID) urlreq = buffer.String() req, err = http.NewRequest("POST", urlreq, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsicHJvZmlsZSIsImhpc3RvcnkiLCJoaXN0b3J5X2xpdGUiXSwic3ViIjoiZjQwMDI4ZjEtNmVmMy00N2QxLWFiOTMtNzlkYWNhNWQ2ZmRhIiwiaXNzIjoidWJlci11czEiLCJqdGkiOiI2NWJmYmQ4NS0wNWZjLTQ2MzUtODRjYS00YzIyOGI1YjgyNTMiLCJleHAiOjE0NTA3NTg4MTMsImlhdCI6MTQ0ODE2NjgxMiwidWFjdCI6ImVFcW40WXRLMmc4NHZOcWZCVUNOdkVQc252aE5ROCIsIm5iZiI6MTQ0ODE2NjcyMiwiYXVkIjoiYnRNSUFXbkpEQzdnUF85SzhfQzBxUjI2VWlNQmx5b2UifQ.CBm5HucgCKwOi-MkWdLKaJ9NMMnfCpHo1gjQ17VkYRFgMDanxPeQYjDZUhWUlKsb3wJmYdWs5CYeVbeFcKm_huIC5DmjNJ4QRODx3-XgetKdfHBwAwuWkUypTfMswOlWV1JONmZur9YBTHHqBIqLbcNKKj7HUtvMvQv0w-Dm29XuSoJtIMnQkDzBqyxUGQjkWcv1WjSqJAsFDUo_m8S6bSSWOR7xQFhQCm4gXH_wZ3JKaPv6bqOkfyUfwZ5YqFZzT5ybWhd6ZoLcUiFRsBZPfAqPA0WgHIdrdeS2DKGcrjboBjL4MOjS9yT5BWdT59RrBZQy19650Q1MqRxf1fSW_A") req.Header.Set("Content-Type", "application/json") client = &http.Client{} resp, err = client.Do(req) checkError(err) resp2.ID = resultResponse.ID resp2.NextDestinationLocationID = resultResponse.StartingFromLocationID resp2.StartingFromLocationID = resultResponse.StartingFromLocationID resp2.TotalDistance = resultResponse.TotalDistance resp2.TotalUberCosts = resultResponse.TotalUberCosts resp2.TotalUberDuration = resultResponse.TotalUberDuration resp2.UberWaitTimeEta = respUber1.Eta for i := 0; i < len(resultResponse.BestRouteLocationIds); i++ { resp2.BestRouteLocationIds = append(resp2.BestRouteLocationIds, resultResponse.BestRouteLocationIds[i]) } resp2.Status = "completed" // Marshal provided interface into JSON structure uj, _ := json.Marshal(resp2) // Write content-type, statuscode, payload w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s", uj) } else if t == len(resultResponse.BestRouteLocationIds)-1 { err = c.FindId(resultResponse.BestRouteLocationIds[t-1]).One(&responseDB1) startLatitude := strconv.FormatFloat(responseDB1.Coordinate.Lat, 'g', -1, 64) startLongitude := strconv.FormatFloat(responseDB1.Coordinate.Lng, 'g', -1, 64) err = c.FindId(resultResponse.BestRouteLocationIds[t]).One(&responseDB1) endLatitude := strconv.FormatFloat(responseDB1.Coordinate.Lat, 'g', -1, 64) endLongitude := strconv.FormatFloat(responseDB1.Coordinate.Lng, 'g', -1, 64) var jsonStr = []byte(`{"start_latitude":"` + startLatitude + `","start_longitude":"` + startLongitude + `","end_latitude":"` + endLatitude + `","end_longitude":"` + endLongitude + `","product_id":"a1111c8c-c720-46c3-8534-2fcdd730040d"}`) urlreq := "https://sandbox-api.uber.com/v1/requests" req, err := http.NewRequest("POST", urlreq, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsicHJvZmlsZSIsImhpc3RvcnkiLCJoaXN0b3J5X2xpdGUiXSwic3ViIjoiZjQwMDI4ZjEtNmVmMy00N2QxLWFiOTMtNzlkYWNhNWQ2ZmRhIiwiaXNzIjoidWJlci11czEiLCJqdGkiOiI2NWJmYmQ4NS0wNWZjLTQ2MzUtODRjYS00YzIyOGI1YjgyNTMiLCJleHAiOjE0NTA3NTg4MTMsImlhdCI6MTQ0ODE2NjgxMiwidWFjdCI6ImVFcW40WXRLMmc4NHZOcWZCVUNOdkVQc252aE5ROCIsIm5iZiI6MTQ0ODE2NjcyMiwiYXVkIjoiYnRNSUFXbkpEQzdnUF85SzhfQzBxUjI2VWlNQmx5b2UifQ.CBm5HucgCKwOi-MkWdLKaJ9NMMnfCpHo1gjQ17VkYRFgMDanxPeQYjDZUhWUlKsb3wJmYdWs5CYeVbeFcKm_huIC5DmjNJ4QRODx3-XgetKdfHBwAwuWkUypTfMswOlWV1JONmZur9YBTHHqBIqLbcNKKj7HUtvMvQv0w-Dm29XuSoJtIMnQkDzBqyxUGQjkWcv1WjSqJAsFDUo_m8S6bSSWOR7xQFhQCm4gXH_wZ3JKaPv6bqOkfyUfwZ5YqFZzT5ybWhd6ZoLcUiFRsBZPfAqPA0WgHIdrdeS2DKGcrjboBjL4MOjS9yT5BWdT59RrBZQy19650Q1MqRxf1fSW_A") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) checkError(err) defer resp.Body.Close() contents, errmesg := ioutil.ReadAll(resp.Body) checkError(errmesg) json.Unmarshal([]byte(contents), &respUber1) jsonStr = []byte(`{"status": "accepted"}`) var buffer bytes.Buffer buffer.WriteString("https://sandbox-api.uber.com/v1/sandbox/requests?") buffer.WriteString(respUber1.RequestID) urlreq = buffer.String() req, err = http.NewRequest("POST", urlreq, bytes.NewBuffer(jsonStr)) req.Header.Set("Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsicHJvZmlsZSIsImhpc3RvcnkiLCJoaXN0b3J5X2xpdGUiXSwic3ViIjoiZjQwMDI4ZjEtNmVmMy00N2QxLWFiOTMtNzlkYWNhNWQ2ZmRhIiwiaXNzIjoidWJlci11czEiLCJqdGkiOiI2NWJmYmQ4NS0wNWZjLTQ2MzUtODRjYS00YzIyOGI1YjgyNTMiLCJleHAiOjE0NTA3NTg4MTMsImlhdCI6MTQ0ODE2NjgxMiwidWFjdCI6ImVFcW40WXRLMmc4NHZOcWZCVUNOdkVQc252aE5ROCIsIm5iZiI6MTQ0ODE2NjcyMiwiYXVkIjoiYnRNSUFXbkpEQzdnUF85SzhfQzBxUjI2VWlNQmx5b2UifQ.CBm5HucgCKwOi-MkWdLKaJ9NMMnfCpHo1gjQ17VkYRFgMDanxPeQYjDZUhWUlKsb3wJmYdWs5CYeVbeFcKm_huIC5DmjNJ4QRODx3-XgetKdfHBwAwuWkUypTfMswOlWV1JONmZur9YBTHHqBIqLbcNKKj7HUtvMvQv0w-Dm29XuSoJtIMnQkDzBqyxUGQjkWcv1WjSqJAsFDUo_m8S6bSSWOR7xQFhQCm4gXH_wZ3JKaPv6bqOkfyUfwZ5YqFZzT5ybWhd6ZoLcUiFRsBZPfAqPA0WgHIdrdeS2DKGcrjboBjL4MOjS9yT5BWdT59RrBZQy19650Q1MqRxf1fSW_A") req.Header.Set("Content-Type", "application/json") client = &http.Client{} resp, err = client.Do(req) checkError(err) resp2.ID = resultResponse.ID resp2.NextDestinationLocationID = resultResponse.BestRouteLocationIds[t] resp2.StartingFromLocationID = resultResponse.StartingFromLocationID resp2.TotalDistance = resultResponse.TotalDistance resp2.TotalUberCosts = resultResponse.TotalUberCosts resp2.TotalUberDuration = resultResponse.TotalUberDuration resp2.UberWaitTimeEta = respUber1.Eta for i := 0; i < len(resultResponse.BestRouteLocationIds); i++ { resp2.BestRouteLocationIds = append(resp2.BestRouteLocationIds, resultResponse.BestRouteLocationIds[i]) } t = t + 1 resp2.Status = "requesting" // Marshal provided interface into JSON structure uj, _ := json.Marshal(resp2) // Write content-type, statuscode, payload w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s", uj) } fmt.Println(t) }