-
The server response would be like {
"result": 0,
"productCode": "111112"
} and {
"result": 0,
"messages": [
{
"message": "The productCode test_product_1 has been existed, try another one.",
"ruleType": 1
}
]
} Here is my solution below trying to make this case elegant, not taking benefit of auto-unmarshal of resty caused i didn't find any document about this. So, does resty give some solution or feature to handle a 200 response but the response body may be different in some cases? func (s *proxyService) CreateProduct(dto *CreateProductPayloadDTO, token string) (*CreateProductResDTO, error) {
var (
payload []byte
err error
createProductRes CreateProductResDTO
createProductResErrorDTO CreateProductResErrorDTO
res *resty.Response
)
if payload, err = json.Marshal(dto); err != nil {
return nil, err
}
if res, err = http_util.R(s.Resty, s.Context, token, nil).
SetBody(payload).
SetResult(&createProductRes).
Post(s.ProductHost + CreateProductEndpoint); err != nil || res.StatusCode() != 200 {
return nil, errors.New("create product in platform failed" + res.String())
}
if createProductRes.ProductId == 0 && createProductRes.Result == 0 {
if err = json.Unmarshal(res.Body(), &createProductResErrorDTO); err != nil {
return nil, errors.New("create product in platform failed")
}
if createProductResErrorDTO.Result == 0 && len(createProductResErrorDTO.Messages) != 0 {
return nil, errors.New("product code existed, try another one. " + createProductResErrorDTO.Messages[0].Message)
}
}
return &createProductRes, nil
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Of course a generic response dto is suitable for this case, but what about a quite different response ? type GenericResDTO struct {
Result int `json:"result"`
ProductId int64 `json:"productId"`
Messages []struct {
Message string `json:"message"`
RuleType int `json:"ruleType"`
} `json:"messages"`
} |
Beta Was this translation helpful? Give feedback.
-
@y4code Have a look at the section Features on the readme. That mentions the details of auto unmarshal for success and error scenarios.
It covers details about HTTP status codes on method doc. So, you can use your |
Beta Was this translation helpful? Give feedback.
@y4code Have a look at the section Features on the readme. That mentions the details of auto unmarshal for success and error scenarios.
Then, if you follow the godoc from the readme.
It covers details about HTTP status codes on method doc.
So, you can use your
GenericResDTO
on any scenario, and Resty does not limit you.