/
routes.go
67 lines (54 loc) · 1.28 KB
/
routes.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
package routes
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/jgreat/things/models"
"github.com/go-pg/pg/v10"
)
// GetWelcome - default get route
func GetWelcome(c *gin.Context) {
c.JSON(200, gin.H{
"hello": "world",
})
return
}
// GetThings - Get all the things
func GetThings(c *gin.Context) {
db := c.MustGet("db").(*pg.DB)
things := &[]models.Thing{}
err := db.Model(things).Select()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": things})
return
}
/*
curl --header "Content-Type: application/json" \
--request POST --data '{"name":"plumbus"}' \
http://localhost:8080/thing
*/
// CreateThing - add a thing to the db
func CreateThing(c *gin.Context) {
db := c.MustGet("db").(*pg.DB)
thing := &models.Thing{}
// Validate input
err := c.ShouldBindJSON(thing)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Create Thing
thing = &models.Thing{
Name: thing.Name,
}
// probably needs a lot more to check for unique and other constraints...
_, err = db.Model(thing).Insert()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": thing})
return
}