Query URL without redirect in Go

后端 未结 2 1298
轻奢々
轻奢々 2020-12-17 20:23

I am writing a benchmark test for a redirect script.

I wisg my program to query certain URL that redirects to AppStore. But I do not wish to download AppStore page.

相关标签:
2条回答
  • 2020-12-17 20:53

    You need to use an http.Transport instead of an http.Client. Transport is lower-level and does not follow redirects.

    req, err := http.NewRequest("GET", "http://example.com/redirectToAppStore", nil)
    // ...
    resp, err := http.DefaultTransport.RoundTrip(req)
    
    0 讨论(0)
  • 2020-12-17 20:56

    For completeness' sake, you can use an http.Client and not follow redirects. http.Client has a CheckRedirect field which is a function. It is called before following any redirection.

    If this function returns an error, then httpClient.Do(...) will not follow the redirect (see doFollowingRedirects() function in Go's source code) and instead will return an error (its concrete type will be url.Error, and its URL field will be the redirect-to URL, aka the Location header value, see this code).

    You can see my gocrawl library for a concrete example of this use.

    0 讨论(0)
提交回复
热议问题