学了一天golang,一边看文档一边写的go读取分析json并下载图片
json api为爱壁纸HD mac 1920x1200版本,高清妹子图
总结:go+json=shit
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
|
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
//"encoding/json"
"strings"
"github.com/bitly/go-simplejson"
)
const (
DataRoot = "./tmp/" // 存放封面图的根目录
TimeoutLimit = 10 // 设置超时时间
PageUrl = "http://api.lovebizhi.com/macos_v4.php?a=category&spdy=1&tid=3&order=hot&color_id=3&device=105&uuid=436e4ddc389027ba3aef863a27f6e6f9&mode=0&retina=0&client_id=1008&device_id=31547324&model_id=105&size_id=0&channel_id=70001&screen_width=1920&screen_height=1200&bizhi_width=1920&bizhi_height=1200&version_code=19&language=zh-Hans&jailbreak=0&mac=&p={pid}"
)
// 壁纸类型,有编号,长宽和URL
type Wallpaper struct {
Pid int
Url string
Width int
Height int
}
// 将图片下载并保存到本地
func SaveImage(paper *Wallpaper) {
res, err := http.Get(paper.Url)
defer res.Body.Close()
if err != nil {
fmt.Printf( "%d HTTP ERROR:%s" , paper.Pid, err)
return
}
//按分辨率目录保存图片
Dirname := DataRoot + strconv.Itoa(paper.Width) + "x" + strconv.Itoa(paper.Height) + "/"
if ! isDirExist(Dirname) {
os.Mkdir(Dirname, 0755 );
fmt.Printf( "dir %s created\n" , Dirname)
}
//根据URL文件名创建文件
filename := filepath.Base(paper.Url)
dst, err := os.Create(Dirname + filename)
if err != nil {
fmt.Println( "%d HTTP ERROR:%s" , paper.Pid, err)
return
}
// 写入文件
io.Copy(dst, res.Body)
}
func isDirExist(path string) bool {
p, err := os.Stat(path)
if err != nil {
return os.IsExist(err)
} else {
return p.IsDir()
}
}
func main() {
//检查并创建临时目录
if ! isDirExist(DataRoot) {
os.Mkdir(DataRoot, 0755 );
fmt.Println( "dir %s created" , DataRoot)
}
//生成一个数据序列,用来获取分页
pow := make([] int , 2 )
for i := range pow {
if (i > 0 ) {
url := strings.Replace(PageUrl, "{pid}" , strconv.Itoa(i), - 1 );
fmt.Println(i, url);
response, err := http.Get(url)
if ( err != nil) {
fmt.Println(err)
continue
}
body, _ := ioutil.ReadAll(response.Body)
js, err := simplejson.NewJson(body)
//遍历data下的所有数据
data := js.Get( "data" ).MustArray()
for _, v := range data {
v := v.(map[string] interface {})
for kk, vv := range v {
if (kk == "file_id" ) {
//这里 vv 是一个[]interface{} json.Number,不知道怎么取出值,这里用了比较傻的Sprintf
vv := fmt.Sprintf( "%s" , vv)
imgid,_ := strconv.Atoi(vv)
url := fmt.Sprintf( "http://s.qdcdn.com/c/%d,1920,1200.jpg" , imgid)
fmt.Println(kk, imgid, url);
paper := &Wallpaper{imgid, url, 1920 , 1200 }
SaveImage(paper);
}
}
}
}
}
fmt.Println( "oh yes, all job done." )
}
|
以上就是本文的全部内容了,希望大家能够喜欢。