netutil: add BasicAuth function

etcd ships it's own BasicAuth function and no longer requires
Go 1.4 to build.
This commit is contained in:
Kelsey Hightower
2015-03-20 17:32:33 -07:00
parent b7bbeefbff
commit 4611c3b2d7
2 changed files with 39 additions and 2 deletions

View File

@@ -15,10 +15,13 @@
package netutil
import (
"encoding/base64"
"log"
"net"
"net/http"
"net/url"
"reflect"
"strings"
)
var (
@@ -99,3 +102,36 @@ func URLStringsEqual(a []string, b []string) bool {
return URLsEqual(urlsA, urlsB)
}
// BasicAuth returns the username and password provided in the request's
// Authorization header, if the request uses HTTP Basic Authentication.
// See RFC 2617, Section 2.
// Based on the BasicAuth method from the Golang standard lib.
// TODO: use the standard lib BasicAuth method when we move to Go 1.4.
func BasicAuth(r *http.Request) (username, password string, ok bool) {
auth := r.Header.Get("Authorization")
if auth == "" {
return
}
return parseBasicAuth(auth)
}
// parseBasicAuth parses an HTTP Basic Authentication string.
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
// Taken from the Golang standard lib.
// TODO: use the standard lib BasicAuth method when we move to Go 1.4.
func parseBasicAuth(auth string) (username, password string, ok bool) {
if !strings.HasPrefix(auth, "Basic ") {
return
}
c, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(auth, "Basic "))
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}