How to get json data with golang | gin gonic


 

Welcome today im gonna show you how to get data with golang

   

first we need to go.mod file and install gin framework



$ go mod init "YourProjectFolder"
$ go get github.com/gin-gonic/gin


then create main.go and create main function


package main

func main() {


}



so right now we have to crate struct and array 


type words struct {
   ID  string `json:"id"`
   ENG string `json:"eng"`
    TR  string `json:"tr"`
}


var dictionary = []words{
    {ID: "1", ENG: "hello",   TR: "merhaba"},
    {ID: "2", ENG: "cat",     TR: "kedi"},
    {ID: "3", ENG: "car",     TR: "araba"},
    {ID: "4", ENG: "door",    TR: "kapı"},
}


we have array and we need to convert this array to json


func fakeData(c *gin.Context) {

    c.JSON(http.StatusOK, dictionary)

}


Okay now we have json data so lets get this data


package main

import (
    "net/http"

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

func main() {

    router := gin.Default()

    router.GET("/fakeData", fakeData) // http://localhost:9090/fakeData

    router.Run(":9090") // localhost:9090
}


and run in terminal 



$ go run "YourProjectFile"





you can also see in my github account 


Github Code



Comments

Popular Posts