Authenticated HTTP Client Requests from Go
Consider the following code snippet:
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) }
The problem here is that the second HTTP call fails with a 401 access denied error.
Why does this happen?
The reason is that the second request does not contain the session cookie that was obtained during the first request. To solve this, we need to create a cookie jar to store and reuse cookies across requests.
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:
jar := &myjar{} jar.jar = make(map[string] []*http.Cookie) client.Jar = jar
With these changes, the second request will have the necessary cookie to successfully authenticate and retrieve the details from the server.
以上是在使用基本驗證進行初步驗證後,如何在 Go 中對後續 HTTP 請求進行驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!