-
Notifications
You must be signed in to change notification settings - Fork 0
/
modes.go~
89 lines (85 loc) · 2.19 KB
/
modes.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"net/http"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"fmt"
"encoding/json"
"errors"
"strconv"
)
func addMode(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 {
UserId string
ModeName 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()
modeName, modeId, err := addNewMode(db, body.ModeName, body.UserId)
if err != nil {
response["status"] = "Not OK"
response["error"] = err.Error()
} else {
response["status"] = "OK"
response["mode"] = modeName
response["id"] = modeId
}
json.NewEncoder(w).Encode(response)
}
}
}
func addNewMode(db *sql.DB, modeName string, userId string) (string, string, error) {
var mode string
query := "select name from MODE where name='" + modeName + "';"
err := db.QueryRow(query).Scan(&mode)
switch {
case err == sql.ErrNoRows:
query = "insert into MODE set name='" + modeName + "',addedByUser=" + userId + ";"
res, err := db.Exec(query)
if err == nil {
modeId, _ := res.LastInsertId()
return modeName, strconv.Itoa(int(modeId)), nil
} else {
return "", "0", err
}
default:
err = errors.New("Place already exist or user does not exist")
return "", "0", err
}
}
func getModes(db *sql.DB) func (w http.ResponseWriter, r *http.Request){
return func (w http.ResponseWriter, r *http.Request){
if r.Method == "POST" {
type Mode struct {
ModeId int64
ModeName string
}
var modes []Mode
var response map[string] interface{}
response = make(map[string] interface{})
query := "select id,name from MODE;"
rows, err := db.Query(query)
if err == nil {
for rows.Next() {
var mode Mode
err = rows.Scan(&mode.ModeId, &mode.ModeName)
if err == nil {
modes = append(modes, mode)
}
}
response["status"] = "OK"
response["modes"] = modes
} else {
response["status"] = "Not OK"
response["error"] = err.Error()
}
json.NewEncoder(w).Encode(response)
}
}
}