您现在的位置是:首页 >技术杂谈 >golang小demo网站首页技术杂谈
golang小demo
简介golang小demo
调用阿里云域名api和腾讯云负载均衡api的一个小demo,主要用来生成自动化的环境,供测试去使用
目录结构
具体代码
alidomain/alidomain.go
阿里云添加域名解析
package alidomain
import (
"fmt"
alidns20150109 "github.com/alibabacloud-go/alidns-20150109/v4/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"test/tencent-fuzai/mycommon"
)
/**
* 使用AK&SK初始化账号Client
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
var (
// 阿里key
accessKeyId string = "r3oQI2qlajDjyFX0"
accessKeySecret string = "0f5EA3jCRT0M14pE0p2wNLQSuQDR3s"
)
func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *alidns20150109.Client, _err error) {
config := &openapi.Config{
// 必填,您的 AccessKey ID
AccessKeyId: accessKeyId,
// 必填,您的 AccessKey Secret
AccessKeySecret: accessKeySecret,
}
// 访问的域名
config.Endpoint = tea.String("alidns.cn-hangzhou.aliyuncs.com")
_result = &alidns20150109.Client{}
_result, _err = alidns20150109.NewClient(config)
return _result, _err
}
func CreateDomain() (_err error) {
// 工程代码泄露可能会导致AccessKey泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378661.html
client, _err := CreateClient(tea.String(accessKeyId), tea.String(accessKeySecret))
if _err != nil {
return _err
}
addDomainRecordRequest := &alidns20150109.AddDomainRecordRequest{
DomainName: tea.String("zhubaoe.cn"),
RR: tea.String(mycommon.Domain),
Type: tea.String("A"),
Value: tea.String("1.14.224.189"),
}
runtime := &util.RuntimeOptions{}
tryErr := func() (_e error) {
defer func() {
if r := tea.Recover(recover()); r != nil {
_e = r
}
}()
// 复制代码运行请自行打印 API 的返回值
_, _err := client.AddDomainRecordWithOptions(addDomainRecordRequest, runtime)
if _err != nil {
return _err
}
//fmt.Println(result)
return nil
}()
if tryErr != nil {
var error = &tea.SDKError{}
if _t, ok := tryErr.(*tea.SDKError); ok {
error = _t
} else {
error.Message = tea.String(tryErr.Error())
}
// 如有需要,请打印 error
_, _err = util.AssertAsString(error.Message)
if _err != nil {
return _err
}
}
fmt.Println("域名解析添加成功")
return _err
}
mycommon/mycommon.go
公共变量
package mycommon
var (
Domain string
SecretId string
SecretKey string
)
tencentfuzai/bind-backend-rule.go
腾讯云添加服务器绑定到负载均衡的监听器(需在监听器先创建域名规则)
package tencentfuzai
import (
"fmt"
clb "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/clb/v20180317"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
)
func BindBackendRule(LocationId string) (res any, err error) {
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
client := CreateClient()
// 实例化一个请求对象,每个接口都会对应一个request对象
request := clb.NewRegisterTargetsRequest()
request.LoadBalancerId = common.StringPtr("lb-n20du9im")
request.ListenerId = common.StringPtr("lbl-os6epvnu")
request.LocationId = common.StringPtr(LocationId)
request.Targets = []*clb.Target{
&clb.Target{
Type: common.StringPtr("CVM"),
InstanceId: common.StringPtr("ins-avhbsbf2"),
Port: common.Int64Ptr(30793),
Weight: common.Int64Ptr(10),
},
}
// 返回的resp是一个RegisterTargetsResponse的实例,与请求对象对应
response, err := client.RegisterTargets(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("bind backend rule An API error has returned: %s", err)
return
}
if err != nil {
return nil, err
}
// 输出json格式的字符串回包
//fmt.Printf("%s", response.ToJsonString())
fmt.Println("域名绑定后端服务器规则创建成功")
return response.ToJsonString(), nil
}
tencentfuzai/client.go
公共client对象
package tencentfuzai
import (
clb "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/clb/v20180317"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
"test/tencent-fuzai/mycommon"
)
func CreateClient() *clb.Client {
credential := common.NewCredential(
mycommon.SecretId,
mycommon.SecretKey,
)
// 实例化一个client选项,可选的,没有特殊需求可以跳过
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "clb.tencentcloudapi.com"
// 实例化要请求产品的client对象,clientProfile是可选的
client, _ := clb.NewClient(credential, "ap-guangzhou", cpf)
return client
}
tencentfuzai/create-lb-rule.go
监听器添加规则
package tencentfuzai
import (
"fmt"
clb "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/clb/v20180317"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"test/tencent-fuzai/mycommon"
"time"
)
func CreateLbRule() (LocationIds []*string) {
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
client := CreateClient()
// 实例化一个请求对象,每个接口都会对应一个request对象
request := clb.NewCreateRuleRequest()
request.LoadBalancerId = common.StringPtr("lb-n20du9im")
request.ListenerId = common.StringPtr("lbl-os6epvnu")
domain := mycommon.Domain + ".zhubaoe.cn"
request.Rules = []*clb.RuleInput{
&clb.RuleInput{
Domain: common.StringPtr(domain),
Url: common.StringPtr("/"),
HealthCheck: &clb.HealthCheck{
HealthSwitch: common.Int64Ptr(1),
},
},
}
// 返回的resp是一个CreateRuleResponse的实例,与请求对象对应
response, err := client.CreateRule(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("create lb rule An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
// 输出json格式的字符串回包
//fmt.Printf("%s", response.ToJsonString())
var tag bool
for {
if tag {
break
}
statusRequest := clb.NewDescribeTaskStatusRequest()
statusRequest.TaskId = response.Response.RequestId
status, err := client.DescribeTaskStatus(statusRequest)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("查询创建clb规则结果失败: %s", err)
return
}
if err != nil {
panic(err)
}
switch *status.Response.Status {
case 0:
tag = true
break
case 1:
tag = true
break
case 2:
time.Sleep(time.Second * 1)
continue
}
}
fmt.Println("创建监听器规则成功")
return response.Response.LocationIds
}
tencentfuzai/query.go
查询监听器的id
package tencentfuzai
import (
"fmt"
clb "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/clb/v20180317"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
)
func QueryListenerId() {
// 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
// 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
client := CreateClient()
// 实例化一个请求对象,每个接口都会对应一个request对象
request := clb.NewDescribeListenersRequest()
request.LoadBalancerId = common.StringPtr("lb-n20du9im")
// 返回的resp是一个DescribeListenersResponse的实例,与请求对象对应
response, err := client.DescribeListeners(request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
fmt.Printf("An API error has returned: %s", err)
return
}
if err != nil {
panic(err)
}
// 输出json格式的字符串回包
fmt.Printf("%s", response.ToJsonString())
//for _, i2 := range response.Response.Listeners {
// fmt.Println(*i2.ListenerId)
//}
}
utils/utils.go
生成随机字符串的工具(随机域名)
package utils
import (
"math/rand"
"time"
)
func RandStr(length int) string {
str := "0123456789abcdefghijklmnopqrstuvwxyz"
bytes := []byte(str)
result := []byte{}
rand.Seed(time.Now().UnixNano() + int64(rand.Intn(100)))
for i := 0; i < length; i++ {
result = append(result, bytes[rand.Intn(len(bytes))])
}
domain := "randomain" + string(result)
return domain
}
main.go
入口函数
package main
import (
"fmt"
"test/tencent-fuzai/alidomain"
"test/tencent-fuzai/mycommon"
"test/tencent-fuzai/tencentfuzai"
"test/tencent-fuzai/utils"
)
func main() {
mycommon.Domain = utils.RandStr(10)
mycommon.SecretId = "AKIDDE0Wotr9WBcqTssez5waPzINDx2tbRHs"
mycommon.SecretKey = "YrNcbMuEoAICrHRNaZJH3hlcEcnkTy1N"
err2 := alidomain.CreateDomain()
if err2 != nil {
fmt.Println(err2)
}
ids := tencentfuzai.CreateLbRule()
var RuleId string
for _, id := range ids {
RuleId = *id
//fmt.Printf(*id)
}
_, err := tencentfuzai.BindBackendRule(RuleId)
if err != nil {
fmt.Println(err)
}
//fmt.Println(res)
fmt.Println("访问域名为:" + mycommon.Domain + ".zhubaoe.cn")
}
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。