-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
72 lines (65 loc) · 1.43 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/henryckl/pokerequest/database"
)
func makeRange(min, max int) []int {
a := make([]int, max-min+1)
for i := range a {
a[i] = min + i
}
return a
}
type Pokemon struct {
Name string `json:"name"`
Height uint `json:"height"`
Weight uint `json:"weight"`
ID uint `json:"id"`
}
func getPokemon(url string) (pokemon *Pokemon, err error) {
response, err := http.Get(url)
if err != nil {
return nil, err
}
err = json.NewDecoder(response.Body).Decode(&pokemon)
if err != nil {
return nil, err
}
return pokemon, nil
}
func insertPokemon(pokemons []Pokemon) {
db := database.Init()
for _, pokemon := range pokemons {
db.Exec("inserirPokemon", pokemon.Name, pokemon.Height, pokemon.Weight, pokemon.ID)
}
}
func main() {
start := time.Now()
defer func() {
fmt.Println("Execution Time: ", time.Since(start))
}()
var urls []string
var pokemons []Pokemon
for _, value := range makeRange(1, 1000) {
urls = append(urls, fmt.Sprintf("https://pokeapi.co/api/v2/pokemon/%d", value))
}
ch := make(chan Pokemon)
for _, url := range urls {
go func(url string) {
poke, err := getPokemon(url)
if err != nil {
return
}
ch <- *poke
}(url)
}
for i := 0; i < len(makeRange(1, 1000)); i++ {
pokemon := <-ch
pokemons = append(pokemons, pokemon)
}
go insertPokemon(pokemons)
fmt.Printf("Total carregado: %d \n", len(pokemons))
}