Support basic auth

since many API services are behind authenticated endpoints
This commit is contained in:
Ingo Oeser 2015-07-08 10:45:28 +02:00
parent 8665b88cbb
commit 25ae11ff27
1 changed files with 11 additions and 1 deletions

View File

@ -4,6 +4,7 @@ import (
"errors" "errors"
"io" "io"
"net/http" "net/http"
"os"
"time" "time"
"github.com/antonholmquist/jason" "github.com/antonholmquist/jason"
@ -17,13 +18,22 @@ type Expvar struct {
*jason.Object *jason.Object
} }
func getBasicAuthEnv() (user, password string) {
return os.Getenv("HTTP_USER"), os.Getenv("HTTP_PASSWORD")
}
// FetchExpvar fetches expvar by http for the given addr (host:port) // FetchExpvar fetches expvar by http for the given addr (host:port)
func FetchExpvar(addr string) (*Expvar, error) { func FetchExpvar(addr string) (*Expvar, error) {
e := &Expvar{&jason.Object{}} e := &Expvar{&jason.Object{}}
client := &http.Client{ client := &http.Client{
Timeout: 1 * time.Second, // TODO: make it configurable or left default? Timeout: 1 * time.Second, // TODO: make it configurable or left default?
} }
resp, err := client.Get(addr)
req, _ := http.NewRequest("GET", addr, nil)
if user, pass := getBasicAuthEnv(); user != "" && pass != "" {
req.SetBasicAuth(user, pass)
}
resp, err := client.Do(req)
if err != nil { if err != nil {
return e, err return e, err
} }