go language reads json and downloads hd girl pictures
- 2020-05-27 05:54:47
- OfStack
I have learned golang for one day. I wrote go while looking at the document and I read and analyzed json and downloaded the picture
json api is the love wallpaper HD mac 1920x1200 version, hd sister image
Conclusion: go + json = shit
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
//"encoding/json"
"strings"
"github.com/bitly/go-simplejson"
)
const (
DataRoot = "./tmp/" // The root directory where the cover image is stored
TimeoutLimit = 10 // Set timeout time
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}"
)
// Wallpaper type, numbered, long, wide and URL
type Wallpaper struct {
Pid int
Url string
Width int
Height int
}
// Download and save the image locally
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
}
// Save the image in the resolution directory
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)
}
// According to the URL File name creation file
filename := filepath.Base(paper.Url)
dst, err := os.Create(Dirname + filename)
if err != nil {
fmt.Println("%d HTTP ERROR:%s", paper.Pid, err)
return
}
// Written to the file
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() {
// Check and create a temporary directory
if ! isDirExist(DataRoot) {
os.Mkdir(DataRoot, 0755);
fmt.Println("dir %s created", DataRoot)
}
// generate 1 Data sequence, used to get pagination
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)
// traverse data All the data below
data := js.Get("data").MustArray()
for _, v := range data {
v := v.(map[string]interface{})
for kk, vv := range v {
if(kk == "file_id") {
// Here, vv is 1 a []interface{} json.Number I don't know how to get the value out, but I'm using a silly one, right 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.")
}
That's all for this article, I hope you enjoy it.