Home > Backend Development > Golang > How Can I Query URLs in Go Without Following Redirects?

How Can I Query URLs in Go Without Following Redirects?

Linda Hamilton
Release: 2024-12-06 02:16:13
Original
155 people have browsed it

How Can I Query URLs in Go Without Following Redirects?

Querying URLs Without Redirects in Go

In this article, we address the issue of querying a URL without triggering automatic redirects in Go. This is often necessary for benchmarking purposes or when you only need to log the redirect URL or errors.

Solution 1: Using http.DefaultTransport.RoundTrip

Create an http.Request object as usual. Instead of passing it to an http.Client, use http.DefaultTransport.RoundTrip() to make the request. This bypasses the http.Client's built-in redirect handling.

import "net/http"

func QueryURLWithoutRedirect(url string) (*http.Response, error) {
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return nil, err
    }
    return http.DefaultTransport.RoundTrip(req)
}
Copy after login

Solution 2: Disable Redirects with CheckRedirect

Create an http.Client with the CheckRedirect field set to nil. This configures the client to not follow redirects.

import "net/http"

func QueryURLWithoutRedirect(url string) (*http.Response, error) {
    client := &http.Client{
        CheckRedirect: nil,
    }
    return client.Get(url)
}
Copy after login

Further Considerations

While both solutions provide the desired functionality, the first approach may experience performance issues under high load, as it may reuse connections that are closed prematurely.

To ensure that each query opens a new connection with the second approach, you can create a new http.Client for each request in a loop. However, this may not be necessary, as Go automatically closes idle connections after a certain period.

Ultimately, the choice of approach depends on your specific performance requirements and the behavior you desire in a real-world scenario.

The above is the detailed content of How Can I Query URLs in Go Without Following Redirects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template