DEV Community

Vishal Dhapola
Vishal Dhapola

Posted on

simple restapi in go with post request

package main

import (


type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`

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

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

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

func main() {
    // new_list := []string{}
    // fmt.Printf("%T\n", albums)
    // fmt.Printf("%T\n", new_list)
    router := gin.Default() //Default returns an Engine instance with the Logger and Recovery middleware already attached.
    router.GET("/albums", getAlbums)
    router.POST("/albums", postAlbums)

var albums = []album{
    {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
    {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
    {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},

func getAlbums(c *gin.Context) { //gin.Context is the most important part of Gin.
    //It carries request details, validates and serializes JSON, and more.
    //(Despite the similar name, this is different from Go’s built-in context package.)
    c.IndentedJSON(http.StatusOK, albums) //Call Context.IndentedJSON to serialize the struct into JSON and add it to the response.

Enter fullscreen mode Exit fullscreen mode

Top comments (0)