DEV Community

Vishal Dhapola
Vishal Dhapola

Posted on

My first simple rest api using golang

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

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

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.Run("localhost:8000")
}

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

Oldest comments (0)