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?
Creating the HTTP server Now we will add a check for basic auth in the greeting handler. If you look at the above carefully, you will see we are using the r. BasicAuth() method to extract the username password. Here is the method signature func (r *Request) BasicAuth() (username, password string, ok bool) .
HTTP basic authentication is a simple challenge and response mechanism with which a server can request authentication information (a user ID and password) from a client. The client passes the authentication information to the server in an Authorization header. The authentication information is in base-64 encoding.
Basic authentication is easy to define. In the global securityDefinitions section, add an entry with type: basic and an arbitrary name (in this example - basicAuth). Then, apply security to the whole API or specific operations by using the security section.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With