120 lines
2.8 KiB
Go
120 lines
2.8 KiB
Go
package l_short_utl_request
|
||
|
||
import (
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"time"
|
||
)
|
||
|
||
type ShortUrl struct {
|
||
host string
|
||
auth string
|
||
}
|
||
|
||
func NewClient(args ...Option) *ShortUrl {
|
||
s := &ShortUrl{
|
||
host: "https://crm.1688sup.com/api",
|
||
}
|
||
for _, opt := range args {
|
||
opt(s)
|
||
}
|
||
return s
|
||
}
|
||
|
||
// BatchCreate 批量创建短链接。
|
||
//
|
||
// 参数:
|
||
// - urls: 需要生成短链的原始 URL 列表,每个 URL 长度至少为 1,不能为空切片。
|
||
// - index: 外部索引标识,用于后续批量查询和分组管理。非必填,传空字符串表示不设置索引。
|
||
//
|
||
// 返回:
|
||
// - error: 创建过程中遇到的错误,如参数校验失败、存储异常等。
|
||
//
|
||
// 注意:该方法会为每个 URL 生成对应的短链映射关系,任一 URL 创建失败将返回错误并中断后续处理。
|
||
|
||
func (s *ShortUrl) BatchCreate(in *ShortUrlBatchCreate) (*ShortUrlBatchCreateResult, error) {
|
||
path := "/openapi/short_url/batch/create"
|
||
if len(in.Urls) == 0 {
|
||
return nil, errors.New("url is empty")
|
||
}
|
||
if len(in.BatchName) == 0 {
|
||
in.BatchName = fmt.Sprintf("%s_%d", GenerateRandomLowerString(3), time.Now().Unix())
|
||
}
|
||
|
||
requestJson, err := StructToMap(in)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req := Request{
|
||
Method: "POST",
|
||
Url: s.host + path,
|
||
Json: requestJson,
|
||
Headers: s.GetHeader(),
|
||
}
|
||
resp, err := req.Send()
|
||
|
||
if err != nil {
|
||
return nil, fmt.Errorf("请求失败,err: %v", err)
|
||
}
|
||
var resData ShortUrlBatchCreateResult
|
||
err = CheckHttpRes(&resp, &resData)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return &resData, nil
|
||
}
|
||
|
||
func (s *ShortUrl) BatchQuery(in *BatchQueryReq) (*QueryBatchWithUrlResp, error) {
|
||
path := "/openapi/short_url/batch/query"
|
||
if in.BatchNo == 0 && in.Id == 0 && len(in.BatchName) == 0 {
|
||
return nil, errors.New("batch_no,id,batch_name必传其中一个")
|
||
}
|
||
|
||
requestJson, err := StructToMap(in)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
req := Request{
|
||
Method: "POST",
|
||
Url: s.host + path,
|
||
Json: requestJson,
|
||
Headers: s.GetHeader(),
|
||
}
|
||
resp, err := req.Send()
|
||
if err != nil {
|
||
return nil, fmt.Errorf("请求失败,err: %v", err)
|
||
}
|
||
var resData QueryBatchWithUrlResp
|
||
err = CheckHttpRes(&resp, &resData)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return &resData, nil
|
||
}
|
||
|
||
func CheckHttpRes(resp *Response, data interface{}) (err error) {
|
||
var resBody ResCommon
|
||
if err = json.Unmarshal(resp.Content, &resBody); err != nil {
|
||
return
|
||
}
|
||
|
||
if resBody.Code != 0 {
|
||
return fmt.Errorf("请求失败,err: %s", resBody.Message)
|
||
}
|
||
if data != nil {
|
||
dataByte, _ := json.Marshal(resBody.Data)
|
||
if err = json.Unmarshal(dataByte, data); err != nil {
|
||
return
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func (s *ShortUrl) GetHeader() map[string]string {
|
||
return map[string]string{
|
||
"Content-Type": "application/json",
|
||
"Authorization": s.auth,
|
||
}
|
||
}
|