@qucer

Как получить список всех редиректов в http.Client?

Как можно красиво получить список всех редиректов? Если к примеру запрашивая страницу А, она редиректит меня на страницу Б, а Б в свою очередь редиректит на страницу С.
  • Вопрос задан
  • 298 просмотров
Пригласить эксперта
Ответы на вопрос 2
mututunus
@mututunus
Backend developer (Python, Golang)
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("...")
}
Ответ написан
@qucer Автор вопроса
Под “получить список всех редиректов” я имел ввиду получить переменную со списком которую можно потом использовть дальше.

Примерно как тут (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;
}


А просто вывести можно еще и так

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
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы