- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.go
More file actions
Latest commit
159 lines (139 loc) · 4.12 KB
/
Copy pathMain.go
File metadata and controls
159 lines (139 loc) · 4.12 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
)
//User Tag structure for your database
typeUserstruct {
IDint`json:"id"`
Namestring`json:"name"`
Countrystring`json:"country"`
Numberstring`json:"number"`
}
vardb*sql.DB
varerrerror
// function to open connection to mysql database
funcdbConn() (db*sql.DB) {
dbDriver:="mysql"
dbUser:="root"
dbPass:=""// your password, leave it like this if there is no password
dbName:="usertest"// your database name
dbIP:="127.0.0.1:3306"
db, err:=sql.Open(dbDriver, dbUser+":"+dbPass+"@tcp("+dbIP+")/"+dbName)
iferr!=nil {
panic(err.Error())
}
returndb
}
//Index func to view all the records
funcIndex(w http.ResponseWriter, r*http.Request) {
w.Header().Set("Content-Type", "application/json")
db:=dbConn()
varusers []User
result, err:=db.Query("SELECT * FROM users")
iferr!=nil {
panic(err.Error())
}
deferresult.Close()
forresult.Next() {
varpostUser
err=result.Scan(&post.ID, &post.Name, &post.Country, &post.Number)
iferr!=nil {
panic(err.Error())
}
users=append(users, post)
}
json.NewEncoder(w).Encode(users)
deferdb.Close()
}
funcinsertUser(w http.ResponseWriter, r*http.Request) {
w.Header().Set("Content-Type", "application/json")
db:=dbConn()
vars:=mux.Vars(r)
Name:=vars["name"]
Country:=vars["country"]
Number:=vars["number"]
// perform a db.Query insert
stmt, err:=db.Prepare("INSERT INTO users(name, country, number) VALUES(?,?,?)")
iferr!=nil {
panic(err.Error())
}
_, err=stmt.Exec(Name, Country, Number)
iferr!=nil {
panic(err.Error())
}
fmt.Fprintf(w, "New user was created")
deferdb.Close()
}
funcgetUser(w http.ResponseWriter, r*http.Request) {
w.Header().Set("Content-Type", "application/json")
db:=dbConn()
params:=mux.Vars(r)
// perform a db.Query insert
stmt, err:=db.Query("SELECT * FROM users WHERE id = ?", params["id"])
iferr!=nil {
panic(err.Error())
}
deferstmt.Close()
varpostUser
forstmt.Next() {
err=stmt.Scan(&post.ID, &post.Name, &post.Country, &post.Number)
iferr!=nil {
panic(err.Error())
}
}
json.NewEncoder(w).Encode(post)
deferdb.Close()
}
funcdelUser(w http.ResponseWriter, r*http.Request) {
w.Header().Set("Content-Type", "application/json")
db:=dbConn()
params:=mux.Vars(r)
// perform a db.Query insert
stmt, err:=db.Prepare("DELETE FROM users WHERE id = ?")
iferr!=nil {
panic(err.Error())
}
_, err=stmt.Exec(params["id"])
fmt.Fprintf(w, "User with ID = %s was deleted", params["id"])
deferdb.Close()
}
funcupdateUser(w http.ResponseWriter, r*http.Request) {
w.Header().Set("Content-Type", "application/json")
db:=dbConn()
params:=mux.Vars(r)
Name:=params["name"]
Country:=params["country"]
Number:=params["number"]
// perform a db.Query insert
stmt, err:=db.Prepare("Update users SET name = ?, country = ?, number = ? WHERE id = ?")
iferr!=nil {
panic(err.Error())
}
_, err=stmt.Exec(Name, Country, Number, params["id"])
iferr!=nil {
panic(err.Error())
}
fmt.Fprintf(w, "User with ID = %s was updated", params["id"])
deferdb.Close()
}
funcmain() {
log.Println("Server started on: http://localhost:8080")
router:=mux.NewRouter()
//On postman try http://localhost:8080/all with method GET
router.HandleFunc("/all", Index).Methods("GET")
//On postman try http://localhost:8080/add?name=Test&country=LEB&number=7777777 with metho POST
router.HandleFunc("/add", insertUser).Methods("POST").Queries("name", "{name}", "country", "{country}", "number", "{number}")
//On postman try http://localhost:8080/get/1 with method GET
router.HandleFunc("/get/{id}", getUser).Methods("GET")
//On postman try http://localhost:8080/update/1 with method PUT
router.HandleFunc("/update/{id}", updateUser).Methods("PUT").Queries("name", "{name}", "country", "{country}", "number", "{number}")
//On postman try http://localhost:8080/del/1 with method DELETE
router.HandleFunc("/del/{id}", delUser).Methods("DELETE")
http.ListenAndServe(":8080", router)
}