forked from motyar/restgomysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
167 lines (142 loc) · 4.09 KB
/
server.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
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
160
161
162
163
164
165
166
167
// server.go
//
// REST APIs with Go and MySql.
//
// Usage:
//
// # run go server in the background
// $ go run server.go
package main
import (
"fmt"
"io/ioutil"
"strconv"
"log"
"strings"
"net/http"
"encoding/json"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
type Panda struct {
Id int
Name string
}
//Handle all requests
func Handler(response http.ResponseWriter, request *http.Request){
response.Header().Set("Content-type", "text/html")
webpage, err := ioutil.ReadFile("index.html")
if err != nil {
http.Error(response, fmt.Sprintf("home.html file error %v", err), 500)
}
fmt.Fprint(response, string(webpage));
}
// Respond to URLs of the form /generic/...
func APIHandler(response http.ResponseWriter, request *http.Request){
//Connect to database
db, e := sql.Open("mysql", "username:password@tcp(localhost:3306)/farm")
if( e != nil){
fmt.Print(e)
}
//set mime type to JSON
response.Header().Set("Content-type", "application/json")
err := request.ParseForm()
if err != nil {
http.Error(response, fmt.Sprintf("error parsing url %v", err), 500)
}
//can't define dynamic slice in golang
var result = make([]string,1000)
switch request.Method {
case "GET":
st, err := db.Prepare("select * from pandas limit 10")
if err != nil{
fmt.Print( err );
}
rows, err := st.Query()
if err != nil {
fmt.Print( err )
}
i := 0
for rows.Next() {
var name string
var id int
err = rows.Scan( &id, &name )
panda := &Panda{Id: id,Name:name}
b, err := json.Marshal(panda)
if err != nil {
fmt.Println(err)
return
}
result[i] = fmt.Sprintf("%s", string(b))
i++
}
result = result[:i]
case "POST":
name := request.PostFormValue("name")
st, err := db.Prepare("INSERT INTO pandas(name) VALUES(?)")
if err != nil{
fmt.Print( err );
}
res, err := st.Exec(name)
if err != nil {
fmt.Print( err )
}
if res!=nil{
result[0] = "true"
}
result = result[:1]
case "PUT":
name := request.PostFormValue("name")
id := request.PostFormValue("id")
st, err := db.Prepare("UPDATE pandas SET name=? WHERE id=?")
if err != nil{
fmt.Print( err );
}
res, err := st.Exec(name,id)
if err != nil {
fmt.Print( err )
}
if res!=nil{
result[0] = "true"
}
result = result[:1]
case "DELETE":
id := strings.Replace(request.URL.Path,"/api/","",-1)
st, err := db.Prepare("DELETE FROM pandas WHERE id=?")
if err != nil{
fmt.Print( err );
}
res, err := st.Exec(id)
if err != nil {
fmt.Print( err )
}
if res!=nil{
result[0] = "true"
}
result = result[:1]
default:
}
json, err := json.Marshal(result)
if err != nil {
fmt.Println(err)
return
}
// Send the text diagnostics to the client.
fmt.Fprintf(response,"%v",string(json))
//fmt.Fprintf(response, " request.URL.Path '%v'\n", request.Method)
db.Close()
}
func main(){
port := 1234
var err string
portstring := strconv.Itoa(port)
mux := http.NewServeMux()
mux.Handle("/api/", http.HandlerFunc( APIHandler ))
mux.Handle("/", http.HandlerFunc( Handler ))
// Start listing on a given port with these routes on this server.
log.Print("Listening on port " + portstring + " ... ")
errs := http.ListenAndServe(":" + portstring, mux)
if errs != nil {
log.Fatal("ListenAndServe error: ", err)
}
}