-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
99 lines (74 loc) · 1.89 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
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Book struct {
ID string `json:"id" gorm:"primaryKey"`
Title string `json:"title"`
Author string `json:"author"`
}
var db *gorm.DB
func Migrate(db *gorm.DB) {
db.AutoMigrate(&Book{})
}
func connectToDb() {
var err error
dsn := "host=localhost user=myuser password=123 dbname=mydb port=5432 sslmode=disable"
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect to database")
}
Migrate(db)
}
func main() {
connectToDb()
router := gin.Default()
router.GET("/books/:id", getBook)
router.POST("/books", createBook)
router.PUT("/books/:id", updateBook)
router.DELETE("/books/:id", deleteBook)
router.Run("localhost:8000")
}
func getBook(c *gin.Context) {
id := c.Param("id")
var book Book
if err := db.First(&book, "id = ?", id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "book not found"})
return
}
c.JSON(http.StatusOK, book)
}
func createBook(c *gin.Context) {
var newBook Book
if err := c.ShouldBindJSON(&newBook); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
db.Create(&newBook)
c.JSON(http.StatusCreated, newBook)
}
func updateBook(c *gin.Context) {
id := c.Param("id")
var updatedBook Book
if err := db.First(&updatedBook, "id = ?", id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Book not found"})
return
}
if err := c.ShouldBindJSON(&updatedBook); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
db.Save(&updatedBook)
c.JSON(http.StatusOK, updatedBook)
}
func deleteBook(c *gin.Context) {
id := c.Param("id")
if err := db.Delete(&Book{}, "id = ?", id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "book not found"})
return
}
c.JSON(http.StatusNoContent, nil)
}