#Tutorial Write a handler to add a new item

10 messages · Page 1 of 1 (latest)

long vault
#

Add code to add albums data to the list of albums.

Somewhere after the import statements, paste the following code. (The end of the file is a good place for this code, but Go doesn’t enforce the order in which you declare functions.)

// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
    var newAlbum album

    // Call BindJSON to bind the received JSON to
    // newAlbum.
    if err := c.BindJSON(&newAlbum); err != nil {
        return
    }

    // Add the new album to the slice.
    albums = append(albums, newAlbum)
    c.IndentedJSON(http.StatusCreated, newAlbum)
}

In this code, you:

Use Context.BindJSON to bind the request body to newAlbum.
Append the album struct initialized from the JSON to the albums slice.
Add a 201 status code to the response, along with JSON representing the album you added.

#

Sorry I'm very new to web.

#

what does

if err := c.BindJSON(&newAlbum); err != nil {
        return
    }

mean?
The grammar seems to be so complicated. I mainly use Python before.

hollow parcel
#

c.BindJSON returns an error, and then you're checking if the error is not nil

#

The syntax is like if assignment; condition {}

#

The if only cares about the part after the ;

long vault
#

why c.BindJSON(&newAlbum) instead of c.BindJSON(newAlbum)?

hollow parcel
#

Oh, that's because it needs a pointer to actually change the data inside it

#

Stuff in go is passed by value, and using a pointer allows the function to update the original value

long vault