diff --git a/http_client.go b/http_client.go index 361ecc6c..c4ec8f2a 100644 --- a/http_client.go +++ b/http_client.go @@ -3,6 +3,7 @@ package main import ( "bytes" "crypto/tls" + "encoding/base64" "io" "log" "net" @@ -44,6 +45,7 @@ type HTTPClient struct { baseURL string scheme string host string + auth string conn net.Conn respBuf []byte config *HTTPClientConfig @@ -79,6 +81,10 @@ func NewHTTPClient(baseURL string, config *HTTPClientConfig) *HTTPClient { client.respBuf = make([]byte, config.ResponseBufferSize) client.config = config + if u.User != nil { + client.auth = "Basic " + base64.StdEncoding.EncodeToString([]byte(u.User.String())) + } + return client } @@ -164,6 +170,10 @@ func (c *HTTPClient) Send(data []byte) (response []byte, err error) { data = proto.SetHost(data, []byte(c.baseURL), []byte(c.host)) } + if c.auth != "" { + data = proto.SetHeader(data, []byte("Authorization"), []byte(c.auth)) + } + if c.config.Debug { Debug("[HTTPClient] Sending:", string(data)) } diff --git a/http_client_test.go b/http_client_test.go index 79c71e70..00f9db3e 100644 --- a/http_client_test.go +++ b/http_client_test.go @@ -11,6 +11,7 @@ import ( "net/http/httptest" "net/http/httputil" _ "reflect" + "strings" "sync" "testing" "time" @@ -92,7 +93,7 @@ func TestHTTPClientResonseByClose(t *testing.T) { payload := []byte("GET / HTTP/1.1\r\n\r\n") ln, _ := net.Listen("tcp", ":0") - go func(){ + go func() { for { conn, _ := ln.Accept() buf := make([]byte, 4096) @@ -356,6 +357,45 @@ func TestHTTPClientRedirectLimit(t *testing.T) { wg.Wait() } +func TestHTTPClientBasicAuth(t *testing.T) { + wg := new(sync.WaitGroup) + wg.Add(2) + + GETPayload := []byte("GET / HTTP/1.1\r\n\r\n") + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, pass, _ := r.BasicAuth() + + if user != "user" || pass != "pass" { + http.Error(w, "Unauthorized.", 401) + wg.Done() + return + } + + wg.Done() + })) + defer server.Close() + + client := NewHTTPClient(server.URL, &HTTPClientConfig{Debug: false}) + resp, _ := client.Send(GETPayload) + client.Disconnect() + + if !bytes.Equal(proto.Status(resp), []byte("401")) { + t.Error("Should return unauthorized error", string(resp)) + } + + authUrl := strings.Replace(server.URL, "http://", "http://user:pass@", -1) + client = NewHTTPClient(authUrl, &HTTPClientConfig{Debug: false}) + resp, _ = client.Send(GETPayload) + client.Disconnect() + + if !bytes.Equal(proto.Status(resp), []byte("200")) { + t.Error("Should return proper response", string(resp)) + } + + wg.Wait() +} + func TestHTTPClientHandleHTTP10(t *testing.T) { wg := new(sync.WaitGroup)