如何获取重定向url而不是golang中的页面内容? [英] how to get the redirect url instead of page content in golang?

查看:1011
本文介绍了如何获取重定向url而不是golang中的页面内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向服务器发送请求,但它正在返回一个网页。有没有办法获得网页的网址?

I am sending a request to server but it is returning a web page. Is there a way to get the url of the web page instead?

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


推荐答案

您需要检查重定向并停止(捕获)它们。如果您捕获重定向,那么您可以使用响应结构的位置方法来获取重定向URL(发生重定向)。

You need to check for redirect and stop(capture) them. If you capture a redirection then you can get the redirect URL (to which redirection was happening) using location method of response struct.

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

}

这篇关于如何获取重定向url而不是golang中的页面内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆