-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.go~
74 lines (70 loc) · 2.09 KB
/
routes.go~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"net/http"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"fmt"
"encoding/json"
"errors"
"strconv"
)
func addRoute(db *sql.DB) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
type Body struct {
FromPlace string
ToPlace string
UserId string
Distance string
Cost string
Mode string
}
var response map[string] string
response = make(map[string] string)
body := Body{}
err := json.NewDecoder(r.Body).Decode(&body)
fmt.Println(body)
defer r.Body.Close()
routeId, err := addNewRoute(db, body.FromPlace, body.ToPlace, body.Distance, body.UserId, body.Cost, body.Mode)
if err != nil {
response["status"] = "Not OK"
response["error"] = err.Error()
} else {
response["status"] = "OK"
response["id"] = routeId
}
json.NewEncoder(w).Encode(response)
}
}
}
func addNewRoute(db *sql.DB, fromPlace string, toPlace string, distance string, userId string, cost string, mode string) (string, error) {
var routeId int64
var wayId string
query := "select id from ROUTE where fromPlace=" + fromPlace + " and toPlace=" + toPlace + ";"
err := db.QueryRow(query).Scan(&routeId)
switch {
case err == sql.ErrNoRows:
query = "insert into ROUTE set fromPlace=" + fromPlace + ",toPlace=" + toPlace +",addedByUser=" + userId + ",distance=" + distance + ";"
res, err := db.Exec(query)
if err == nil {
routeId, _ = res.LastInsertId()
} else {
return "0", err
}
default:
fmt.Println("Route already exist")
}
wayId, err = addWay(db, strconv.Itoa(int(routeId)), mode, cost, distance, userId)
return wayId, err
}
func addWay(db *sql.DB, routeId string, mode string, cost string, distance string, userId string) (string, error) {
query := "insert into WAY set route=" + routeId + ",cost=" + cost + ",mode=" + mode + ",addedByUser=" + userId + ";"
res, err := db.Exec(query)
if err == nil {
wayId, _ := res.LastInsertId()
return strconv.Itoa(int(wayId)), nil
} else {
fmt.Println("return error:" + err.Error())
return "0", err
}
}