-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (67 loc) · 1.57 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
package main
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
)
type Book struct {
Title string
Description string
}
func dbInit() {
db, err := gorm.Open("sqlite3", "book.sqlite3")
if err != nil {
panic("You can't open db! (init)")
}
defer db.Close()
db.AutoMigrate(&Book{})
}
func dbInsert(title string, description string) {
db, err := gorm.Open("sqlite3", "book.sqlite3")
if err != nil {
panic("You can't open db! (insert)")
}
defer db.Close()
db.Create(&Book{Title: title, Description: description})
}
func dbGetAll() []Book {
db, err := gorm.Open("sqlite3", "book.sqlite3")
if err != nil {
panic("You can't open DB (dbGetAll())")
}
defer db.Close()
var books []Book
db.Find(&books)
return books
}
func dbDelete(id int) {
db, err := gorm.Open("sqlite3", "book.sqlite3")
if err != nil {
panic("You can't open DB (dbDelete)")
}
defer db.Close()
var book Book
db.First(&book,id)
db.Delete(&book)
}
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*.html")
dbInit()
router.GET("/", func(ctx *gin.Context) {
books := dbGetAll()
ctx.HTML(200, "index.html", gin.H{
// "data": data,
// "books": []Book{{"Sample book", "Lorem ipsum dolor..."}, {"Sample book2", "Lorem ipsum ..."}},
"books": books,
})
})
// 追加
router.POST("/new", func(c *gin.Context) {
title := c.PostForm("title")
description := c.PostForm("description")
dbInsert(title,description)
c.Redirect(302, "/")
})
router.Run()
}