Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ Latency Percentiles:
u := config.ParsedTarget

httpCfg := config.ToHTTPConfig()
httpCfg.Version = cmd.Root().Version
if outputFormat != "json" {
httpCfg.Stderr = cmd.ErrOrStderr()
}
Expand Down
5 changes: 5 additions & 0 deletions internal/httpclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type Config struct {
Body string
Headers []string
Verbose bool
Version string
Stderr io.Writer
}

Expand Down Expand Up @@ -74,6 +75,10 @@ func MakeRequest(ctx context.Context, client HTTPDoer, cfg Config) (statusCode i
}
}

if req.Header.Get("User-Agent") == "" {
req.Header.Set("User-Agent", fmt.Sprintf("goperf/%s", cfg.Version))
}

if cfg.Body != "" && req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}
Expand Down
48 changes: 48 additions & 0 deletions internal/httpclient/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,54 @@ func TestMakeRequestSuccess(t *testing.T) {
}
}

func TestMakeRequest_DefaultUserAgent(t *testing.T) {
var gotUA string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotUA = r.Header.Get("User-Agent")
w.WriteHeader(http.StatusOK)
}))
defer server.Close()

_, _, err := MakeRequest(context.Background(), &http.Client{}, Config{
Target: server.URL,
Timeout: testTimeout,
Method: "GET",
Version: "1.2.3",
})
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if gotUA != "goperf/1.2.3" {
t.Errorf("expected User-Agent 'goperf/1.2.3', got %q", gotUA)
}
}

func TestMakeRequest_UserAgentOverride(t *testing.T) {
var gotUAValues []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotUAValues = r.Header.Values("User-Agent")
w.WriteHeader(http.StatusOK)
}))
defer server.Close()

_, _, err := MakeRequest(context.Background(), &http.Client{}, Config{
Target: server.URL,
Timeout: testTimeout,
Method: "GET",
Version: "1.2.3",
Headers: []string{"User-Agent: custom-agent/9.9"},
})
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if len(gotUAValues) != 1 {
t.Errorf("expected exactly 1 User-Agent value (no duplicates), got %v", gotUAValues)
}
if gotUAValues[0] != "custom-agent/9.9" {
t.Errorf("expected User-Agent 'custom-agent/9.9', got %q", gotUAValues[0])
}
}

func TestMakeRequest_Errors(t *testing.T) {
tests := []struct {
name string
Expand Down