forked from chunghha/docker-go-gin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
76 lines (58 loc) · 1.33 KB
/
app.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
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
// Product type
type Product struct {
ID uint `json:”id”`
Code string `json:”code”`
Price uint `json:”price”`
}
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"greet": "hello, world!",
})
})
r.GET("/echo/:echo", func(c *gin.Context) {
echo := c.Param("echo")
c.JSON(http.StatusOK, gin.H{
"echo": echo,
})
})
r.POST("/upload", func(c *gin.Context) {
form, _ := c.MultipartForm()
files := form.File["upload[]"]
for _, file := range files {
log.Println(file.Filename)
// Upload the file to specific dst.
// c.SaveUploadedFile(file, dst)
}
c.JSON(http.StatusOK, gin.H{
"uploaded": len(files),
})
})
r.GET("/products", GetProducts)
r.Run() // listen and serve on 0.0.0.0:8080
}
func GetProducts(c *gin.Context) {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
db.AutoMigrate(&Product{})
var products []Product
if err := db.Find(&products).Error; err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
log.Println(err)
} else {
c.JSON(http.StatusOK, products)
log.Println(products)
}
}