Home > Backend Development > Golang > How Can I Perform Basic Authentication in Go Without Handling Redirects?

How Can I Perform Basic Authentication in Go Without Handling Redirects?

Susan Sarandon
Release: 2024-12-26 08:25:08
Original
432 people have browsed it

How Can I Perform Basic Authentication in Go Without Handling Redirects?

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
}
Copy after login

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))

}
Copy after login

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!

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