Why does my golang httprequest always return Statuscode 200 while the same approach in c# doesn't?

66 Views Asked by At

I'm trying to convert some c# code to golang. In my code there is a simple http get request created that should not allow to be redirected (because later on I want to do something with the response). My c# code looks like that:

static async Task testrequest()
{    
        HttpClientHandler handler = new HttpClientHandler ();
        handler.AllowAutoRedirect = false; 

        CancellationToken ct = new CancellationToken();
        HttpClient httpClient = new HttpClient(handler);
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
        Uri uri = new("https://mytesturl.com/");
        
        HttpResponseMessage response = await httpClient.GetAsync(uri, ct).ConfigureAwait(false);
}

This correctly returns status code 307.

Now I'm trying to get the same response in golang (in which I'm a complete beginner). I learned that http client in go doesn't have a AllowAutoRedirect-property and I have to use "CheckRedirect" on the client. So this is what I set up in go:

func testrequestingo([]string, error) {

    client := http.Client{
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            fmt.Println("Redirected to:", req.URL)
            return nil
        }}

    req, err := http.NewRequest("GET", "https://mytesturl.com/", nil)
    if err != nil {
        panic(err)
    }

    req.Header.Set("Accept", "text/html")

    resp, err := client.Do(req)

    fmt.Println("StatusCode: ", resp.StatusCode)
    
}

However this always returns Statuscode 200 - so I guess I'm using CheckRedirect wrong and it's just following the redirect.

EDIT:

As also mentioned in the comments I tried to change the CheckRedirect to "http.ErrUseLastResponse", however I still get the wrong StatusCode, so the answer here doesn't fix the issue in my case

0

There are 0 best solutions below