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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写