Home >Backend Development >Golang >How to Handle HTTP POST Requests with Cookies in Go?

How to Handle HTTP POST Requests with Cookies in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 22:01:11313browse

How to Handle HTTP POST Requests with Cookies in Go?

Go: HTTP Post with Cookies

In Go, managing cookies for HTTP requests can be achieved using the cookiejar package introduced in Go 1.1. By creating a CookieJar and associating it with an HTTP client, cookies can be automatically stored and retrieved for subsequent requests.

Example Code

Here's an example of how to log into a website, store the cookies, and access another page using the stored cookies:

package main

import (
    "fmt"
    "net/http"
    "net/http/cookiejar"
    "net/url"
)

func main() {
    // Create a new cookie jar.
    jar, err := cookiejar.New(nil)
    if err != nil {
        panic(err)
    }

    // Create an HTTP client that uses the cookie jar.
    client := &http.Client{
        Jar: jar,
    }

    // Login to the website.
    loginPostUrl := "http://www.example.com/login"
    values := url.Values{}
    values.Set("username", "my_username")
    values.Set("password", "my_password")
    resp, err := client.PostForm(loginPostUrl, values)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    // View the user's bill.
    viewBillUrl := "http://www.example.com/my/bill"
    resp, err = client.Get(viewBillUrl)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    // Read the bill's contents.
    billContents, err := resp.Body.ReadString('\n')
    if err != nil {
        panic(err)
    }

    fmt.Println(billContents)
}

In this example, the CookieJar is used to automatically store the cookies returned by the login request. These cookies are then used to authorize the subsequent request to the /my/bill page.

The above is the detailed content of How to Handle HTTP POST Requests with Cookies in Go?. 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