-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
110 lines (80 loc) · 2.19 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
package main
import (
"log"
"net/http"
"os"
"simple-rest-api/component"
"simple-rest-api/modules/restaurant/restauranttransport/ginrestaurant"
"strconv"
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
dsn := os.Getenv("DBConnectionStr")
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
if err := runService(db); err != nil {
log.Fatalln(err)
}
}
func runService(db *gorm.DB) error {
r := gin.Default()
r.GET("/ping", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"message": "pong"})
})
appCtx := component.NewAppContext(db)
restaurants := r.Group("/restaurants")
{
restaurants.POST("", ginrestaurant.CreateRestaurant(appCtx))
restaurants.GET("/:id", ginrestaurant.GetRestaurant(appCtx))
restaurants.GET("", ginrestaurant.ListRestaurant(appCtx))
restaurants.PATCH("/:id", func(ctx *gin.Context) {
id, err := strconv.Atoi(ctx.Param("id"))
if err != nil {
ctx.JSON(401, gin.H{"error": err.Error()})
return
}
var data RestaurantUpdate
if err := ctx.ShouldBind(&data); err != nil {
ctx.JSON(401, gin.H{"error": err.Error()})
return
}
if err := db.Where("id = ?", id).Updates(&data).Error; err != nil {
ctx.JSON(401, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"ok": 1})
})
restaurants.DELETE("/:id", func(ctx *gin.Context) {
id, err := strconv.Atoi(ctx.Param("id"))
if err != nil {
ctx.JSON(401, gin.H{"error": err.Error()})
return
}
if err := db.Table(Restaurant{}.TableName()).Where("id = ?", id).Delete(nil).Error; err != nil {
ctx.JSON(401, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"ok": 1})
})
}
return r.Run()
}
type Restaurant struct {
Id int `json:"id" gorm:"column:id;"`
Name string `json:"name" gorm:"column:name;"`
Addr string `json:"address" gorm:"column:addr;"`
}
func (Restaurant) TableName() string {
return "restaurants"
}
type RestaurantUpdate struct {
Name *string `json:"name" gorm:"column:name;"`
Addr *string `json:"address" gorm:"column:addr;"`
}
func (RestaurantUpdate) TableName() string {
return Restaurant{}.TableName()
}