2016-01-29 8 views
5

मैं सर्वर से अनुरोध भेज रहा हूं लेकिन यह एक वेब पेज लौटा रहा है। क्या इसके बजाय वेब पेज का यूआरएल प्राप्त करने का कोई तरीका है?गोलांग में पृष्ठ सामग्री के बजाय रीडायरेक्ट यूआरएल कैसे प्राप्त करें?

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 (जिस पर पुनर्निर्देशन हो रहा था) प्राप्त कर सकते हैं।

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) 
     } 
    } 

} 
संबंधित मुद्दे