parent
41ef981614
commit
2152ef6ef9
@ -0,0 +1,295 @@
|
||||
package search_ali
|
||||
|
||||
import (
|
||||
opensearchutil "github.com/alibabacloud-go/opensearch-util/service"
|
||||
util "github.com/alibabacloud-go/tea-utils/service"
|
||||
"github.com/alibabacloud-go/tea/tea"
|
||||
credential "github.com/aliyun/credentials-go/credentials"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Endpoint *string `json:"endpoint,omitempty" xml:"endpoint,omitempty"`
|
||||
Protocol *string `json:"protocol,omitempty" xml:"protocol,omitempty"`
|
||||
Type *string `json:"type,omitempty" xml:"type,omitempty"`
|
||||
SecurityToken *string `json:"securityToken,omitempty" xml:"securityToken,omitempty"`
|
||||
AccessKeyId *string `json:"accessKeyId,omitempty" xml:"accessKeyId,omitempty"`
|
||||
AccessKeySecret *string `json:"accessKeySecret,omitempty" xml:"accessKeySecret,omitempty"`
|
||||
UserAgent *string `json:"userAgent,omitempty" xml:"userAgent,omitempty"`
|
||||
}
|
||||
|
||||
func (s Config) String() string {
|
||||
return tea.Prettify(s)
|
||||
}
|
||||
|
||||
func (s Config) GoString() string {
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func (s *Config) SetEndpoint(v string) *Config {
|
||||
s.Endpoint = &v
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Config) SetProtocol(v string) *Config {
|
||||
s.Protocol = &v
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Config) SetType(v string) *Config {
|
||||
s.Type = &v
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Config) SetSecurityToken(v string) *Config {
|
||||
s.SecurityToken = &v
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Config) SetAccessKeyId(v string) *Config {
|
||||
s.AccessKeyId = &v
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Config) SetAccessKeySecret(v string) *Config {
|
||||
s.AccessKeySecret = &v
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Config) SetUserAgent(v string) *Config {
|
||||
s.UserAgent = &v
|
||||
return s
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
Endpoint *string
|
||||
Protocol *string
|
||||
UserAgent *string
|
||||
Credential credential.Credential
|
||||
}
|
||||
|
||||
func NewClient(config *Config) (*Client, error) {
|
||||
client := new(Client)
|
||||
err := client.Init(config)
|
||||
return client, err
|
||||
}
|
||||
|
||||
func (client *Client) Init(config *Config) (_err error) {
|
||||
if tea.BoolValue(util.IsUnset(tea.ToMap(config))) {
|
||||
_err = tea.NewSDKError(map[string]interface{}{
|
||||
"name": "ParameterMissing",
|
||||
"message": "'config' can not be unset",
|
||||
})
|
||||
return _err
|
||||
}
|
||||
|
||||
if tea.BoolValue(util.Empty(config.Type)) {
|
||||
config.Type = tea.String("access_key")
|
||||
}
|
||||
|
||||
credentialConfig := &credential.Config{
|
||||
AccessKeyId: config.AccessKeyId,
|
||||
Type: config.Type,
|
||||
AccessKeySecret: config.AccessKeySecret,
|
||||
SecurityToken: config.SecurityToken,
|
||||
}
|
||||
client.Credential, _err = credential.NewCredential(credentialConfig)
|
||||
if _err != nil {
|
||||
return _err
|
||||
}
|
||||
|
||||
client.Endpoint = config.Endpoint
|
||||
client.Protocol = config.Protocol
|
||||
client.UserAgent = config.UserAgent
|
||||
return nil
|
||||
}
|
||||
|
||||
func (client *Client) Request(method *string, pathname *string, query map[string]interface{}, headers map[string]*string, body interface{}, runtime *util.RuntimeOptions) (_result map[string]interface{}, _err error) {
|
||||
_err = tea.Validate(runtime)
|
||||
if _err != nil {
|
||||
return _result, _err
|
||||
}
|
||||
_runtime := map[string]interface{}{
|
||||
"timeouted": "retry",
|
||||
"readTimeout": tea.IntValue(runtime.ReadTimeout),
|
||||
"connectTimeout": tea.IntValue(runtime.ConnectTimeout),
|
||||
"httpProxy": tea.StringValue(runtime.HttpProxy),
|
||||
"httpsProxy": tea.StringValue(runtime.HttpsProxy),
|
||||
"noProxy": tea.StringValue(runtime.NoProxy),
|
||||
"maxIdleConns": tea.IntValue(runtime.MaxIdleConns),
|
||||
"retry": map[string]interface{}{
|
||||
"retryable": tea.BoolValue(runtime.Autoretry),
|
||||
"maxAttempts": tea.IntValue(util.DefaultNumber(runtime.MaxAttempts, tea.Int(3))),
|
||||
},
|
||||
"backoff": map[string]interface{}{
|
||||
"policy": tea.StringValue(util.DefaultString(runtime.BackoffPolicy, tea.String("no"))),
|
||||
"period": tea.IntValue(util.DefaultNumber(runtime.BackoffPeriod, tea.Int(1))),
|
||||
},
|
||||
"ignoreSSL": tea.BoolValue(runtime.IgnoreSSL),
|
||||
}
|
||||
|
||||
_resp := make(map[string]interface{})
|
||||
for _retryTimes := 0; tea.BoolValue(tea.AllowRetry(_runtime["retry"], tea.Int(_retryTimes))); _retryTimes++ {
|
||||
if _retryTimes > 0 {
|
||||
_backoffTime := tea.GetBackoffTime(_runtime["backoff"], tea.Int(_retryTimes))
|
||||
if tea.IntValue(_backoffTime) > 0 {
|
||||
tea.Sleep(_backoffTime)
|
||||
}
|
||||
}
|
||||
|
||||
_resp, _err = func() (map[string]interface{}, error) {
|
||||
request_ := tea.NewRequest()
|
||||
accesskeyId, _err := client.GetAccessKeyId()
|
||||
if _err != nil {
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
accessKeySecret, _err := client.GetAccessKeySecret()
|
||||
if _err != nil {
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
request_.Protocol = util.DefaultString(client.Protocol, tea.String("HTTP"))
|
||||
request_.Method = method
|
||||
request_.Pathname = pathname
|
||||
request_.Headers = tea.Merge(map[string]*string{
|
||||
"user-agent": client.GetUserAgent(),
|
||||
"Date": opensearchutil.GetDate(),
|
||||
"host": util.DefaultString(client.Endpoint, tea.String("opensearch-cn-hangzhou.aliyuncs.com")),
|
||||
"X-Opensearch-Nonce": util.GetNonce(),
|
||||
}, headers)
|
||||
if !tea.BoolValue(util.IsUnset(query)) {
|
||||
request_.Query = util.StringifyMapValue(query)
|
||||
}
|
||||
|
||||
if !tea.BoolValue(util.IsUnset(body)) {
|
||||
reqBody := util.ToJSONString(body)
|
||||
request_.Headers["Content-MD5"] = opensearchutil.GetContentMD5(reqBody)
|
||||
request_.Headers["Content-Type"] = tea.String("application/json")
|
||||
request_.Body = tea.ToReader(reqBody)
|
||||
}
|
||||
|
||||
request_.Headers["Authorization"] = opensearchutil.GetSignature(request_, accesskeyId, accessKeySecret)
|
||||
response_, _err := tea.DoRequest(request_, _runtime)
|
||||
if _err != nil {
|
||||
return _result, _err
|
||||
}
|
||||
objStr, _err := util.ReadAsString(response_.Body)
|
||||
if _err != nil {
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
if tea.BoolValue(util.Is4xx(response_.StatusCode)) || tea.BoolValue(util.Is5xx(response_.StatusCode)) {
|
||||
_err = tea.NewSDKError(map[string]interface{}{
|
||||
"message": tea.StringValue(response_.StatusMessage),
|
||||
"data": tea.StringValue(objStr),
|
||||
"code": tea.IntValue(response_.StatusCode),
|
||||
})
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
obj := util.ParseJSON(objStr)
|
||||
res := util.AssertAsMap(obj)
|
||||
_result = make(map[string]interface{})
|
||||
_err = tea.Convert(map[string]interface{}{
|
||||
"body": res,
|
||||
"headers": response_.Headers,
|
||||
}, &_result)
|
||||
return _result, _err
|
||||
}()
|
||||
if !tea.BoolValue(tea.Retryable(_err)) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return _resp, _err
|
||||
}
|
||||
|
||||
func (client *Client) SetUserAgent(userAgent *string) {
|
||||
client.UserAgent = userAgent
|
||||
}
|
||||
|
||||
func (client *Client) AppendUserAgent(userAgent *string) {
|
||||
client.UserAgent = tea.String(tea.StringValue(client.UserAgent) + " " + tea.StringValue(userAgent))
|
||||
}
|
||||
|
||||
func (client *Client) GetUserAgent() (_result *string) {
|
||||
userAgent := util.GetUserAgent(client.UserAgent)
|
||||
_result = userAgent
|
||||
return _result
|
||||
}
|
||||
|
||||
func (client *Client) GetAccessKeyId() (_result *string, _err error) {
|
||||
if tea.BoolValue(util.IsUnset(client.Credential)) {
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
accessKeyId, _err := client.Credential.GetAccessKeyId()
|
||||
if _err != nil {
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
_result = accessKeyId
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
func (client *Client) GetAccessKeySecret() (_result *string, _err error) {
|
||||
if tea.BoolValue(util.IsUnset(client.Credential)) {
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
secret, _err := client.Credential.GetAccessKeySecret()
|
||||
if _err != nil {
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
_result = secret
|
||||
return _result, _err
|
||||
}
|
||||
|
||||
type RecookSearchModel struct {
|
||||
Body struct {
|
||||
Errors []interface{} `json:"errors"`
|
||||
OpsRequestMisc string `json:"ops_request_misc"`
|
||||
RequestId string `json:"request_id"`
|
||||
Result struct {
|
||||
ComputeCost []struct {
|
||||
IndexName string `json:"index_name"`
|
||||
Value float64 `json:"value"`
|
||||
} `json:"compute_cost"`
|
||||
Facet []interface{} `json:"facet"`
|
||||
Items []struct {
|
||||
Attribute struct {
|
||||
} `json:"attribute"`
|
||||
Fields struct {
|
||||
Id string `json:"id"`
|
||||
IndexName string `json:"index_name"`
|
||||
} `json:"fields"`
|
||||
Property struct {
|
||||
} `json:"property"`
|
||||
SortExprValues []string `json:"sortExprValues"`
|
||||
VariableValue struct {
|
||||
} `json:"variableValue"`
|
||||
} `json:"items"`
|
||||
Num int `json:"num"`
|
||||
Searchtime float64 `json:"searchtime"`
|
||||
Total uint `json:"total"`
|
||||
Viewtotal int `json:"viewtotal"`
|
||||
} `json:"result"`
|
||||
Status string `json:"status"`
|
||||
Tracer string `json:"tracer"`
|
||||
} `json:"body"`
|
||||
Headers struct {
|
||||
Connection string `json:"connection"`
|
||||
ContentLength string `json:"content-length"`
|
||||
ContentType string `json:"content-type"`
|
||||
Date string `json:"date"`
|
||||
KeepAlive string `json:"keep-alive"`
|
||||
RequestId string `json:"request-id"`
|
||||
Server string `json:"server"`
|
||||
XActionName string `json:"x-action-name"`
|
||||
XAliyunUserId string `json:"x-aliyun-user-id"`
|
||||
XAppId string `json:"x-app-id"`
|
||||
XAppName string `json:"x-app-name"`
|
||||
XAppgroupId string `json:"x-appgroup-id"`
|
||||
} `json:"headers"`
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
package search_ali
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
util "github.com/alibabacloud-go/tea-utils/service"
|
||||
"github.com/alibabacloud-go/tea/tea"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func SearchByAliES(keyWords string, limit, page int) (goodsList []uint, total uint, err error) {
|
||||
// 创建请求用客户端实例
|
||||
// Endpoint 为 要访问服务的区域域名.
|
||||
// AccessKeyId 及AccessKeySecret 用于构造鉴权信息.
|
||||
config := &Config{
|
||||
Endpoint: tea.String("opensearch-cn-shanghai.aliyuncs.com"),
|
||||
AccessKeyId: tea.String("LTAI5tBeJdJBq2R9quhwGeQH"),
|
||||
AccessKeySecret: tea.String("sKvHrPwNWbVeDgUARAiGTluW06AQ4c"),
|
||||
}
|
||||
|
||||
// New 一个client, 用以发送请求.
|
||||
client, _clientErr := NewClient(config)
|
||||
|
||||
// 如果 NewClient 过程中出现异常. 则 返回 _clientErr 且输出 错误信息.
|
||||
if _clientErr != nil {
|
||||
fmt.Println(_clientErr)
|
||||
return
|
||||
}
|
||||
|
||||
// requestParams 信息
|
||||
requestParams := map[string]interface{}{
|
||||
"query": fmt.Sprintf("config=start:%v,hit:%v,format:fulljson&&query=default:'%s'&&filter=publish_status=1", int(20*(page-1)), limit, keyWords),
|
||||
}
|
||||
|
||||
// 请求发送的配置参数. 用以请求配置及连接池配置.
|
||||
runtime := &util.RuntimeOptions{
|
||||
ConnectTimeout: tea.Int(5000),
|
||||
ReadTimeout: tea.Int(10000),
|
||||
Autoretry: tea.Bool(false),
|
||||
IgnoreSSL: tea.Bool(false),
|
||||
MaxIdleConns: tea.Int(50),
|
||||
}
|
||||
|
||||
// 搜索接口需要提供 appName.
|
||||
// App 可以是 app 的版本信息. 也可以是 app 名称.
|
||||
appName := "recook"
|
||||
|
||||
// 发送请求的方法调用.
|
||||
response, _requestErr := client.Request(
|
||||
tea.String("GET"),
|
||||
tea.String("/v3/openapi/apps/"+appName+"/search"),
|
||||
requestParams,
|
||||
nil,
|
||||
nil,
|
||||
runtime)
|
||||
|
||||
// 如果 发送请求 过程中出现异常. 则 返回 _requestErr 且输出 错误信息.
|
||||
if _requestErr != nil {
|
||||
fmt.Println(_requestErr)
|
||||
return []uint{}, 0, errors.New("网络异常")
|
||||
}
|
||||
|
||||
// 输出正常返回的 response 内容.
|
||||
body, _ := json.MarshalIndent(response, "", " ")
|
||||
var gl RecookSearchModel
|
||||
err = json.Unmarshal(body, &gl)
|
||||
if err != nil {
|
||||
return []uint{}, 0, errors.New("网络异常2")
|
||||
}
|
||||
for _, item := range gl.Body.Result.Items {
|
||||
n, _ := strconv.Atoi(item.Fields.Id)
|
||||
goodsList = append(goodsList, uint(n))
|
||||
}
|
||||
total = gl.Body.Result.Total
|
||||
return
|
||||
}
|
Loading…
Reference in new issue