文档

HTTPS配置

更新时间:
一键部署

本节主要介绍V2.0 Go SDK对于HTTPS请求方式的配置。

在使用V2.0 Go SDK进行开发时,您可以在Config中配置请求协议,当Client在调用OpenAPI时,使用指定的请求协议进行通信。建议使用HTTPS,这样可以提升数据传输的安全性。若不设置,则使用OpenAPI默认支持的请求协议类型(HTTPS):

config := &openapi.Config{
    // 设定协议HTTPS/HTTP
    Protocol: tea.String("HTTPS"),
}
重要

使用HTTPS协议访问OpenAPI时,SDK会默认开启校验SSL/TLS证书有效性,若您代码环境没有证书环境,则会报错证书校验失败。

为保障通信安全,建议您保持开启,若在测试环境必须忽略证书校验,可以通过运行时参数IgnoreSSL设置

// 创建RuntimeObject实例并设置运行参数。
runtime := &util.RuntimeOptions{}
// 忽略 SSL 相关报错
runtime.IgnoreSSL = tea.Bool(true)

下面是完整示例:

package main

import (
	"encoding/json"
	"fmt"
	"github.com/aliyun/credentials-go/credentials"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

func main() {
	// 初始化Credential
	credential, err := credentials.NewCredential(nil)
	if err != nil {
		panic(err)
	}
	config := &openapi.Config{
		// 使用Credential配置凭证
		Credential: credential,
		// 设定协议 HTTPS/HTTP
		Protocol: tea.String("HTTPS"),
		RegionId: tea.String("<RegionId>"),
	}
	client, err := ecs20140526.NewClient(config)
	if err != nil {
		panic(err)
	}
	describeRegionsRequest := &ecs20140526.DescribeRegionsRequest{}
	// 创建RuntimeObject实例并设置运行参数。
	runtime := &util.RuntimeOptions{}
	// 忽略 SSL 相关报错
	runtime.IgnoreSSL = tea.Bool(true)
	resp, err := client.DescribeRegionsWithOptions(describeRegionsRequest, runtime)
	if err != nil {
		panic(err)
	}
	// response 包含服务端响应的 body 和 headers
	body, err := json.Marshal(resp.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("body: %s\n", string(body))
}