Basic HTTP Auth in Go

GoBasic Authentication

Go Problem Overview


I'm trying to do basic HTTP auth with the code below, but it is throwing out the following error:

> 2013/05/21 10:22:58 Get mydomain.com: unsupported protocol scheme "" > exit status 1

func basicAuth() string {
    var username string = "foo"
    var passwd string = "bar"
    client := &http.Client{}
    req, err := http.NewRequest("GET", "mydomain.com", nil)
    req.SetBasicAuth(username, passwd)
    resp, err := client.Do(req)
    if err != nil{
        log.Fatal(err)
    }
    bodyText, err := ioutil.ReadAll(resp.Body)
    s := string(bodyText)
    return s
}

Any idea what I may be doing wrong?

Go Solutions


Solution 1 - Go

the potential 'gotcha' is if your website does any redirects... Go-lang will drop your specified headers on the redirects. (I had to do wireshark to see this! You can quicky find out in chrome by right-clicking then "inspect element" and click network tab)

you'll want to define a redirect function that adds the header back in.

func basicAuth(username, password string) string {
  auth := username + ":" + password
  return base64.StdEncoding.EncodeToString([]byte(auth))
}

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

func main() {
  client := &http.Client{
    Jar: cookieJar,
    CheckRedirect: redirectPolicyFunc,
  }

  req, err := http.NewRequest("GET", "http://localhost/", nil)
  req.Header.Add("Authorization","Basic " + basicAuth("username1","password123")) 
  resp, err := client.Do(req)
}

Solution 2 - Go

You need to specify the protocol for NewRequest, e.g. "http://", see here.

req, err := http.NewRequest("GET", "http://mydomain.com", nil)

[1]: http://play.golang.org/p/bX0r-PbCv2 "here"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleonsasView Question on Stackoverflow
Solution 1 - GopmerrellView Answer on Stackoverflow
Solution 2 - GoRyanView Answer on Stackoverflow