Skip to content

Commit 9ee6b93

Browse files
golang added value to array of object
1 parent 6733b03 commit 9ee6b93

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

gin-web-app/main.go

+24-5
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,34 @@ func getUser(c *gin.Context) {
2929
c.JSON(http.StatusOK, gin.H{"message": "Hello, " + name + "!"})
3030
}
3131

32+
var users = []userDetail{
33+
{ID: "1", Name: "Blue Train", Age: 56},
34+
{ID: "2", Name: "Akash", Age: 11},
35+
{ID: "3", Name: "pradip", Age: 56},
36+
}
37+
3238
func getUsers(c *gin.Context) {
33-
var users = []userDetail{
34-
{ID: "1", Name: "Blue Train", Age: 56},
35-
{ID: "2", Name: "Akash", Age: 11},
36-
{ID: "3", Name: "pradip", Age: 56},
37-
}
3839

3940
c.JSON(http.StatusOK, users)
4041
}
4142

43+
// postAlbums adds an album from JSON received in the request body.
44+
func addUser(c *gin.Context) {
45+
46+
var newUser userDetail
47+
48+
// Call BindJSON to bind the received JSON to
49+
// newAlbum.
50+
if err := c.BindJSON(&newUser); err != nil {
51+
return
52+
}
53+
54+
// Add the new album to the slice.
55+
users = append(users, newUser)
56+
c.IndentedJSON(http.StatusCreated, newUser)
57+
58+
}
59+
4260
func main() {
4361
router := gin.Default()
4462

@@ -55,6 +73,7 @@ func main() {
5573
// with param
5674
router.GET("/user/:name", getUser)
5775
router.GET("/user", getUsers)
76+
router.POST("/user", addUser)
5877

5978
router.Run(":3000")
6079
}

0 commit comments

Comments
 (0)