change request reader
This commit is contained in:
parent
f3b532ec67
commit
b1e60de34a
|
@ -1,7 +1,6 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
|
@ -92,17 +91,15 @@ func (client *Client) Delete(urlPath string) *Request {
|
|||
func (client *Client) execute(r *Request) (res *http.Response, err error) {
|
||||
var (
|
||||
n int
|
||||
buf []byte
|
||||
reader io.Reader
|
||||
)
|
||||
if r.contentType == "" && r.body != nil {
|
||||
r.contentType = r.detectContentType(r.body)
|
||||
}
|
||||
if r.body != nil {
|
||||
if buf, err = r.readRequestBody(r.contentType, r.body); err != nil {
|
||||
if reader, err = r.readRequestBody(r.contentType, r.body); err != nil {
|
||||
return
|
||||
}
|
||||
reader = bytes.NewReader(buf)
|
||||
}
|
||||
if r.rawRequest, err = http.NewRequest(r.method, r.uri, reader); err != nil {
|
||||
return
|
||||
|
|
|
@ -0,0 +1,14 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClient_execute(t *testing.T) {
|
||||
c := New()
|
||||
buf := []byte("Hello")
|
||||
c.Post("https://ip.nspix.com/geo").
|
||||
SetBody(bytes.NewReader(buf)).
|
||||
Do()
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
|
@ -63,16 +64,15 @@ func (r *Request) detectContentType(body interface{}) string {
|
|||
return contentType
|
||||
}
|
||||
|
||||
func (r *Request) readRequestBody(contentType string, body any) (buf []byte, err error) {
|
||||
func (r *Request) readRequestBody(contentType string, body any) (reader io.Reader, err error) {
|
||||
var (
|
||||
ok bool
|
||||
s string
|
||||
reader io.Reader
|
||||
ok bool
|
||||
s string
|
||||
buf []byte
|
||||
)
|
||||
kind := reflect.Indirect(reflect.ValueOf(body)).Type().Kind()
|
||||
if reader, ok = r.body.(io.Reader); ok {
|
||||
buf, err = io.ReadAll(reader)
|
||||
goto __end
|
||||
return reader, nil
|
||||
}
|
||||
if buf, ok = r.body.([]byte); ok {
|
||||
goto __end
|
||||
|
@ -91,6 +91,11 @@ func (r *Request) readRequestBody(contentType string, body any) (buf []byte, err
|
|||
}
|
||||
err = fmt.Errorf("unmarshal content type %s", contentType)
|
||||
__end:
|
||||
if err == nil {
|
||||
if len(buf) > 0 {
|
||||
return bytes.NewReader(buf), nil
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue