This repository has been archived by the owner on Aug 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcim.go
95 lines (78 loc) · 1.78 KB
/
cim.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
package main
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
)
func GetMD5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
func ExtractURI(stuct map[string]interface{}) string {
ims, ok := stuct["images"].([]interface{})
if !ok || len(ims) == 0 {
return ""
}
im, ok := ims[0].(map[string]interface{})
if !ok {
return ""
}
return im["url"].(string)
}
func main() {
if len(os.Args) <= 1 {
return
}
endPoint := "http://www.bing.com"
url := fmt.Sprintf("%s/HPImageArchive.aspx?format=js&idx=%s&n=1&mkt=en-US", endPoint, os.Args[1])
imagePath := os.Getenv("image_base_path")
if imagePath == "" {
_, _ = io.WriteString(os.Stderr, "please config local image path\n")
return
}
_, err := os.Stat(imagePath)
if err == os.ErrNotExist {
_ = os.MkdirAll(imagePath, 0755)
}
resp, err := http.Get(url)
if err != nil {
_, _ = io.WriteString(os.Stderr, err.Error()+"\n")
return
}
dat, err := ioutil.ReadAll(resp.Body)
if err != nil {
_, _ = io.WriteString(os.Stderr, err.Error()+"\n")
return
}
var stuct map[string]interface{}
err = json.Unmarshal(dat, &stuct)
if err != nil {
_, _ = io.WriteString(os.Stderr, err.Error()+"\n")
return
}
uri := ExtractURI(stuct)
if uri == "" {
_, _ = io.WriteString(os.Stderr, "get image url failed\n")
return
}
imageUrl := fmt.Sprintf("%s%s", endPoint, uri)
filepath := path.Join(imagePath, GetMD5Hash(imageUrl)+".jpg")
resp, err = http.Get(imageUrl)
if err != nil {
_, _ = io.WriteString(os.Stderr, err.Error()+"\n")
return
}
dat, err = ioutil.ReadAll(resp.Body)
if err != nil {
_, _ = io.WriteString(os.Stderr, err.Error()+"\n")
return
}
_ = os.WriteFile(filepath, dat, 0744)
fmt.Print(filepath)
}