-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (70 loc) · 1.65 KB
/
main.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
package main
import (
"fmt"
"net/http"
"log"
"encoding/json"
"github.com/gorilla/mux"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"os"
)
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
func Handler(w http.ResponseWriter, r *http.Request) {
// Connect to database
host := os.Getenv("DBHOST")
dsn := fmt.Sprintf("root@tcp(%s:3306)/users", host)
db, err := sql.Open("mysql", dsn)
if err != nil{
fmt.Println("Error validating sql Open arguments", err)
panic(err.Error())
}
defer db.Close()
err = db.Ping()
if err != nil {
fmt.Println("Error verifiing connection with db.Ping", err)
panic(err.Error)
}
switch r.Method {
case "GET":
var users []User
w.Header().Set("Content-Type", "application/json")
// read from database
result, err := db.Query("SELECT * from users")
if err != nil {
panic(err)
}
defer result.Close()
for result.Next() {
var user User
err := result.Scan(&user.ID, &user.Name)
if err != nil {
panic(err.Error())
}
users = append(users, user)
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(users)
case "POST":
w.Header().Set("Content-Type", "application/json")
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
panic(err.Error())
}
insert, err := db.Query("INSERT INTO users(`id`,`name`) VALUES(?,?)",user.ID, user.Name )
if err != nil {
panic(err.Error())
}
defer insert.Close()
}
}
func main(){
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/users", Handler)
router.HandleFunc("/user", Handler)
log.Fatal(http.ListenAndServe(":3001", router))
}