-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
114 lines (91 loc) · 1.93 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
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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
_ "github.com/go-sql-driver/mysql"
)
var (
db *sql.DB
)
func main() {
configureConnectionDB()
http.HandleFunc("/ping", ping)
http.HandleFunc("/getUsers", getUsers)
http.HandleFunc("/postUser", postUser)
fmt.Println("Api rodando na porta 1200")
log.Fatal(http.ListenAndServe(":1200", nil))
}
func ping(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "pong")
}
func getUsers(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Nao autorizado", 401)
return
}
// users := []User{
// User{
// Name: "Esteves",
// Age: 22,
// },
// User{
// Name: "Gerepe",
// Age: 22,
// },
// }
users := []User{}
rows, err := db.Query("Select * from User")
if err != nil {
fmt.Println(err)
}
for rows.Next() {
user := User{}
err := rows.Scan(&user.Id, &user.Name, &user.Age)
if err != nil {
fmt.Println(err)
}
users = append(users, user)
}
defer rows.Close()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
func postUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Nao autorizado", http.StatusUnauthorized)
return
}
decoder := json.NewDecoder(r.Body)
user := User{}
errDecode := decoder.Decode(&user)
if errDecode != nil {
fmt.Println("Error decoder", errDecode)
return
}
query := "Insert into User values(?,?,?)"
_, err := db.Exec(query, user.Id, user.Name, user.Age)
if err != nil {
fmt.Println("Error", err)
}
w.WriteHeader(http.StatusCreated)
}
type User struct {
Id int
Name string
Age int
}
func configureConnectionDB() {
var errorBanco error
db, errorBanco = sql.Open("mysql", "root:123@tcp(localhost:3306)/go")
if errorBanco != nil {
fmt.Println(errorBanco)
}
err := db.Ping()
if err != nil {
fmt.Println("Erro no ping do banco")
}
fmt.Println("Connect Mysql :)")
}