-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
112 lines (97 loc) · 2.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
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
package main
import (
"database/sql"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
type custom struct {
Cid int `json:"cid"`
Cname string `json:"cName"`
Age string `json:"age"`
}
func ConnectToDB() (*sql.DB, error) {
db, err := sql.Open("mysql", "root:1234@@tcp(localhost:3306)/chinni")
if err != nil {
return nil, err
}
return db, nil
}
func getCustomerById(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
return
}
db, err := ConnectToDB()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer db.Close()
rows, err := db.Query("select * from customer where cid=?", id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer rows.Close()
var customer custom
for rows.Next() {
if err := rows.Scan(&customer.Cid, &customer.Cname, &customer.Age); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
}
c.JSON(http.StatusOK, customer)
}
func getCustomers(c *gin.Context) {
db, err := ConnectToDB()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer db.Close()
rows, err := db.Query("select * from customer")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer rows.Close()
customers := []custom{}
for rows.Next() {
var customer custom
if err := rows.Scan(&customer.Cid, &customer.Cname, &customer.Age); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
customers = append(customers, customer)
}
c.JSON(http.StatusOK, customers)
}
func UpdateById(c *gin.Context) {
db, err := ConnectToDB()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer db.Close()
var data custom
if err := c.BindJSON(&data); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err = db.QueryRow("insert into customer(cid,cName,age) values(?,?,?)", data.Cid, data.Cname, data.Age).Scan(&data.Cid, &data.Cname, &data.Age)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Data updated successfully"})
}
func main() {
r := gin.Default()
r.GET("/customers", getCustomers)
r.GET("/customer/:id", getCustomerById)
r.POST("customeru", UpdateById)
r.Run(":8081")
}