Home > Backend Development > Golang > How to Follow Redirections with Cookies in Go?

How to Follow Redirections with Cookies in Go?

Patricia Arquette
Release: 2024-11-06 02:34:02
Original
693 people have browsed it

How to Follow Redirections with Cookies in Go?

Following Redirections with Cookies in Go

In handling HTTP requests, it's common to encounter redirects that carry cookies. This poses a challenge when using Golang, as the default behavior is to drop cookies during redirects. To overcome this, you can utilize the net/http/cookiejar package, introduced in Go 1.1.

With the cookiejar package, you can configure a client to automatically follow redirects while preserving the received cookies. To achieve this:

  1. Create a cookiejar.Jar to store the received cookies.
  2. Set the cookiejar.Jar as the Jar field of an http.Client instance.
  3. Use the modified client to make HTTP requests.

Here's an illustrative example:

<code class="go">package main

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

func main() {
    options := cookiejar.Options{
        PublicSuffixList: publicsuffix.List,
    }
    jar, err := cookiejar.New(&options)
    if err != nil {
        log.Fatal(err)
    }
    client := http.Client{Jar: jar}
    resp, err := client.Get("http://dubbelboer.com/302cookie.php")
    if err != nil {
        log.Fatal(err)
    }
    data, err := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    if err != nil {
        log.Fatal(err)
    }
    log.Println(string(data))
}</code>
Copy after login

By using this approach, your Go client will automatically follow redirects and maintain the received cookies, similar to the behavior in cURL when setting COOKIEFILE, AUTOREFERER, and FOLLOWLOCATION.

The above is the detailed content of How to Follow Redirections with Cookies in Go?. 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