Q
Q
qucer2015-08-14 15:50:34
go
qucer, 2015-08-14 15:50:34

How to get a list of all redirects in http.Client?

How can I get a nice list of all redirects? If, for example, when requesting page A, it redirects me to page B, and B, in turn, redirects to page C.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey K, 2015-08-14
@mututunus

package main

import (
  "fmt"
  "net/http"
)

func main() {
  client := &http.Client{
    Transport: &http.Transport{},
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
      if len(via) > 0 {
        fmt.Printf("%s -> %s\n", via[len(via)-1].URL.String(), req.URL.String())
      }
      return nil
    },
  }
  res, err := client.Get("...")
}

Q
qucer, 2015-08-17
@qucer

By “get a list of all redirects” I meant get a variable with a list that can then be used further.
Something like here (Java Apache HttpClient)

public List getAllRedirectLocations(String link) throws ClientProtocolException, IOException {
    List redirectLocations = null;
    CloseableHttpResponse response = null;

    try {
        HttpClientContext context = HttpClientContext.create();
        HttpGet httpGet = new HttpGet(link);
        response = httpClient.execute(httpGet, context);

        // get all redirection locations
        redirectLocations = context.getRedirectLocations();
    } finally {
        if(response != null) {
            response.close();
        }
    }

    return redirectLocations;
}

And you can just take it out like this
type LogRedirects struct {
    Transport http.RoundTripper
}

func (l LogRedirects) RoundTrip(req *http.Request) (resp *http.Response, err error) {
    t := l.Transport
    if t == nil {
        t = http.DefaultTransport
    }
    resp, err = t.RoundTrip(req)
    if err != nil {
        return
    }
    switch resp.StatusCode {
        case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:
            log.Println("Request for", req.URL, "redirected with status", resp.StatusCode)
    }
    return
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question