All Products
Search
Document Center

OpenSearch:Go client example

Last Updated:Apr 01, 2026

The Open Search Go client handles authentication, request signing, and HTTP communication with the Open Search service. Use it to configure credentials, initialize a client, and send authenticated requests.

Prerequisites

Before you begin, ensure that you have:

  • An Alibaba Cloud account with Open Search enabled

  • An AccessKey ID and AccessKey secret for authentication

Install the client

Add the required modules to your project:

go get github.com/alibabacloud-go/opensearch-util/service
go get github.com/alibabacloud-go/tea-utils/service
go get github.com/alibabacloud-go/tea/tea
go get github.com/aliyun/credentials-go/credentials

Set up the client

Configuration fields

FieldTypeDescription
Endpoint*stringService endpoint. Defaults to opensearch-cn-hangzhou.aliyuncs.com.
Protocol*stringHTTP protocol. Defaults to HTTP.
Type*stringCredential type. Defaults to access_key.
AccessKeyId*stringYour AccessKey ID.
AccessKeySecret*stringYour AccessKey secret.
SecurityToken*stringTemporary security token. Optional; used when authenticating with Security Token Service (STS) credentials.
UserAgent*stringUser agent string assigned to the client.

Initialize the client

Pass a Config to NewClient. Store your AccessKey ID and AccessKey secret in environment variables rather than hardcoding them in source code.

Replace your-module/client with the import path to your local client package.

package main

import (
    "fmt"
    "os"

    client "your-module/client"
    util "github.com/alibabacloud-go/tea-utils/service"
    "github.com/alibabacloud-go/tea/tea"
)

func main() {
    // Load credentials from environment variables — do not hardcode secrets in source code.
    cfg := &client.Config{
        Endpoint:        tea.String("opensearch-cn-hangzhou.aliyuncs.com"),
        Protocol:        tea.String("HTTP"),
        AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
        AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
    }

    c, err := client.NewClient(cfg)
    if err != nil {
        fmt.Println("Failed to initialize client:", err)
        return
    }
    _ = c
}

Make a request

Call Request with the following parameters:

ParameterTypeDescription
method*stringHTTP method, such as GET or POST.
pathname*stringRequest path, for example /v3/openapi/apps/<app-name>/search.
querymap[string]interface{}URL query parameters. Pass nil if none.
headersmap[string]*stringAdditional request headers. Pass nil to use defaults.
bodyinterface{}Request body. Pass nil for requests without a body.
runtime*util.RuntimeOptionsTimeout, proxy, retry, and SSL settings.

The client automatically sets the Date, Authorization, X-Opensearch-Nonce, and user-agent headers on every request. When a body is present, it also sets Content-Type: application/json and Content-MD5.

Configure runtime options

RuntimeOptions controls connection behavior. The client uses these defaults when options are not explicitly set:

OptionDefaultDescription
MaxAttempts3Maximum number of retry attempts.
BackoffPolicynoBackoff strategy between retries.
BackoffPeriod1Backoff period in seconds.
runtime := &util.RuntimeOptions{
    ReadTimeout:    tea.Int(5000),
    ConnectTimeout: tea.Int(3000),
    Autoretry:      tea.Bool(true),
    MaxAttempts:    tea.Int(5),
}

result, err := c.Request(
    tea.String("GET"),
    tea.String("/v3/openapi/apps/<app-name>/search"),
    map[string]interface{}{"query": "example search"},
    nil,
    nil,
    runtime,
)

Handle errors

The client returns a tea.SDKError for HTTP 4xx and 5xx responses. The error includes the status code, status message, and raw response body.

result, err := c.Request(...)
if err != nil {
    if sdkErr, ok := err.(*tea.SDKError); ok {
        fmt.Println("Status code:", sdkErr.Code)
        fmt.Println("Message:", sdkErr.Message)
        fmt.Println("Response body:", sdkErr.Data)
    }
    return
}
fmt.Println("Response:", result["body"])

If client.Credential is not set, GetAccessKeyId and GetAccessKeySecret return nil without an error. Ensure credentials are configured before calling Request.

Complete client code

The following is the complete auto-generated Go client. Do not edit this file manually.

// This file is auto-generated, don't edit it. Thanks.
/**
 *
 */
package client

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
}

What's next