Skip to content

Instantly share code, notes, and snippets.

@lucasmarqs
Last active December 19, 2018 11:54
Show Gist options
  • Save lucasmarqs/13914043c6d4630cbc0cac044c5fac8a to your computer and use it in GitHub Desktop.
Save lucasmarqs/13914043c6d4630cbc0cac044c5fac8a to your computer and use it in GitHub Desktop.
API IMDB
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"sort"
"strconv"
"strings"
)
type Response struct {
Results []Search `json:"Search"`
}
type Search struct {
Title string `json:"Title"`
Year string `json:"Year"`
Type string `json:"Type"`
}
type ByYear []Search
func (y ByYear) Len() int { return len(y) }
func (y ByYear) Swap(i, j int) {
y[i], y[j] = y[j], y[i]
}
func (y ByYear) Less(i, j int) bool {
y1, _ := strconv.Atoi(y[i].Year)
y2, _ := strconv.Atoi(y[j].Year)
return y1 < y2
}
// func (a ByAge) Len() int { return len(a) }
// func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() {
if len(os.Args) < 2 {
fmt.Printf("Informe um nome de filme.")
return
}
// ./go3 harry potter stone
names := os.Args[1:]
// [harry, potter, stone]
name := strings.Join(names, "+")
// harry+potter+stone
searchMovie(name)
}
func searchMovie(name string) {
url := fmt.Sprintf("http://www.omdbapi.com/?apikey=key&s=%s", name)
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
r := Response{}
if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
panic(err)
}
sort.Sort(ByYear(r.Results))
for _, movie := range r.Results {
if movie.Type != "movie" {
continue
}
fmt.Printf("%s - %s\n", movie.Title, movie.Year)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment