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 // 設(shè)置超時(shí)時(shí)間
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}"
)
// 壁紙類型,有編號(hào),長(zhǎng)寬和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)
}
//根據(jù)URL文件名創(chuàng)建文件
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() {
//檢查并創(chuàng)建臨時(shí)目錄
if ! isDirExist(DataRoot) {
os.Mkdir(DataRoot, 0755);
fmt.Println("dir %s created", DataRoot)
}
//生成一個(gè)數(shù)據(jù)序列,用來獲取分頁
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下的所有數(shù)據(jù)
data := js.Get("data").MustArray()
for _, v := range data {
v := v.(map[string]interface{})
for kk, vv := range v {
if(kk == "file_id") {
//這里 vv 是一個(gè)[]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.")
}