Home > Backend Development > Golang > Why Does Go HTTP Authentication Fail with 'unsupported protocol scheme '''?

Why Does Go HTTP Authentication Fail with 'unsupported protocol scheme '''?

Barbara Streisand
Release: 2024-11-21 11:02:11
Original
248 people have browsed it

Why Does Go HTTP Authentication Fail with

Basic HTTP Authentication in Go: Resolving an Error Code

In attempting basic HTTP authentication with Go, you may encounter the error message "unsupported protocol scheme ''". Let's delve into the code and explore why this issue arises.

The problematic code is as follows:

func basicAuth() string {
    req, err := http.NewRequest("GET", "mydomain.example", nil)
Copy after login

The error stems from omitting the "http://" or "https://" prefix in the URL. To address this, modify the code to:

func basicAuth() string {
    req, err := http.NewRequest("GET", "http://mydomain.example", nil)
Copy after login

Ensure that the URL you provide includes the correct protocol scheme, either "http" or "https".

Additional Gotcha: Redirects

Be aware of a potential pitfall involving redirects. Go-lang discards specified headers during redirects. To overcome this, implement a custom redirect policy function that re-adds the header:

func redirectPolicyFunc(req *http.Request, via []*http.Request) error{
  req.Header.Add("Authorization","Basic " + basicAuth("username1","password123"))
  return nil
}
Copy after login

Incorporate the custom redirect policy into your client:

client := &http.Client{
  CheckRedirect: redirectPolicyFunc,
}
Copy after login

By following these adjustments, you can successfully perform basic HTTP authentication in Go and handle potential redirects without losing your authorization header.

The above is the detailed content of Why Does Go HTTP Authentication Fail with 'unsupported protocol scheme '''?. 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