/
hotels_gins.go
121 lines (103 loc) · 2.51 KB
/
hotels_gins.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
116
117
118
119
120
121
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
v1 := router.Group("/v1/hotels")
{
v1.POST("/", createHotel)
v1.GET("/", getAllHotels)
v1.GET("/:id", getHotel)
v1.PUT("/:id", updateHotel)
v1.DELETE("/:id", deleteHotel)
}
router.Run()
}
type Hotel struct {
Id string `json:"id" binding:"required"`
DisplayName string `json:"display_name" `
StarRating int `json:"star_rating" `
NoRooms int `json:"no_rooms" `
Links []Link `json:"links"`
}
type Link struct {
Href string `json:"href"`
Rel string `json:"rel"`
Type string `json:"type"`
}
var (
repository map[string]*Hotel
)
func init() {
repository = make(map[string]*Hotel)
}
func (h *Hotel) generateHateosLinks(url string) {
// Book url
postLink := Link{
Href: url + "book",
Rel: "book",
Type: "POST",
}
h.Links = append(h.Links, postLink)
}
func createHotel(c *gin.Context) {
var hotel Hotel
if err := c.ShouldBindJSON(&hotel); err == nil {
// add HATEOS links
hotel.generateHateosLinks(c.Request.URL.String())
// add hotel to repository
repository[hotel.Id] = &hotel
//return OK
c.JSON(http.StatusAccepted, gin.H{"status": "created"})
} else {
// some params not correct
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
func getHotel(c *gin.Context) {
// get ID from path param
hotelId := c.Param("id")
// get hotel object from repository
hotel, found := repository[hotelId]
fmt.Println(hotel, found, hotelId)
if !found {
c.JSON(http.StatusNotFound, gin.H{"status": "hotel with id not found"})
} else {
c.JSON(http.StatusOK, gin.H{"result": hotel})
}
}
func updateHotel(c *gin.Context) {
// get hotel object from repository
hotelId := c.Param("id")
hotel, found := repository[hotelId]
if !found {
c.JSON(http.StatusNotFound, gin.H{"status": "hotel with id not found"})
} else {
//update
if err := c.ShouldBindJSON(&hotel); err == nil {
repository[hotel.Id] = hotel
//return OK
c.JSON(http.StatusOK, gin.H{"status": "ok"})
} else {
// some params not correct
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
}
func getAllHotels(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"result": repository})
}
func deleteHotel(c *gin.Context) {
hotelId := c.Param("id")
_, found := repository[hotelId]
if !found {
c.JSON(http.StatusNotFound, gin.H{"status": "hotel with id not found"})
} else {
delete(repository, hotelId)
//return OK
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
}