2016-01-29 25 views
5

我正在向服務器發送請求,但它正在返回一個網頁。有沒有辦法獲得網頁的網址?如何獲取重定向url而不是golang中的頁面內容?

package main 

import (
    "fmt" 
    "io/ioutil" 
    "net/http" 
) 

func main() { 
    req, err := http.NewRequest("GET", "https://www.google.com", nil) 
    if err != nil { 
     panic(err) 
    } 

    client := new(http.Client) 
    response, err := client.Do(req) 
    if err != nil { 
     panic(err) 
    } 
    fmt.Println(ioutil.ReadAll(response.Body)) 
} 
+0

可能重複:http://stackoverflow.com/questions/24518945/ http://stackoverflow.com/questions/29865691/,http://stackoverflow.com/questions/27814942/ – JimB

回答

12

您需要檢查重定向並停止(捕獲)它們。如果您捕獲重定向,則可以使用響應結構的位置方法獲取重定向URL(重定向發生在該URL)。

package main 

import (
    "errors" 
    "fmt" 
    "net/http" 
) 

func main() { 
    req, err := http.NewRequest("GET", "https://www.google.com", nil) 
    if err != nil { 
     panic(err) 
    } 
    client := new(http.Client) 
    client.CheckRedirect = func(req *http.Request, via []*http.Request) error { 
     return errors.New("Redirect") 
    } 

    response, err := client.Do(req) 
    if err != nil { 
     if response.StatusCode == http.StatusFound { //status code 302 
      fmt.Println(response.Location()) 
     } else { 
      panic(err) 
     } 
    } 

} 
相關問題