Home  >  Article  >  Backend Development  >  How can Go's CookieJar be used to follow redirects while preserving cookies?

How can Go's CookieJar be used to follow redirects while preserving cookies?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-05 18:35:02848browse

How can Go's CookieJar be used to follow redirects while preserving cookies?

Leveraging Go's cookiejar to Follow Redirections with Cookies

When an HTTP request results in a 302 redirect, it's crucial to maintain cookies received from the server for the subsequent request. In Go, this can be achieved through the cookiejar package, providing a convenient way to automatically follow redirections while preserving cookies.

In this scenario, the goal is to emulate the behavior of CURL with the following settings:

  • COOKIEFILE = "": Disable writing cookies to disk.
  • AUTOREFERER = 1: Automatically set the Referer header.
  • FOLLOWLOCATION = 1: Follow redirects.

Implementation with cookiejar

With Go 1.1, the net/http/cookiejar package is available to handle these tasks seamlessly. Here's a code sample demonstrating its usage:

<code class="go">package main

import (
    "golang.org/x/net/publicsuffix"
    "io/ioutil"
    "log"
    "net/http"
    "net/http/cookiejar"
)

func main() {
    // Configure the cookie jar.
    options := cookiejar.Options{
        PublicSuffixList: publicsuffix.List,
    }
    jar, err := cookiejar.New(&options)
    if err != nil {
        log.Fatal(err)
    }

    // Create an HTTP client with the cookie jar.
    client := http.Client{Jar: jar}

    // Make the request.
    resp, err := client.Get("http://dubbelboer.com/302cookie.php")
    if err != nil {
        log.Fatal(err)
    }

    // Read the response body.
    data, err := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    if err != nil {
        log.Fatal(err)
    }

    // Log the response.
    log.Println(string(data))
}</code>

In this example, the cookie jar is configured to follow the public suffix list, ensuring proper domain-based cookie handling. The client is created with the jar, and a GET request is made to the specified URL. The response body is read and logged, demonstrating that the cookie jar effectively handles the redirection and preserves the cookie.

The above is the detailed content of How can Go's CookieJar be used to follow redirects while preserving cookies?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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