ddliu / go-httpclient

Advanced HTTP client for golang
MIT License
465 stars 105 forks source link

Post throw panic when content-type is not kv #40

Closed oscarwin closed 4 years ago

oscarwin commented 4 years ago

Post method transfer params by called toUrlValues,but the payload of the request is a string and content-type is text/plain,toUrlValues will throw panic.

What to do in above scenario?

panic stack: panic: Invalid value [recovered] panic: Invalid value

goroutine 89 [running]: testing.tRunner.func1(0xc000336100) /usr/local/go/src/testing/testing.go:874 +0x3a3 panic(0x143e500, 0x15664c0) /usr/local/go/src/runtime/panic.go:679 +0x1b2 github.com/ddliu/go-httpclient.toUrlValues(0x143e500, 0xc000189e40, 0xc000189d38) /Users/liuteng/go/pkg/mod/github.com/ddliu/go-httpclient@v0.6.4/util.go:160 +0x2bc github.com/ddliu/go-httpclient.(*HttpClient).Post(0x184e9a0, 0xc0003ac060, 0x56, 0x143e500, 0xc000189e40, 0x1, 0x56, 0x104c3b7) /Users/liuteng/go/pkg/mod/github.com/ddliu/go-httpclient@v0.6.4/httpclient.go:661 +0x3f

ddliu commented 4 years ago

Could you please provide some example code?

ddliu commented 4 years ago

The string param is set as body in such case.

oscarwin commented 4 years ago

maybe PostJson can solve this problem, the payload could be string when call PostJson.

func (this *HttpClient) sendJson(method string, url string, data interface{}) (*Response, error) {
    headers := make(map[string]string)
    headers["Content-Type"] = "application/json"

    var body []byte
    switch t := data.(type) {
    case []byte:
        body = t
    case string:
                // if use PostJson,payload param could be string
        body = []byte(t)
    default:
        var err error
        body, err = json.Marshal(data)
        if err != nil {
            return nil, err
        }
    }

    return this.Do(method, url, headers, bytes.NewReader(body))
}
ddliu commented 4 years ago

Post with string param is supported by the latest version, please update and try again.

func TestPostText(t *testing.T) {
    c := NewHttpClient()

    res, err := c.Post("http://httpbin.org/post", "hello")
    if err != nil {
        t.Error(err)
    }

    if res.StatusCode != 200 {
        t.Error("Status code is not 200")
    }
}
oscarwin commented 4 years ago

OK,thanks