最近小研究了一下GO语言,试着自己写了一个GET获取远程网页的例子。代码如下:
- func loginPre1() map[string]interface{} {
- client := &http.Client{}
- reqest, err := http.NewRequest("GET", "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=Z3V5dWV0ZnRiJTQwMTYzLmNvbQ%3D%3D&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.5)&_=", nil)
- if err != nil {
- fmt.Println("Fatal error ", err.Error())
- os.Exit(0)
- }
- reqest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
- reqest.Header.Add("Accept-Encoding", "gzip, deflate")
- reqest.Header.Add("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
- reqest.Header.Add("Connection", "keep-alive")
- reqest.Header.Add("Host", "login.sina.com.cn")
- reqest.Header.Add("Referer", "http://weibo.com/")
- reqest.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")
- response, err := client.Do(reqest)
- defer response.Body.Close()
- if err != nil {
- fmt.Println("Fatal error ", err.Error())
- os.Exit(0)
- }
- if response.StatusCode == 200 {
- var body string
- switch response.Header.Get("Content-Encoding") {
- case "gzip":
- reader, _ := gzip.NewReader(response.Body)
- for {
- buf := make([]byte, 1024)
- n, err := reader.Read(buf)
- if err != nil && err != io.EOF {
- panic(err)
- }
- if n == 0 {
- break
- }
- body += string(buf)
- }
- default:
- bodyByte, _ := ioutil.ReadAll(response.Body)
- body = string(bodyByte)
- }
- r := regexp.MustCompile(`sinaSSOController.preloginCallBack\((.*?)\)`)
- rs := r.FindStringSubmatch(body)
- //json decode
- header := make(map[string]interface{})
- err = json.Unmarshal([]byte(rs[1]), &header)
- if err != nil {
- fmt.Println("Fatal error ", err.Error())
- os.Exit(0)
- }
- t := fmt.Sprintf("%f", header["servertime"])
- header["servertime"] = strings.Trim(t, ".000000")
- return header
- }
- return nil
- }
有疑问加站长微信联系(非本文作者)