75 lines
1.6 KiB
Go
75 lines
1.6 KiB
Go
package restyclient
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
|
|
resty "github.com/go-resty/resty/v2"
|
|
)
|
|
|
|
// CodeNotZeroErr ...
|
|
var CodeNotZeroErr = errors.New("resp code != 0")
|
|
|
|
// BKResult 蓝鲸返回规范的结构体
|
|
type BKResult[T any] struct {
|
|
Result bool `json:"result"` // 部分蓝鲸接口有, 按需校验
|
|
Code any `json:"code"`
|
|
Message string `json:"message"`
|
|
Data *T `json:"data"`
|
|
}
|
|
|
|
// NewBKResult create NewBKResult by resp
|
|
func NewBKResult[T any](resp *resty.Response) (*BKResult[T], error) {
|
|
if !resp.IsSuccess() {
|
|
return nil, fmt.Errorf("request failed, status: %s, message: %s", resp.Status(), resp.Body())
|
|
}
|
|
|
|
bkResult := new(BKResult[T])
|
|
if err := json.Unmarshal(resp.Body(), bkResult); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err := bkResult.ValidateCode(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return bkResult, nil
|
|
}
|
|
|
|
// NewBKData only create data by resp
|
|
func NewBKData[T any](resp *resty.Response) (*T, error) {
|
|
bkResult, err := NewBKResult[T](resp)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return bkResult.Data, nil
|
|
}
|
|
|
|
// ValidateCode 返回结果是否OK
|
|
func (r *BKResult[T]) ValidateCode() error {
|
|
var resultCode int
|
|
|
|
switch code := r.Code.(type) {
|
|
case int:
|
|
resultCode = code
|
|
case float64:
|
|
resultCode = int(code)
|
|
case string:
|
|
c, err := strconv.Atoi(code)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
resultCode = c
|
|
default:
|
|
return fmt.Errorf("conversion to int from %T not supported", code)
|
|
}
|
|
|
|
if resultCode != 0 {
|
|
return fmt.Errorf("%w, code=%d, message=%s", CodeNotZeroErr, resultCode, r.Message)
|
|
}
|
|
return nil
|
|
}
|