zoukankan      html  css  js  c++  java
  • go语言*第4章JSON部分习题

    github地址
    笔记

    只做了 4.10 和 4.13

    4.10

    练习 4.10:** 修改issues程序,根据问题的时间进行分类,比如不到一个月的、不到一年的、超过一年。
    代码有点多,见 github
    主要是学会用 time 包,在Issue结构体中的成员变量 CreatAt 本身就是time类的,所以可以很方便比较。
    我本来打算用github api去查询特定时间之后的issue发现好像并不支持。

    4.13

    在爬取接口的时候记得加上你的 apiKey 否则返回401

    package ex4_13
    
    import (
    	"encoding/json"
    	"fmt"
    	"io/ioutil"
    	"net/http"
    	"net/url"
    	"os"
    	"strings"
    	"sync"
    )
    
    const apikey = "837a1b8b"
    const apiUrl = "http://www.omdbapi.com/"
    
    type moveInfo struct {
    	Title  string
    	Year   string
    	Poster string
    }
    
    //福尔摩斯
    // OMDb API: http://www.omdbapi.com/?t=Holmes&apikey=837a1b8b
    func getPoster(title string) {
    	resp, err := http.Get(fmt.Sprintf("%s?t=%s&apikey=%s", apiUrl, url.QueryEscape(title), apikey))
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	defer resp.Body.Close()
    
    	binfo, err := ioutil.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	minfo := moveInfo{}
    	err = json.Unmarshal(binfo, &minfo)
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	poster := minfo.Poster
    	if poster != "" {
    		downloadPoster(poster)
    	}
    }
    func downloadPoster(url string) {
    	resp, err := http.Get(url)
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	defer resp.Body.Close()
    
    	bcontent, err := ioutil.ReadAll(resp.Body)
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	pos := strings.LastIndex(url, "/")
    	if pos == -1 {
    		fmt.Println("failed to parse the title of the poster")
    		return
    	}
    	f, err := os.Create(url[pos+1:])
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	defer f.Close()
    
    	_, err = f.Write(bcontent)
    	if err != nil {
    		fmt.Println(err)
    	}
    }
    func searchByTitle(titles ...string) {
    	var wg sync.WaitGroup
    	for _, title := range titles {
    		wg.Add(1)
    		go func() {
    			getPoster(title)
    			wg.Done()
    		}()
    	}
    	wg.Wait()
    }
    
    

    测试文件

    package ex4_13
    
    import (
    	"testing"
    )
    
    func TestSearchByTitle(t *testing.T)  {
    	searchByTitle("Sherlock Holmes")
    }
    
    
  • 相关阅读:
    共望明月
    游丽都公园有感
    创业天才尼尔曼迈向成功的十四个原则
    赵娜(帮别人名字作诗)
    小幽默也有大道理:哲理幽默15则
    夜游草堂
    成功就是简单的事情重复做、重复做
    千万别入错行 15条人生建议
    听一堂课值三十九万,把它看完,定会有收获!
    VIEW:X$KCCRSControlfile Record Section directory (8.0 8.1)
  • 原文地址:https://www.cnblogs.com/Jun10ng/p/12782004.html
Copyright © 2011-2022 走看看