Created
July 1, 2022 10:56
-
-
Save msterhuj/e63dfe3b448cc1a0245d51e350211a48 to your computer and use it in GitHub Desktop.
simple go api call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
) | |
type Brand struct { | |
Id int `json:"brand_id"` | |
Name string `json:"brand_name"` | |
Url string `json:"detail"` | |
} | |
type ApiResponseBrands struct { | |
Status bool `json:"status"` | |
Data []Brand `json:"data"` | |
} | |
type Phone struct { | |
Brand string `json:"brand"` | |
PhoneName string `json:"phone_name"` | |
Url string `json:"detail"` | |
} | |
type BrandDetail struct { | |
Title string `json:"title"` | |
CurrentPage int `json:"current_page"` | |
LastPage int `json:"last_page"` | |
Phones []Phone `json:"phones"` | |
} | |
type ApiResponsePhones struct { | |
Status bool `json:"status"` | |
BrandDetail BrandDetail `json:"data"` | |
} | |
// logic | |
func getJsonResp(url string) *http.Response { | |
resp, err := http.Get(url) | |
if err != nil { | |
fmt.Println("Error getting json:", err) | |
return nil | |
} | |
return resp | |
} | |
func closeResp(resp *http.Response) { | |
err := resp.Body.Close() | |
if err != nil { | |
fmt.Println("Error closing response body:", err) | |
return | |
} | |
} | |
func main() { | |
resp := getJsonResp("https://api-mobilespecs.azharimm.site/v2/brands") | |
var apiResponseBrands ApiResponseBrands | |
err := json.NewDecoder(resp.Body).Decode(&apiResponseBrands) | |
if err != nil { | |
fmt.Println("Error parsing json:", err) | |
return | |
} | |
closeResp(resp) | |
for _, brand := range apiResponseBrands.Data { | |
fmt.Println(brand.Name) | |
resp = getJsonResp(brand.Url) | |
var apiResponsePhones ApiResponsePhones | |
err = json.NewDecoder(resp.Body).Decode(&apiResponsePhones) | |
if err != nil { | |
fmt.Println("Error parsing json:", err) | |
return | |
} | |
closeResp(resp) | |
for _, phone := range apiResponsePhones.BrandDetail.Phones { | |
fmt.Println("\t", phone.PhoneName) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment