-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (95 loc) · 2.37 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
113
114
115
package main
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/joho/godotenv"
"os"
"log"
"strconv"
)
type Member struct {
gorm.Model
Name string
FavoriteFood string
}
var db *gorm.DB
func init() {
godotenv.Load(".devcontainer/.env")
POSTGRES_USER,POSTGRES_PASSWORD,POSTGRES_DB,POSTGRES_HOSTNAME := os.Getenv("POSTGRES_USER"),os.Getenv("POSTGRES_PASSWORD"),os.Getenv("POSTGRES_DB"),os.Getenv("POSTGRES_HOSTNAME_")
conn, err := gorm.Open("postgres", "host="+POSTGRES_HOSTNAME+" dbname="+POSTGRES_DB+" password="+POSTGRES_PASSWORD+" user="+POSTGRES_USER+" sslmode=disable")
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
db = conn
db.AutoMigrate(&Member{})
}
func insertHandler(c *gin.Context) {
name := c.PostForm("name")
favoriteFood := c.PostForm("favoriteFood")
member := Member{Name: name, FavoriteFood: favoriteFood}
if err := db.Create(&member).Error; err != nil {
log.Println(err)
c.String(500, "Internal Server Error")
return
}
c.Redirect(302, "/members")
}
func deleteHandler(c *gin.Context) {
idStr := c.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil {
log.Println(err)
c.String(400, "Invalid ID")
return
}
if err := db.Where("id = ?", id).Delete(&Member{}).Error; err != nil {
log.Println(err)
c.String(500, "Internal Server Error")
return
}
c.Redirect(302, "/members")
}
func membersHandler(c *gin.Context) {
var members []Member
if err := db.Find(&members).Error; err != nil {
log.Println(err)
c.String(500, "Internal Server Error")
return
}
viewModel := ListViewModel{
MemberList: members,
}
c.HTML(200, "members.html",viewModel)
}
type ListViewModel struct {
MemberList []Member ;
}
func memberHandler(c *gin.Context) {
idStr := c.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil {
log.Println(err)
c.String(400, "Invalid ID")
return
}
var member Member
if err := db.First(&member, id).Error; err != nil {
log.Println(err)
c.String(500, "Internal Server Error")
return
}
c.HTML(200, "member.html", gin.H{
"Member": member,
})
}
func main() {
r := gin.Default()
r.Static("/static","./static")
r.LoadHTMLGlob("templates/*")
r.GET("/members", membersHandler)
r.POST("/members", insertHandler)
r.POST("/delete/members/:id", deleteHandler)
r.GET("/members/:id", memberHandler)
r.Run(":8080")
}