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=categoryspdy=1tid=3order=hotcolor_id=3device=105uuid=436e4ddc389027ba3aef863a27f6e6f9mode=0retina=0client_id=1008device_id=31547324model_id=105size_id=0channel_id=70001screen_width=1920screen_height=1200bizhi_width=1920bizhi_height=1200version_code=19language=zh-Hansjailbreak=0mac=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.")
}