How Can I Request Basic Authentication Without Redirecting in Go Without Using Error Handling?
When interacting with a REST API that returns 302 redirects, obtaining the HTTP Location header can be difficult without automatic redirection.
Solution:
As an alternative to error handling, consider using the following CheckRedirect function for your HTTP client:
func noRedirect(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }
This simple modification informs the HTTP package not to follow redirects. Instead, it returns the last received response with an unclosed body and no error.
To illustrate, here's an updated version of the provided code:
package main import ( "fmt" "io/ioutil" "net/http" ) var BASE_URL = "https://api.example.com/v1" var STORMPATH_API_KEY_ID = "xxx" var STORMPATH_API_KEY_SECRET = "xxx" func main() { client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil) req.SetBasicAuth(STORMPATH_API_KEY_ID, STORMPATH_API_KEY_SECRET) resp, err := client.Do(req) // If we get here, it means one of two things: either this http request // actually failed, or we got an http redirect response, and should process it. if err != nil { if resp.StatusCode == 302 { fmt.Println("got redirect") } else { panic("HTTP request failed.") } } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }
The above is the detailed content of How Can I Perform Basic Authentication in Go Without Handling Redirects?. For more information, please follow other related articles on the PHP Chinese website!