Created
November 26, 2020 14:42
-
-
Save c0ze/9e615682065ee97c4477b5877d02f212 to your computer and use it in GitHub Desktop.
ghibli.go
This file contains hidden or 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" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"strings" | |
) | |
type film struct { | |
Title string `json: "title"` | |
Species []string `json: "species"` | |
} | |
type species struct { | |
Name string `json: "name"` | |
EyeColors string `json: "eye_colors"` | |
} | |
// Using the ghibliapi, write a go program to get a list of titles of | |
// movies where a species with emerald eyes appears | |
// You can find the documentation at https://ghibliapi.herokuapp.com/ | |
func main() { | |
url := "https://ghibliapi.herokuapp.com/films" | |
req, err := http.NewRequest(http.MethodGet, url, nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
client := http.Client{} | |
res, getErr := client.Do(req) | |
if getErr != nil { | |
log.Fatal(getErr) | |
} | |
if res.Body != nil { | |
defer res.Body.Close() | |
} | |
body, readErr := ioutil.ReadAll(res.Body) | |
if readErr != nil { | |
log.Fatal(readErr) | |
} | |
var films []film | |
jsonErr := json.Unmarshal(body, &films) | |
if jsonErr != nil { | |
log.Fatal(jsonErr) | |
} | |
fmt.Println(films) | |
url = "https://ghibliapi.herokuapp.com/species" | |
var titles []string | |
for _, film := range films { | |
fmt.Println("checking movie ", film.Title, len(film.Species)) | |
for _, spec := range film.Species { | |
//specUrl := fmt.Sprintf("%s/%s", url, spec) | |
fmt.Println("Checking ", spec) | |
req, err = http.NewRequest(http.MethodGet, spec, nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
res, getErr = client.Do(req) | |
if getErr != nil { | |
log.Fatal(getErr) | |
} | |
if res.Body != nil { | |
defer res.Body.Close() | |
} | |
body, readErr = ioutil.ReadAll(res.Body) | |
if readErr != nil { | |
log.Fatal(readErr) | |
} | |
var speciesObj species | |
jsonErr := json.Unmarshal(body, &speciesObj) | |
if jsonErr != nil { | |
log.Fatal(jsonErr) | |
} | |
fmt.Println("got response ", speciesObj.EyeColors) | |
// fmt.Println(speciesObj) | |
if strings.Contains(speciesObj.EyeColors, "Emerald") { | |
fmt.Printf("%s has red eye colour !", speciesObj.Name) | |
titles = append(titles, film.Title) | |
} | |
} | |
} | |
fmt.Println(titles) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment