Parse REST API json response in golang
Coming from predominantly Python and PHP world I have worked on building and consuming APIs. So when I was tasked with consuming an API in Go language, I had to do it a bit differently compared to Python world.
import requests
from pprint import pprint
headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
response = requests.get('https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode=560060&date=10-05-2021', headers=headers)
print(response.json())
and the similar thing in golang would be something where we have to do the below 1) Unmarshal the JSON 2) Copy to a strut
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type github struct {
Name string `json:"name"`
ShortName string `json:"short_name"`
Icons []struct {
Sizes string `json:"sizes"`
Src string `json:"src"`
Type string `json:"type,omitempty"`
} `json:"icons"`
PreferRelatedApplications bool `json:"prefer_related_applications"`
RelatedApplications []struct {
Platform string `json:"platform"`
URL string `json:"url"`
ID string `json:"id"`
} `json:"related_applications"`
}
func main() {
r, e := http.Get("https://github.com/manifest.json")
if e != nil {
panic(e)
}
gobj := github{}
json.NewDecoder(r.Body).Decode(&gobj)
fmt.Println(gobj.Icons[0].Sizes)
}