Created
January 28, 2020 01:23
-
-
Save topherPedersen/7262048192310fd9c3caa06874c55c92 to your computer and use it in GitHub Desktop.
Example Demonstrating How to Fetch & Parse JSON Data from an API in Golang (using RapidAPI)
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 ( | |
"fmt" | |
"net/http" | |
"io/ioutil" | |
"encoding/json" | |
) | |
// Convert JSON to Go Struct | |
// https://mholt.github.io/json-to-go/ | |
type SoccerMatch struct { | |
Title string `json:"title"` | |
Embed string `json:"embed"` | |
URL string `json:"url"` | |
Thumbnail string `json:"thumbnail"` | |
Date string `json:"date"` | |
Side1 struct { | |
Name string `json:"name"` | |
URL string `json:"url"` | |
} `json:"side1"` | |
Side2 struct { | |
Name string `json:"name"` | |
URL string `json:"url"` | |
} `json:"side2"` | |
Competition struct { | |
Name string `json:"name"` | |
ID int `json:"id"` | |
URL string `json:"url"` | |
} `json:"competition"` | |
Videos []struct { | |
Title string `json:"title"` | |
Embed string `json:"embed"` | |
} `json:"videos"` | |
} | |
func main() { | |
url := "https://free-football-soccer-videos1.p.rapidapi.com/v1/" | |
req, _ := http.NewRequest("GET", url, nil) | |
req.Header.Add("x-rapidapi-host", "free-football-soccer-videos1.p.rapidapi.com") | |
req.Header.Add("x-rapidapi-key", "YouR-SuPeR-SWeeT-aPi-KeY-GoeS-HeRe") | |
res, _ := http.DefaultClient.Do(req) | |
defer res.Body.Close() | |
body, _ := ioutil.ReadAll(res.Body) | |
bodyStr := string(body) | |
var matches []SoccerMatch | |
json.Unmarshal([]byte(bodyStr), &matches) | |
for i := 0; i < len(matches); i++ { | |
fmt.Println(matches[i].Title) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment