Compare commits

...

1 Commits

Author SHA1 Message Date
wangyue789 4a99898735 fix(client): send json request headers 2026-06-11 10:36:18 +08:00
2 changed files with 29 additions and 0 deletions

View File

@ -78,6 +78,10 @@ func (c *Client) Do(method, path string, body interface{}, query url.Values) (*o
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
if bodyReader != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.Debug {
fmt.Printf("→ %s %s\n", method, fullURL)

View File

@ -258,6 +258,12 @@ func TestClientDoWithBody(t *testing.T) {
if r.Method != "POST" {
t.Fatalf("expected POST, got %s", r.Method)
}
if got := r.Header.Get("Accept"); got != "application/json" {
t.Fatalf("Accept = %q, want application/json", got)
}
if got := r.Header.Get("Content-Type"); got != "application/json" {
t.Fatalf("Content-Type = %q, want application/json", got)
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"id":123}`))
}))
@ -273,6 +279,25 @@ func TestClientDoWithBody(t *testing.T) {
}
}
func TestClientDoWithoutBodySetsAcceptOnly(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("Accept"); got != "application/json" {
t.Fatalf("Accept = %q, want application/json", got)
}
if got := r.Header.Get("Content-Type"); got != "" {
t.Fatalf("Content-Type = %q, want empty", got)
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{}`))
}))
defer server.Close()
c := &Client{HTTP: server.Client(), BaseURL: server.URL}
if _, err := c.Do("GET", "/api/test", nil, nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestClientGet(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {