-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
86 lines (76 loc) · 1.83 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
package main
import (
"fmt"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
var db *gorm.DB
var err error
type person struct {
ID uint `json:"id"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
City string `json:"city"`
}
func main() {
// NOTE: See we’re using = to assign the global var
// instead of := which would assign it only in this function
//db, err = gorm.Open("sqlite3", "./gorm.db")
db, _ = gorm.Open("mysql", "root:db@tcp(127.0.0.1:3306)/db?charset=utf8&parseTime=True&loc=Local")
if err != nil {
fmt.Println(err)
}
defer db.Close()
db.AutoMigrate(&person{})
r := gin.Default()
r.GET("/people/", getPeople)
r.GET("/people/:id", getPerson)
r.POST("/people", createPerson)
r.PUT("/people/:id", updatePerson)
r.DELETE("/people/:id", deletePerson)
r.Run(":8080")
}
func deletePerson(c *gin.Context) {
id := c.Params.ByName("id")
var person person
d := db.Where("id = ?", id).Delete(&person)
fmt.Println(d)
c.JSON(200, gin.H{"id #" + id: "deleted"})
}
func updatePerson(c *gin.Context) {
var person person
id := c.Params.ByName("id")
if err := db.Where("id = ?", id).First(&person).Error; err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
}
c.BindJSON(&person)
db.Save(&person)
c.JSON(200, person)
}
func createPerson(c *gin.Context) {
var person person
c.BindJSON(&person)
db.Create(&person)
c.JSON(200, person)
}
func getPerson(c *gin.Context) {
id := c.Params.ByName("id")
var person person
if err := db.Where("id = ?", id).First(&person).Error; err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(200, person)
}
}
func getPeople(c *gin.Context) {
var people []person
if err := db.Find(&people).Error; err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(200, people)
}
}