dongmi19720408 2013-05-28 05:23
浏览 187
已采纳

在golang中,如何在一系列重定向后确定最终URL?

So, I'm using the net/http package. I'm GETting a URL that I know for certain is redirecting. It may even redirect a couple of times before landing on the final URL. Redirection is handled automatically behind the scenes.

Is there an easy way to figure out what the final URL was without a hackish workaround that involves setting the CheckRedirect field on a http.Client object?

I guess I should mention that I think I came up with a workaround, but it's kind of hackish, as it involves using a global variable and setting the CheckRedirect field on a custom http.Client.

There's got to be a cleaner way to do it. I'm hoping for something like this:

package main

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

func main() {
  // Try to GET some URL that redirects.  Could be 5 or 6 unseen redirections here.
  resp, err := http.Get("http://some-server.com/a/url/that/redirects.html")
  if err != nil {
    log.Fatalf("http.Get => %v", err.Error())
  }

  // Find out what URL we ended up at
  finalURL := magicFunctionThatTellsMeTheFinalURL(resp)

  fmt.Printf("The URL you ended up at is: %v", finalURL)
}
  • 写回答

1条回答 默认 最新

  • dtc4547 2013-05-28 06:35
    关注
    package main
    
    import (
        "fmt"
        "log"
        "net/http"
    )
    
    func main() {
        resp, err := http.Get("http://stackoverflow.com/q/16784419/727643")
        if err != nil {
            log.Fatalf("http.Get => %v", err.Error())
        }
    
        // Your magic function. The Request in the Response is the last URL the
        // client tried to access.
        finalURL := resp.Request.URL.String()
    
        fmt.Printf("The URL you ended up at is: %v
    ", finalURL)
    }
    

    Output:

    The URL you ended up at is: http://stackoverflow.com/questions/16784419/in-golang-how-to-determine-the-final-url-after-a-series-of-redirects
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题