Home >Backend Development >Golang >How to Handle Authentication Cookies for HTTP Requests in Go?

How to Handle Authentication Cookies for HTTP Requests in Go?

DDD
DDDOriginal
2024-11-08 22:56:02517browse

How to Handle Authentication Cookies for HTTP Requests in Go?

Improving Authentication Handling for HTTP Queries in Go

Problem:

Consider the following code for performing HTTP requests with authentication:

client := &http.Client{}

// Authenticate
req, err := http.NewRequest("GET", "http://164.99.113.32/Authenticate", nil)
req.SetBasicAuth("<username>", "<password>")
resp, err := client.Do(req)
if err != nil {
    fmt.Printf("Error : %s", err)
}

// Get Details
req.URL, _ = url.Parse("http://164.99.113.32/Details")
resp, err = client.Do(req)
if err != nil {
    fmt.Printf("Error : %s", err)
}

After authenticating successfully, the subsequent request to '/Details' fails with a 401 access-denied error, despite there being no issue on the server-side.

Solution:

To resolve this, it is necessary to utilize a cookie jar to manage session information. Go's HTTP client doesn't handle this by default, so we must define our custom cookie jar implementation:

type myjar struct {
    jar map[string] []*http.Cookie
}

func (p* myjar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    fmt.Printf("The URL is : %s\n", u.String())
    fmt.Printf("The cookie being set is : %s\n", cookies)
    p.jar [u.Host] = cookies
}

func (p *myjar) Cookies(u *url.URL) []*http.Cookie {
    fmt.Printf("The URL is : %s\n", u.String())
    fmt.Printf("Cookie being returned is : %s\n", p.jar[u.Host])
    return p.jar[u.Host]
}

In the main function, initialize the custom cookie jar and assign it to the HTTP client:

    jar := &myjar{}
    jar.jar = make(map[string] []*http.Cookie)
    client.Jar = jar

With this implementation, the subsequent request can successfully access the '/Details' endpoint.

The above is the detailed content of How to Handle Authentication Cookies for HTTP Requests 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