-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
63 lines (53 loc) · 1.15 KB
/
utils.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
package main
import (
"encoding/json"
"net/http"
)
func fetchPosts() ([]Post, error) {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
return nil, err
}
defer resp.Body.Close()
var posts []Post
if err := json.NewDecoder(resp.Body).Decode(&posts); err != nil {
return nil, err
}
return posts, nil
}
func fetchPhotos() (map[int]string, error) {
resp, err := http.Get("https://jsonplaceholder.typicode.com/photos")
if err != nil {
return nil, err
}
defer resp.Body.Close()
var photos []struct {
ID int `json:"id"`
URL string `json:"url"`
AlbumID int `json:"albumId"`
}
if err := json.NewDecoder(resp.Body).Decode(&photos); err != nil {
return nil, err
}
photoMap := make(map[int]string)
for _, photo := range photos {
photoMap[photo.ID] = photo.URL
}
return photoMap, nil
}
func fetchPostsWithPhotos() ([]Post, error) {
posts, err := fetchPosts()
if err != nil {
return nil, err
}
photos, err := fetchPhotos()
if err != nil {
return nil, err
}
for i := range posts {
if photoURL, ok := photos[posts[i].ID]; ok {
posts[i].Photo = photoURL
}
}
return posts, nil
}