go-resty / resty

Simple HTTP and REST client library for Go
MIT License
9.89k stars 696 forks source link

Result value has been set and parsed correctly and the request returns successfully, the correct address cannot be recognized #744

Closed gwyCl closed 10 months ago

gwyCl commented 10 months ago
   type Response struct {
Code int         `json:"code"`
Msg  string      `json:"msg"`
Data interface{} `json:"data"`
     }

    ...
    client := resty.New().SetDebug(true)
resp, err := client.R().
    SetHeader("Content-Type", "application/json").
    SetHeader("Clustername", clusterName).
    SetBody(map[string]string{
        "serviceName": j.Uk,
        "deployment":  j.Env,
    }).
    SetResult(&Response{}).Post(url)
if err != nil {
    err = fmt.Errorf("getDockerfile err %s  url %s", err, resp.String())
    return
}
response, ok := resp.Result().(*Response)
if !ok {
    err = fmt.Errorf("parse Response  err %s resp %s", err, resp.String())
    return  err
}
 ==========================
  Unable to obtain the correct address during the return, resulting in an error in the address parsing step
  and request returns

STATUS       : 200 OK
PROTO        : HTTP/1.1
RECEIVED AT  : 2023-10-31T18:43:16.009538+08:00
TIME DURATION: 334.308877ms
HEADERS      :
        Connection: keep-alive
        Content-Type: text/plain; charset=utf-8
        Date: Tue, 31 Oct 2023 10:43:16 GMT
        Server: hertz
        Vary: Accept-Encoding
BODY     :
{
   "code":200,
   "msg":"success",
   "data":{"kind":"xx","apiVersion":"axxx","metadata": 
            {"name":"xxproduct","namespace":"default","creationTimestamp":null,"labels": 
             {"env":"product","environmentType":"product","uk":"xxx"},"annotations":{"xxx":"xxx"}}
            ...}
}
gwyCl commented 10 months ago

Okay, I understand the reason now. The response type is text/plain. What should I do to handle this? Could you give me some suggestions?

gwyCl commented 10 months ago
resp, err := client.R().
    SetHeader("Content-Type", "application/json").
    SetHeader("Clustername", clusterName).
    SetBody(map[string]string{
        "serviceName": j.Uk,
        "deployment":  j.Env,
    }).Post(fmt.Sprintf(config.SearchK8sTappUrl, clusterName))
if err != nil {
    err = fmt.Errorf("getDockerfile err %s  resp %s", err, resp.String())
    return
}
var response Response
err = json.Unmarshal([]byte(resp.String()), &response)
if err != nil {
    err = fmt.Errorf("json unmarshal err %s  resp %s", err, resp.String())
    return
}