Skip to content
This repository has been archived by the owner on Nov 23, 2019. It is now read-only.

Commit

Permalink
Set fake host header for local communication.
Browse files Browse the repository at this point in the history
Signed-off-by: Lantao Liu <lantaol@google.com>
  • Loading branch information
Random-Liu committed Apr 21, 2016
1 parent 37cc88a commit d5a6705
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
5 changes: 5 additions & 0 deletions client/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ func (cli *Client) sendClientRequest(ctx context.Context, method, path string, q
}

req, err := cli.newRequest(method, path, query, body, headers)
if cli.proto == "unix" || cli.proto == "npipe" {
// For local communications, it doesn't matter what the host is. We just
// need a valid and meaningful host name. (See #189)
req.Host = "docker"
}
req.URL.Host = cli.addr
req.URL.Scheme = cli.transport.Scheme()

Expand Down
77 changes: 77 additions & 0 deletions client/request_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package client

import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strings"
"testing"

"golang.org/x/net/context"
)

// TestSetHostHeader should set fake host for local communications, set real host
// for normal communications.
func TestSetHostHeader(t *testing.T) {
testURL := "/test"
testCases := []struct {
host string
expectedHost string
expectedURLHost string
}{
{
"unix:///var/run/docker.sock",
"docker",
"/var/run/docker.sock",
},
{
"npipe:////./pipe/docker_engine",
"docker",
"//./pipe/docker_engine",
},
{
"tcp://0.0.0.0:4243",
"",
"0.0.0.0:4243",
},
{
"tcp://localhost:4243",
"",
"localhost:4243",
},
}

for c, test := range testCases {
proto, addr, basePath, err := ParseHost(test.host)
if err != nil {
t.Fatal(err)
}

client := &Client{
transport: newMockClient(nil, func(req *http.Request) (*http.Response, error) {
if !strings.HasPrefix(req.URL.Path, testURL) {
return nil, fmt.Errorf("Test Case #%d: Expected URL %q, got %q", c, testURL, req.URL)
}
if req.Host != test.expectedHost {
return nil, fmt.Errorf("Test Case #%d: Expected host %q, got %q", c, test.expectedHost, req.Host)
}
if req.URL.Host != test.expectedURLHost {
return nil, fmt.Errorf("Test Case #%d: Expected URL host %q, got %q", c, test.expectedURLHost, req.URL.Host)
}
return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader(([]byte("")))),
}, nil
}),
proto: proto,
addr: addr,
basePath: basePath,
}

_, err = client.sendRequest(context.Background(), "GET", testURL, nil, nil, nil)
if err != nil {
t.Fatal(err)
}
}
}

0 comments on commit d5a6705

Please sign in to comment.