-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfaces.go
99 lines (86 loc) · 1.54 KB
/
faces.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//before running create "images" dirrectory
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
)
var (
URL = "http://uifaces.com/api/v1/random"
DIR = "images"
DEBUG = false
WORKERS = 2
mx sync.Mutex
)
func main() {
DEBUG = true
for i := 0; i < WORKERS; i++ {
go work()
}
for {
}
}
func work() {
user := Random()
mx.Lock()
if !checkFile(user) {
save(user)
}
mx.Unlock()
}
func get(url string) []byte {
r, err := http.Get(url)
if err != nil {
return []byte{}
}
defer r.Body.Close()
b, _ := ioutil.ReadAll(r.Body)
return b
}
func checkFile(u Response) bool {
if _, err := os.Stat(u.ImagePath()); os.IsNotExist(err) {
DBG("File %s not exist", u.ImagePath())
return false
}
return true
}
func save(u Response) {
DBG("Start get image")
im := get(u.ImageUrls.Epic)
DBG("End get image")
if len(im) != 0 {
err := ioutil.WriteFile(u.ImagePath(), im, 0777)
if err != nil {
panic(err)
}
}
}
func Random() Response {
DBG("Start fetch random user")
bts := get(URL)
DBG("End fetch random user")
var res Response
json.Unmarshal(bts, &res)
return res
}
type Response struct {
Username string `json:"username"`
ImageUrls ImageUrls `json:"image_urls"`
}
func (r Response) ImagePath() string {
return DIR + "/" + r.Username + ".jpg"
}
type ImageUrls struct {
Epic string `json:"epic"`
Bigger string `json:"bigger"`
Normal string `json:"normal"`
Mini string `json:"mini"`
}
func DBG(format string, args ...interface{}) {
if DEBUG {
log.Printf(format, args...)
}
}