-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
77 lines (62 loc) · 1.07 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
73
74
75
76
77
package main
import (
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"strconv"
"sync"
)
// Post ...
type Post struct {
UserID int `json:"userId"`
ID int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
const (
POSTS_COUNT = 100
BASE_URL = "https://jsonplaceholder.typicode.com/posts/"
STORAGE_PATH = "./storage/posts/"
)
var (
wg sync.WaitGroup
)
func getPost(id int) {
defer wg.Done()
resp, err := http.Get(BASE_URL + strconv.Itoa(id))
if err != nil {
log.Println(err)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Println(err)
return
}
var post Post
err = json.Unmarshal(body, &post)
if err != nil {
log.Println(err)
return
}
data, err := json.MarshalIndent(post, "", " ")
if err != nil {
log.Println(err)
return
}
err = ioutil.WriteFile(STORAGE_PATH+strconv.Itoa(id)+".txt", data, 0644)
if err != nil {
log.Println(err)
return
}
}
func main() {
for postID := 1; postID <= POSTS_COUNT; postID++ {
wg.Add(1)
go getPost(postID)
}
wg.Wait()
}