This commit is contained in:
zhouqunjie 2022-08-31 16:11:58 +08:00
commit dc1c0dfa66
398 changed files with 74555 additions and 244 deletions

30
.gitignore vendored
View File

@ -1,5 +1,27 @@
/vendor/
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
*.a
/.idea/shelf/在进行更新之前于_2022_7_14_下午3_34_取消提交了变更_[Changes]/shelved.patch
/.idea/shelf/_2022_7_14_3_34___Changes_.xml
/.idea/shelf/在进行更新之前于_2022_7_14_下午3_34_取消提交了变更_[Changes]/shelved.patch
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Files generated by JetBrains IDEs, e.g. IntelliJ IDEA
.idea/
*.iml
bin/
# Vscode files
.vscode/
__debug_bin
log/
cache/
tmp/
testbin/

View File

@ -1,8 +1,6 @@
FROM alpine:3.16.2
WORKDIR /home
RUN mkdir -p /root/.kube/
# 修改alpine源为上海交通大学
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.sjtug.sjtu.edu.cn/g' /etc/apk/repositories && \
apk update && \
@ -12,10 +10,9 @@ RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.sjtug.sjtu.edu.cn/g' /etc/apk/repos
rm -rf /var/cache/apk/*
COPY karmada /home/
COPY config_test /root/.kube/config
COPY jcce-karmada /home/
ENV TZ=Asia/Shanghai
EXPOSE 8082
ENTRYPOINT ./karmada
ENTRYPOINT ./jcce-karmada

143
cmd/backend/Jenkinsfile vendored Normal file
View File

@ -0,0 +1,143 @@
def JOB_NAME = "${env.JOB_NAME}"
def BUILD_NUMBER = "${env.BUILD_NUMBER}"
def label = "jenkins-${JOB_NAME}-${BUILD_NUMBER}-${UUID.randomUUID().toString()}"
def secret_name = "harbor-auth"
def helmLint(String chartDir) {
println "校验 chart 模板"
sh "helm lint ${chartDir}"
}
def helmDeploy(Map args) {
if (args.debug) {
println "Debug 应用"
sh "helm upgrade --dry-run --debug --install ${args.name} ${args.chartDir} -f ${args.valuePath} --set image.tag=${args.imageTag} --namespace ${args.namespace}"
} else {
println "部署应用"
sh "helm upgrade --install ${args.name} ${args.chartDir} -f ${args.valuePath} --set image.tag=${args.imageTag} --namespace ${args.namespace}"
echo "应用 ${args.name} 部署成功. 可以使用 helm status ${args.name} 查看应用状态"
}
}
podTemplate(label: label, containers: [
containerTemplate(name: 'golang', image: 'golang:1.18.5-alpine3.16', command: 'cat', ttyEnabled: true),
containerTemplate(name: 'docker', image: 'docker:latest', command: 'cat', ttyEnabled: true),
// containerTemplate(name: 'helm', image: 'cnych/helm', command: 'cat', ttyEnabled: true),
containerTemplate(name: 'kubectl', image: 'jcce/kubectl:1.23.7', command: 'cat', ttyEnabled: true)
], serviceAccount: 'jenkins', volumes: [
hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock')
]) {
node(label) {
def myRepo = checkout scm
// 获取 git commit id 作为镜像标签
def imageTag = sh(script: "git rev-parse --short HEAD", returnStdout: true).trim()
// 仓库地址
def registryUrl = "hub.jcce-dev.net:8443"
def imageEndpoint = "jcce/jcce-karmada"
// 镜像
def image = "${registryUrl}/${imageEndpoint}:${imageTag}"
stage('单元测试') {
echo "1.测试阶段"
}
stage('代码编译打包') {
try {
container('golang') {
echo "2.代码编译打包阶段"
sh """
cd cmd/backend/
export GOPROXY=https://goproxy.cn
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o jcce-karmada ./main.go
"""
}
} catch (exc) {
println "构建失败 - ${currentBuild.fullDisplayName}"
throw(exc)
}
}
stage('构建 Docker 镜像') {
withCredentials([[$class: 'UsernamePasswordMultiBinding',
credentialsId: 'docker-auth',
usernameVariable: 'DOCKER_USER',
passwordVariable: 'DOCKER_PASSWORD']]) {
container('docker') {
echo "3. 构建 Docker 镜像阶段"
sh('cat /etc/resolv.conf')
sh("docker login '${registryUrl}' -u '${DOCKER_USER}' -p '${DOCKER_PASSWORD}' ")
sh("docker build -t '${image}' -f cmd/backend/Dockerfile cmd/backend/")
sh("docker push '${image}'")
}
}
}
// stage('运行 Helm') {
// withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
// container('helm') {
// sh "mkdir -p ~/.kube && cp ${KUBECONFIG} ~/.kube/config"
// echo "4.开始 Helm 部署"
// def userInput = input(
// id: 'userInput',
// message: '选择一个部署环境',
// parameters: [
// [
// $class: 'ChoiceParameterDefinition',
// choices: "Dev\nQA\nProd",
// name: 'Env'
// ]
// ]
// )
// echo "部署应用到 ${userInput} 环境"
// // 选择不同环境下面的 values 文件
// if (userInput == "Dev") {
// // deploy dev stuff
// } else if (userInput == "QA"){
// // deploy qa stuff
// } else {
// // deploy prod stuff
// }
// helmDeploy(
// debug : false,
// name : "${JOB_NAME}",
// chartDir : "./helm",
// namespace : "jcce-system",
// valuePath : "./helm/my-values.yaml",
// imageTag : "${imageTag}"
// )
// }
// }
// }
stage('运行 Kubectl 部署到k8s平台') {
withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
container('kubectl') {
echo "5.部署应用"
sh('mkdir -p ~/.kube && cp ${KUBECONFIG} ~/.kube/config')
sh("sed -i 's#IMAGE_NAME#${image}#' cmd/backend/deploy/jcce-karmada-deployment.yaml")
sh("sed -i 's#SECRET_NAME#${secret_name}#' cmd/backend/deploy/jcce-karmada-deployment.yaml")
sh('kubectl apply -f cmd/backend/deploy/')
sh('sleep 3')
echo "6.查看应用"
sh('kubectl get all -n jcce-system -l app=${JOB_NAME}')
}
}
}
// stage('快速回滚?') {
// withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
// container('helm') {
// sh "mkdir -p ~/.kube && cp ${KUBECONFIG} ~/.kube/config"
// def userInput = input(
// id: 'userInput',
// message: '是否需要快速回滚?',
// parameters: [
// [
// $class: 'ChoiceParameterDefinition',
// choices: "Y\nN",
// name: '回滚?'
// ]
// ]
// )
// if (userInput == "Y") {
// sh "helm rollback ${JOB_NAME} --namespace jcce-system"
// }
// }
// }
// }
}
}

View File

@ -10,6 +10,7 @@ import (
"github.com/karmada-io/karmada/pkg/util"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"net/http"
"os"
"strconv"
"strings"
"time"
@ -37,7 +38,7 @@ type JoinRequest struct {
Labels map[string]string `json:"labels,omitempty" protobuf:"bytes,11,rep,name=labels"`
}
//ListCluster 查询集群列表
// ListCluster 查询集群列表
func ListCluster(c *gin.Context) {
clusterName, _ := c.GetQuery("cluster_name")
@ -86,7 +87,7 @@ func ListCluster(c *gin.Context) {
Response(c, http.StatusOK, "success", data)
}
//ListClusterWithLabel 查询有标签的集群列表
// ListClusterWithLabel 查询有标签的集群列表
func ListClusterWithLabel(c *gin.Context) {
clusterName, _ := c.GetQuery("cluster_name")
@ -173,7 +174,7 @@ func UnJoin(c *gin.Context) {
Response(c, http.StatusOK, "success", "")
}
//Join 新集群加入联邦
// Join 新集群加入联邦
func Join(c *gin.Context) {
var (
Labels map[string]string
@ -185,7 +186,8 @@ func Join(c *gin.Context) {
return
}
file, _ := c.FormFile("file")
memberClusterConfigName := ConfigNacos.Karmada.MemberConfigPath + "/" + memberName + ".config"
dir, _ := os.Getwd()
memberClusterConfigName := dir + "/karmadaConfig/" + memberName + ".config"
// 上传文件至指定目录
if err := c.SaveUploadedFile(file, memberClusterConfigName); err != nil {
glog.Errorf("File upload failed err %v", err)
@ -259,7 +261,7 @@ func Join(c *gin.Context) {
Response(c, http.StatusOK, "success", "")
}
//TagCluster 集群打标签
// TagCluster 集群打标签
func TagCluster(c *gin.Context) {
var clusterTag Cluster
if err := c.BindJSON(&clusterTag); err != nil {
@ -303,14 +305,14 @@ func UnTagCluster(c *gin.Context) {
Response(c, http.StatusOK, "success", cluster)
}
//删除map中的某个key
// 删除map中的某个key
func deleteMaps(labels map[string]string, keys map[string]string) {
for key := range keys {
delete(labels, key)
}
}
//ListByDomain 根据项目名称、工作负载、域id查询集群
// ListByDomain 根据项目名称、工作负载、域id查询集群
func ListByDomain(c *gin.Context) {
namespaceName, _ := c.GetQuery("namespace")
deploymentName, _ := c.GetQuery("deployment_name")

View File

@ -2,10 +2,12 @@ package app
import (
"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/clients/config_client"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/vo"
"gopkg.in/yaml.v3"
"log"
"os"
)
type Config struct {
@ -30,31 +32,7 @@ type Config struct {
}
func GetNacosConfig() Config {
serverConfig := []constant.ServerConfig{
{
IpAddr: "10.101.15.6",
Port: 8848,
},
}
// 创建clientConfig
clientConfig := constant.ClientConfig{
NamespaceId: "zqj",
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogLevel: "debug",
}
// 创建动态配置客户端
configClient, err := clients.CreateConfigClient(map[string]interface{}{
"serverConfigs": serverConfig,
"clientConfig": clientConfig,
})
if err != nil {
log.Fatalf("初始化nacos失败: %s", err.Error())
}
configClient := GetClient()
// 获取配置
dataId := "dispatch_center_test"
group := "dispatch"
@ -70,5 +48,52 @@ func GetNacosConfig() Config {
if err != nil {
log.Fatalf("解析%s配置失败: %s", dataId, err.Error())
}
CreateKarmadaHostConfig()
return config
}
func GetClient() config_client.IConfigClient {
serverConfig := []constant.ServerConfig{
{
IpAddr: "nacos-client",
Port: 8848,
},
}
// 创建clientConfig
clientConfig := constant.ClientConfig{
NamespaceId: "zqj", // 如果需要支持多namespace我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时此处填空字符串。
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogLevel: "debug",
}
// 创建动态配置客户端
configClient, err := clients.CreateConfigClient(map[string]interface{}{
"serverConfigs": serverConfig,
"clientConfig": clientConfig,
})
if err != nil {
log.Fatalf("初始化nacos失败: %s", err.Error())
}
return configClient
}
// CreateKarmadaHostConfig 从nacos读取配置创建karmada-host集群配置文件
func CreateKarmadaHostConfig() {
configName := "karmada-host"
client := GetClient()
content, err := client.GetConfig(vo.ConfigParam{
DataId: "karmada-host",
Group: "dispatch",
})
if err != nil {
log.Fatalf("获取%s配置失败: %s", "golang", err.Error())
}
dir, _ := os.Getwd()
err = os.MkdirAll(dir+"/karmadaConfig", 0766)
if err != nil {
log.Fatalf("nacos 配置目录创建失败,error:%s", err.Error())
}
clusterConfig, err := os.Create("karmadaConfig/" + configName)
defer clusterConfig.Close()
clusterConfig.Write([]byte(content))
}

View File

@ -13,6 +13,7 @@ import (
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"net/http"
"os"
)
var DB *sql.DB
@ -33,9 +34,10 @@ func InitRouter() *gin.Engine {
DB.SetMaxIdleConns(int(ConfigNacos.Mysql.MaxIdleConn))
//Karmada Client
dir, _ := os.Getwd()
KarmadaConfig = karmadactl.NewKarmadaConfig(clientcmd.NewDefaultPathOptions())
KarmadaConfig.GetClientConfig("", ConfigNacos.Karmada.ConfigPath)
ControlPlaneRestConfig, _ = KarmadaConfig.GetRestConfig("", ConfigNacos.Karmada.ConfigPath)
KarmadaConfig.GetClientConfig("", dir+"/karmadaConfig/karmada-host")
ControlPlaneRestConfig, _ = KarmadaConfig.GetRestConfig("", dir+"/karmadaConfig/karmada-host")
KarmadaClient = karmadaclientset.NewForConfigOrDie(ControlPlaneRestConfig)
ClientSet, _ = utils.NewClientSet(ControlPlaneRestConfig)

View File

@ -20,7 +20,7 @@ spec:
- name: SECRET_NAME
containers:
- name: jcce-karmada
image: jcce/jcce-karmada:latest
image: IMAGE_NAME
resources: {}
imagePullPolicy: Always
securityContext:

View File

@ -1,52 +1,52 @@
# heredoc
[![Build Status](https://circleci.com/gh/MakeNowJust/heredoc.svg?style=svg)](https://circleci.com/gh/MakeNowJust/heredoc) [![GoDoc](https://godoc.org/github.com/MakeNowJusti/heredoc?status.svg)](https://godoc.org/github.com/MakeNowJust/heredoc)
## About
Package heredoc provides the here-document with keeping indent.
## Install
```console
$ go get github.com/MakeNowJust/heredoc
```
## Import
```go
// usual
import "github.com/MakeNowJust/heredoc"
```
## Example
```go
package main
import (
"fmt"
"github.com/MakeNowJust/heredoc"
)
func main() {
fmt.Println(heredoc.Doc(`
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, ...
`))
// Output:
// Lorem ipsum dolor sit amet, consectetur adipisicing elit,
// sed do eiusmod tempor incididunt ut labore et dolore magna
// aliqua. Ut enim ad minim veniam, ...
//
}
```
## API Document
- [heredoc - GoDoc](https://godoc.org/github.com/MakeNowJust/heredoc)
## License
This software is released under the MIT License, see LICENSE.
# heredoc
[![Build Status](https://circleci.com/gh/MakeNowJust/heredoc.svg?style=svg)](https://circleci.com/gh/MakeNowJust/heredoc) [![GoDoc](https://godoc.org/github.com/MakeNowJusti/heredoc?status.svg)](https://godoc.org/github.com/MakeNowJust/heredoc)
## About
Package heredoc provides the here-document with keeping indent.
## Install
```console
$ go get github.com/MakeNowJust/heredoc
```
## Import
```go
// usual
import "github.com/MakeNowJust/heredoc"
```
## Example
```go
package main
import (
"fmt"
"github.com/MakeNowJust/heredoc"
)
func main() {
fmt.Println(heredoc.Doc(`
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, ...
`))
// Output:
// Lorem ipsum dolor sit amet, consectetur adipisicing elit,
// sed do eiusmod tempor incididunt ut labore et dolore magna
// aliqua. Ut enim ad minim veniam, ...
//
}
```
## API Document
- [heredoc - GoDoc](https://godoc.org/github.com/MakeNowJust/heredoc)
## License
This software is released under the MIT License, see LICENSE.

201
vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,249 @@
package sdk
import (
"encoding/json"
"strings"
"time"
)
var apiTimeouts = `{
"ecs": {
"ActivateRouterInterface": 10,
"AddTags": 61,
"AllocateDedicatedHosts": 10,
"AllocateEipAddress": 17,
"AllocatePublicIpAddress": 36,
"ApplyAutoSnapshotPolicy": 10,
"AssignIpv6Addresses": 10,
"AssignPrivateIpAddresses": 10,
"AssociateEipAddress": 17,
"AttachClassicLinkVpc": 14,
"AttachDisk": 36,
"AttachInstanceRamRole": 11,
"AttachKeyPair": 16,
"AttachNetworkInterface": 16,
"AuthorizeSecurityGroupEgress": 16,
"AuthorizeSecurityGroup": 16,
"CancelAutoSnapshotPolicy": 10,
"CancelCopyImage": 10,
"CancelPhysicalConnection": 10,
"CancelSimulatedSystemEvents": 10,
"CancelTask": 10,
"ConnectRouterInterface": 10,
"ConvertNatPublicIpToEip": 12,
"CopyImage": 10,
"CreateAutoSnapshotPolicy": 10,
"CreateCommand": 16,
"CreateDeploymentSet": 16,
"CreateDisk": 36,
"CreateHpcCluster": 10,
"CreateImage": 36,
"CreateInstance": 86,
"CreateKeyPair": 10,
"CreateLaunchTemplate": 10,
"CreateLaunchTemplateVersion": 10,
"CreateNatGateway": 36,
"CreateNetworkInterfacePermission": 13,
"CreateNetworkInterface": 16,
"CreatePhysicalConnection": 10,
"CreateRouteEntry": 17,
"CreateRouterInterface": 10,
"CreateSecurityGroup": 86,
"CreateSimulatedSystemEvents": 10,
"CreateSnapshot": 86,
"CreateVirtualBorderRouter": 10,
"CreateVpc": 16,
"CreateVSwitch": 17,
"DeactivateRouterInterface": 10,
"DeleteAutoSnapshotPolicy": 10,
"DeleteBandwidthPackage": 10,
"DeleteCommand": 16,
"DeleteDeploymentSet": 12,
"DeleteDisk": 16,
"DeleteHpcCluster": 10,
"DeleteImage": 36,
"DeleteInstance": 66,
"DeleteKeyPairs": 10,
"DeleteLaunchTemplate": 10,
"DeleteLaunchTemplateVersion": 10,
"DeleteNatGateway": 10,
"DeleteNetworkInterfacePermission": 10,
"DeleteNetworkInterface": 16,
"DeletePhysicalConnection": 10,
"DeleteRouteEntry": 16,
"DeleteRouterInterface": 10,
"DeleteSecurityGroup": 87,
"DeleteSnapshot": 17,
"DeleteVirtualBorderRouter": 10,
"DeleteVpc": 17,
"DeleteVSwitch": 17,
"DescribeAccessPoints": 10,
"DescribeAccountAttributes": 10,
"DescribeAutoSnapshotPolicyEx": 16,
"DescribeAvailableResource": 10,
"DescribeBandwidthLimitation": 16,
"DescribeBandwidthPackages": 10,
"DescribeClassicLinkInstances": 15,
"DescribeCloudAssistantStatus": 16,
"DescribeClusters": 10,
"DescribeCommands": 16,
"DescribeDedicatedHosts": 10,
"DescribeDedicatedHostTypes": 10,
"DescribeDeploymentSets": 26,
"DescribeDiskMonitorData": 16,
"DescribeDisksFullStatus": 14,
"DescribeDisks": 19,
"DescribeEipAddresses": 16,
"DescribeEipMonitorData": 16,
"DescribeEniMonitorData": 10,
"DescribeHaVips": 10,
"DescribeHpcClusters": 16,
"DescribeImageSharePermission": 10,
"DescribeImages": 38,
"DescribeImageSupportInstanceTypes": 16,
"DescribeInstanceAttribute": 36,
"DescribeInstanceAutoRenewAttribute": 17,
"DescribeInstanceHistoryEvents": 19,
"DescribeInstanceMonitorData": 19,
"DescribeInstancePhysicalAttribute": 10,
"DescribeInstanceRamRole": 11,
"DescribeInstancesFullStatus": 14,
"DescribeInstances": 10,
"DescribeInstanceStatus": 26,
"DescribeInstanceTopology": 12,
"DescribeInstanceTypeFamilies": 17,
"DescribeInstanceTypes": 17,
"DescribeInstanceVncPasswd": 10,
"DescribeInstanceVncUrl": 36,
"DescribeInvocationResults": 16,
"DescribeInvocations": 16,
"DescribeKeyPairs": 12,
"DescribeLaunchTemplates": 16,
"DescribeLaunchTemplateVersions": 16,
"DescribeLimitation": 36,
"DescribeNatGateways": 10,
"DescribeNetworkInterfacePermissions": 13,
"DescribeNetworkInterfaces": 16,
"DescribeNewProjectEipMonitorData": 16,
"DescribePhysicalConnections": 10,
"DescribePrice": 16,
"DescribeRecommendInstanceType": 10,
"DescribeRegions": 19,
"DescribeRenewalPrice": 16,
"DescribeResourceByTags": 10,
"DescribeResourcesModification": 17,
"DescribeRouterInterfaces": 10,
"DescribeRouteTables": 17,
"DescribeSecurityGroupAttribute": 133,
"DescribeSecurityGroupReferences": 16,
"DescribeSecurityGroups": 25,
"DescribeSnapshotLinks": 17,
"DescribeSnapshotMonitorData": 12,
"DescribeSnapshotPackage": 10,
"DescribeSnapshots": 26,
"DescribeSnapshotsUsage": 26,
"DescribeSpotPriceHistory": 22,
"DescribeTags": 17,
"DescribeTaskAttribute": 10,
"DescribeTasks": 11,
"DescribeUserBusinessBehavior": 13,
"DescribeUserData": 10,
"DescribeVirtualBorderRoutersForPhysicalConnection": 10,
"DescribeVirtualBorderRouters": 10,
"DescribeVpcs": 41,
"DescribeVRouters": 17,
"DescribeVSwitches": 17,
"DescribeZones": 103,
"DetachClassicLinkVpc": 14,
"DetachDisk": 17,
"DetachInstanceRamRole": 10,
"DetachKeyPair": 10,
"DetachNetworkInterface": 16,
"EipFillParams": 19,
"EipFillProduct": 13,
"EipNotifyPaid": 10,
"EnablePhysicalConnection": 10,
"ExportImage": 10,
"GetInstanceConsoleOutput": 14,
"GetInstanceScreenshot": 14,
"ImportImage": 29,
"ImportKeyPair": 10,
"InstallCloudAssistant": 10,
"InvokeCommand": 16,
"JoinResourceGroup": 10,
"JoinSecurityGroup": 66,
"LeaveSecurityGroup": 66,
"ModifyAutoSnapshotPolicyEx": 10,
"ModifyBandwidthPackageSpec": 11,
"ModifyCommand": 10,
"ModifyDeploymentSetAttribute": 10,
"ModifyDiskAttribute": 16,
"ModifyDiskChargeType": 13,
"ModifyEipAddressAttribute": 14,
"ModifyImageAttribute": 10,
"ModifyImageSharePermission": 16,
"ModifyInstanceAttribute": 22,
"ModifyInstanceAutoReleaseTime": 15,
"ModifyInstanceAutoRenewAttribute": 16,
"ModifyInstanceChargeType": 22,
"ModifyInstanceDeployment": 10,
"ModifyInstanceNetworkSpec": 36,
"ModifyInstanceSpec": 62,
"ModifyInstanceVncPasswd": 35,
"ModifyInstanceVpcAttribute": 15,
"ModifyLaunchTemplateDefaultVersion": 10,
"ModifyNetworkInterfaceAttribute": 10,
"ModifyPhysicalConnectionAttribute": 10,
"ModifyPrepayInstanceSpec": 13,
"ModifyRouterInterfaceAttribute": 10,
"ModifySecurityGroupAttribute": 10,
"ModifySecurityGroupEgressRule": 10,
"ModifySecurityGroupPolicy": 10,
"ModifySecurityGroupRule": 16,
"ModifySnapshotAttribute": 10,
"ModifyUserBusinessBehavior": 10,
"ModifyVirtualBorderRouterAttribute": 10,
"ModifyVpcAttribute": 10,
"ModifyVRouterAttribute": 10,
"ModifyVSwitchAttribute": 10,
"ReActivateInstances": 10,
"RebootInstance": 27,
"RedeployInstance": 14,
"ReInitDisk": 16,
"ReleaseDedicatedHost": 10,
"ReleaseEipAddress": 16,
"ReleasePublicIpAddress": 10,
"RemoveTags": 10,
"RenewInstance": 19,
"ReplaceSystemDisk": 36,
"ResetDisk": 36,
"ResizeDisk": 11,
"RevokeSecurityGroupEgress": 13,
"RevokeSecurityGroup": 16,
"RunInstances": 86,
"StartInstance": 46,
"StopInstance": 27,
"StopInvocation": 10,
"TerminatePhysicalConnection": 10,
"TerminateVirtualBorderRouter": 10,
"UnassignIpv6Addresses": 10,
"UnassignPrivateIpAddresses": 10,
"UnassociateEipAddress": 16
}
}
`
func getAPIMaxTimeout(product, actionName string) (time.Duration, bool) {
timeout := make(map[string]map[string]int)
err := json.Unmarshal([]byte(apiTimeouts), &timeout)
if err != nil {
return 0 * time.Millisecond, false
}
obj := timeout[strings.ToLower(product)]
if obj != nil && obj[actionName] != 0 {
return time.Duration(obj[actionName]) * time.Second, true
}
return 0 * time.Millisecond, false
}

View File

@ -0,0 +1,18 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package auth
type Credential interface {
}

View File

@ -0,0 +1,34 @@
package credentials
// Deprecated: Use AccessKeyCredential in this package instead.
type BaseCredential struct {
AccessKeyId string
AccessKeySecret string
}
type AccessKeyCredential struct {
AccessKeyId string
AccessKeySecret string
}
// Deprecated: Use NewAccessKeyCredential in this package instead.
func NewBaseCredential(accessKeyId, accessKeySecret string) *BaseCredential {
return &BaseCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
}
}
func (baseCred *BaseCredential) ToAccessKeyCredential() *AccessKeyCredential {
return &AccessKeyCredential{
AccessKeyId: baseCred.AccessKeyId,
AccessKeySecret: baseCred.AccessKeySecret,
}
}
func NewAccessKeyCredential(accessKeyId, accessKeySecret string) *AccessKeyCredential {
return &AccessKeyCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
}
}

View File

@ -0,0 +1,12 @@
package credentials
type BearerTokenCredential struct {
BearerToken string
}
// NewBearerTokenCredential return a BearerTokenCredential object
func NewBearerTokenCredential(token string) *BearerTokenCredential {
return &BearerTokenCredential{
BearerToken: token,
}
}

View File

@ -0,0 +1,29 @@
package credentials
func (oldCred *StsRoleNameOnEcsCredential) ToEcsRamRoleCredential() *EcsRamRoleCredential {
return &EcsRamRoleCredential{
RoleName: oldCred.RoleName,
}
}
type EcsRamRoleCredential struct {
RoleName string
}
func NewEcsRamRoleCredential(roleName string) *EcsRamRoleCredential {
return &EcsRamRoleCredential{
RoleName: roleName,
}
}
// Deprecated: Use EcsRamRoleCredential in this package instead.
type StsRoleNameOnEcsCredential struct {
RoleName string
}
// Deprecated: Use NewEcsRamRoleCredential in this package instead.
func NewStsRoleNameOnEcsCredential(roleName string) *StsRoleNameOnEcsCredential {
return &StsRoleNameOnEcsCredential{
RoleName: roleName,
}
}

View File

@ -0,0 +1,30 @@
package provider
import (
"errors"
"os"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
)
type EnvProvider struct{}
var ProviderEnv = new(EnvProvider)
func NewEnvProvider() Provider {
return &EnvProvider{}
}
func (p *EnvProvider) Resolve() (auth.Credential, error) {
accessKeyID, ok1 := os.LookupEnv(ENVAccessKeyID)
accessKeySecret, ok2 := os.LookupEnv(ENVAccessKeySecret)
if !ok1 || !ok2 {
return nil, nil
}
if accessKeyID == "" || accessKeySecret == "" {
return nil, errors.New("Environmental variable (ALIBABACLOUD_ACCESS_KEY_ID or ALIBABACLOUD_ACCESS_KEY_SECRET) is empty")
}
return credentials.NewAccessKeyCredential(accessKeyID, accessKeySecret), nil
}

View File

@ -0,0 +1,92 @@
package provider
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
var securityCredURL = "http://100.100.100.200/latest/meta-data/ram/security-credentials/"
type InstanceCredentialsProvider struct{}
var ProviderInstance = new(InstanceCredentialsProvider)
var HookGet = func(fn func(string) (int, []byte, error)) func(string) (int, []byte, error) {
return fn
}
func NewInstanceCredentialsProvider() Provider {
return &InstanceCredentialsProvider{}
}
func (p *InstanceCredentialsProvider) Resolve() (auth.Credential, error) {
roleName, ok := os.LookupEnv(ENVEcsMetadata)
if !ok {
return nil, nil
}
if roleName == "" {
return nil, errors.New("Environmental variable 'ALIBABA_CLOUD_ECS_METADATA' are empty")
}
status, content, err := HookGet(get)(securityCredURL + roleName)
if err != nil {
return nil, err
}
if status != 200 {
if status == 404 {
return nil, fmt.Errorf("The role was not found in the instance")
}
return nil, fmt.Errorf("Received %d when getting security credentials for %s", status, roleName)
}
body := make(map[string]interface{})
if err := json.Unmarshal(content, &body); err != nil {
return nil, err
}
accessKeyID, err := extractString(body, "AccessKeyId")
if err != nil {
return nil, err
}
accessKeySecret, err := extractString(body, "AccessKeySecret")
if err != nil {
return nil, err
}
securityToken, err := extractString(body, "SecurityToken")
if err != nil {
return nil, err
}
return credentials.NewStsTokenCredential(accessKeyID, accessKeySecret, securityToken), nil
}
func get(url string) (status int, content []byte, err error) {
httpClient := http.DefaultClient
httpClient.Timeout = 1 * time.Second
resp, err := httpClient.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
content, err = ioutil.ReadAll(resp.Body)
return resp.StatusCode, content, err
}
func extractString(m map[string]interface{}, key string) (string, error) {
raw, ok := m[key]
if !ok {
return "", fmt.Errorf("%s not in map", key)
}
str, ok := raw.(string)
if !ok {
return "", fmt.Errorf("%s is not a string in map", key)
}
return str, nil
}

View File

@ -0,0 +1,159 @@
package provider
import (
"bufio"
"errors"
"os"
"runtime"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
ini "gopkg.in/ini.v1"
)
type ProfileProvider struct {
Profile string
}
var ProviderProfile = NewProfileProvider()
// NewProfileProvider receive zero or more parameters,
// when length of name is 0, the value of field Profile will be "default",
// and when there are multiple inputs, the function will take the
// first one and discard the other values.
func NewProfileProvider(name ...string) Provider {
p := new(ProfileProvider)
if len(name) == 0 {
p.Profile = "default"
} else {
p.Profile = name[0]
}
return p
}
// Resolve implements the Provider interface
// when credential type is rsa_key_pair, the content of private_key file
// must be able to be parsed directly into the required string
// that NewRsaKeyPairCredential function needed
func (p *ProfileProvider) Resolve() (auth.Credential, error) {
path, ok := os.LookupEnv(ENVCredentialFile)
if !ok {
var err error
path, err = checkDefaultPath()
if err != nil {
return nil, err
}
if path == "" {
return nil, nil
}
} else if path == "" {
return nil, errors.New("Environment variable '" + ENVCredentialFile + "' cannot be empty")
}
ini, err := ini.Load(path)
if err != nil {
return nil, errors.New("ERROR: Can not open file" + err.Error())
}
section, err := ini.GetSection(p.Profile)
if err != nil {
return nil, errors.New("ERROR: Can not load section" + err.Error())
}
value, err := section.GetKey("type")
if err != nil {
return nil, errors.New("ERROR: Can not find credential type" + err.Error())
}
switch value.String() {
case "access_key":
value1, err1 := section.GetKey("access_key_id")
value2, err2 := section.GetKey("access_key_secret")
if err1 != nil || err2 != nil {
return nil, errors.New("ERROR: Failed to get value")
}
if value1.String() == "" || value2.String() == "" {
return nil, errors.New("ERROR: Value can't be empty")
}
return credentials.NewAccessKeyCredential(value1.String(), value2.String()), nil
case "ecs_ram_role":
value1, err1 := section.GetKey("role_name")
if err1 != nil {
return nil, errors.New("ERROR: Failed to get value")
}
if value1.String() == "" {
return nil, errors.New("ERROR: Value can't be empty")
}
return credentials.NewEcsRamRoleCredential(value1.String()), nil
case "ram_role_arn":
value1, err1 := section.GetKey("access_key_id")
value2, err2 := section.GetKey("access_key_secret")
value3, err3 := section.GetKey("role_arn")
value4, err4 := section.GetKey("role_session_name")
if err1 != nil || err2 != nil || err3 != nil || err4 != nil {
return nil, errors.New("ERROR: Failed to get value")
}
if value1.String() == "" || value2.String() == "" || value3.String() == "" || value4.String() == "" {
return nil, errors.New("ERROR: Value can't be empty")
}
return credentials.NewRamRoleArnCredential(value1.String(), value2.String(), value3.String(), value4.String(), 3600), nil
case "rsa_key_pair":
value1, err1 := section.GetKey("public_key_id")
value2, err2 := section.GetKey("private_key_file")
if err1 != nil || err2 != nil {
return nil, errors.New("ERROR: Failed to get value")
}
if value1.String() == "" || value2.String() == "" {
return nil, errors.New("ERROR: Value can't be empty")
}
file, err := os.Open(value2.String())
if err != nil {
return nil, errors.New("ERROR: Can not get private_key")
}
defer file.Close()
var privateKey string
scan := bufio.NewScanner(file)
var data string
for scan.Scan() {
if strings.HasPrefix(scan.Text(), "----") {
continue
}
data += scan.Text() + "\n"
}
return credentials.NewRsaKeyPairCredential(privateKey, value1.String(), 3600), nil
default:
return nil, errors.New("ERROR: Failed to get credential")
}
}
// GetHomePath return home directory according to the system.
// if the environmental virables does not exist, will return empty
func GetHomePath() string {
if runtime.GOOS == "windows" {
path, ok := os.LookupEnv("USERPROFILE")
if !ok {
return ""
}
return path
}
path, ok := os.LookupEnv("HOME")
if !ok {
return ""
}
return path
}
func checkDefaultPath() (path string, err error) {
path = GetHomePath()
if path == "" {
return "", errors.New("The default credential file path is invalid")
}
path = strings.Replace("~/.alibabacloud/credentials", "~", path, 1)
_, err = os.Stat(path)
if err != nil {
return "", nil
}
return path, nil
}

View File

@ -0,0 +1,19 @@
package provider
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
)
//Environmental virables that may be used by the provider
const (
ENVAccessKeyID = "ALIBABA_CLOUD_ACCESS_KEY_ID"
ENVAccessKeySecret = "ALIBABA_CLOUD_ACCESS_KEY_SECRET"
ENVCredentialFile = "ALIBABA_CLOUD_CREDENTIALS_FILE"
ENVEcsMetadata = "ALIBABA_CLOUD_ECS_METADATA"
PATHCredentialFile = "~/.alibabacloud/credentials"
)
// When you want to customize the provider, you only need to implement the method of the interface.
type Provider interface {
Resolve() (auth.Credential, error)
}

View File

@ -0,0 +1,34 @@
package provider
import (
"errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
)
type ProviderChain struct {
Providers []Provider
}
var defaultproviders = []Provider{ProviderEnv, ProviderProfile, ProviderInstance}
var DefaultChain = NewProviderChain(defaultproviders)
func NewProviderChain(providers []Provider) Provider {
return &ProviderChain{
Providers: providers,
}
}
func (p *ProviderChain) Resolve() (auth.Credential, error) {
for _, provider := range p.Providers {
creds, err := provider.Resolve()
if err != nil {
return nil, err
} else if err == nil && creds == nil {
continue
}
return creds, err
}
return nil, errors.New("No credential found")
}

View File

@ -0,0 +1,15 @@
package credentials
type RsaKeyPairCredential struct {
PrivateKey string
PublicKeyId string
SessionExpiration int
}
func NewRsaKeyPairCredential(privateKey, publicKeyId string, sessionExpiration int) *RsaKeyPairCredential {
return &RsaKeyPairCredential{
PrivateKey: privateKey,
PublicKeyId: publicKeyId,
SessionExpiration: sessionExpiration,
}
}

View File

@ -0,0 +1,15 @@
package credentials
type StsTokenCredential struct {
AccessKeyId string
AccessKeySecret string
AccessKeyStsToken string
}
func NewStsTokenCredential(accessKeyId, accessKeySecret, accessKeyStsToken string) *StsTokenCredential {
return &StsTokenCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
AccessKeyStsToken: accessKeyStsToken,
}
}

View File

@ -0,0 +1,61 @@
package credentials
// Deprecated: Use RamRoleArnCredential in this package instead.
type StsRoleArnCredential struct {
AccessKeyId string
AccessKeySecret string
RoleArn string
RoleSessionName string
RoleSessionExpiration int
}
type RamRoleArnCredential struct {
AccessKeyId string
AccessKeySecret string
RoleArn string
RoleSessionName string
RoleSessionExpiration int
Policy string
}
// Deprecated: Use RamRoleArnCredential in this package instead.
func NewStsRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *StsRoleArnCredential {
return &StsRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
RoleSessionExpiration: roleSessionExpiration,
}
}
func (oldCred *StsRoleArnCredential) ToRamRoleArnCredential() *RamRoleArnCredential {
return &RamRoleArnCredential{
AccessKeyId: oldCred.AccessKeyId,
AccessKeySecret: oldCred.AccessKeySecret,
RoleArn: oldCred.RoleArn,
RoleSessionName: oldCred.RoleSessionName,
RoleSessionExpiration: oldCred.RoleSessionExpiration,
}
}
func NewRamRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *RamRoleArnCredential {
return &RamRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
RoleSessionExpiration: roleSessionExpiration,
}
}
func NewRamRoleArnWithPolicyCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string, roleSessionExpiration int) *RamRoleArnCredential {
return &RamRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
RoleSessionExpiration: roleSessionExpiration,
Policy: policy,
}
}

View File

@ -0,0 +1,138 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package auth
import (
"bytes"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
var debug utils.Debug
var hookGetDate = func(fn func() string) string {
return fn()
}
func init() {
debug = utils.Init("sdk")
}
func signRoaRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) {
completeROASignParams(request, signer, regionId)
stringToSign := buildRoaStringToSign(request)
request.SetStringToSign(stringToSign)
accessKeyId, err := signer.GetAccessKeyId()
if err != nil {
return err
}
signature := signer.Sign(stringToSign, "")
request.GetHeaders()["Authorization"] = "acs " + accessKeyId + ":" + signature
return
}
func completeROASignParams(request requests.AcsRequest, signer Signer, regionId string) {
headerParams := request.GetHeaders()
// complete query params
queryParams := request.GetQueryParams()
//if _, ok := queryParams["RegionId"]; !ok {
// queryParams["RegionId"] = regionId
//}
if extraParam := signer.GetExtraParam(); extraParam != nil {
for key, value := range extraParam {
if key == "SecurityToken" {
headerParams["x-acs-security-token"] = value
continue
}
if key == "BearerToken" {
headerParams["x-acs-bearer-token"] = value
continue
}
queryParams[key] = value
}
}
// complete header params
headerParams["Date"] = hookGetDate(utils.GetTimeInFormatRFC2616)
headerParams["x-acs-signature-method"] = signer.GetName()
headerParams["x-acs-signature-version"] = signer.GetVersion()
if request.GetFormParams() != nil && len(request.GetFormParams()) > 0 {
formString := utils.GetUrlFormedMap(request.GetFormParams())
request.SetContent([]byte(formString))
if headerParams["Content-Type"] == "" {
headerParams["Content-Type"] = requests.Form
}
}
contentMD5 := utils.GetMD5Base64(request.GetContent())
headerParams["Content-MD5"] = contentMD5
if _, contains := headerParams["Content-Type"]; !contains {
headerParams["Content-Type"] = requests.Raw
}
switch format := request.GetAcceptFormat(); format {
case "JSON":
headerParams["Accept"] = requests.Json
case "XML":
headerParams["Accept"] = requests.Xml
default:
headerParams["Accept"] = requests.Raw
}
}
func buildRoaStringToSign(request requests.AcsRequest) (stringToSign string) {
headers := request.GetHeaders()
stringToSignBuilder := bytes.Buffer{}
stringToSignBuilder.WriteString(request.GetMethod())
stringToSignBuilder.WriteString(requests.HeaderSeparator)
// append header keys for sign
appendIfContain(headers, &stringToSignBuilder, "Accept", requests.HeaderSeparator)
appendIfContain(headers, &stringToSignBuilder, "Content-MD5", requests.HeaderSeparator)
appendIfContain(headers, &stringToSignBuilder, "Content-Type", requests.HeaderSeparator)
appendIfContain(headers, &stringToSignBuilder, "Date", requests.HeaderSeparator)
// sort and append headers witch starts with 'x-acs-'
var acsHeaders []string
for key := range headers {
if strings.HasPrefix(key, "x-acs-") {
acsHeaders = append(acsHeaders, key)
}
}
sort.Strings(acsHeaders)
for _, key := range acsHeaders {
stringToSignBuilder.WriteString(key + ":" + headers[key])
stringToSignBuilder.WriteString(requests.HeaderSeparator)
}
// append query params
stringToSignBuilder.WriteString(request.BuildQueries())
stringToSign = stringToSignBuilder.String()
debug("stringToSign: %s", stringToSign)
return
}
func appendIfContain(sourceMap map[string]string, target *bytes.Buffer, key, separator string) {
if value, contain := sourceMap[key]; contain && len(value) > 0 {
target.WriteString(sourceMap[key])
target.WriteString(separator)
}
}

View File

@ -0,0 +1,94 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package auth
import (
"net/url"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
var hookGetNonce = func(fn func() string) string {
return fn()
}
func signRpcRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) {
err = completeRpcSignParams(request, signer, regionId)
if err != nil {
return
}
// remove while retry
if _, containsSign := request.GetQueryParams()["Signature"]; containsSign {
delete(request.GetQueryParams(), "Signature")
}
stringToSign := buildRpcStringToSign(request)
request.SetStringToSign(stringToSign)
signature := signer.Sign(stringToSign, "&")
request.GetQueryParams()["Signature"] = signature
return
}
func completeRpcSignParams(request requests.AcsRequest, signer Signer, regionId string) (err error) {
queryParams := request.GetQueryParams()
queryParams["Version"] = request.GetVersion()
queryParams["Action"] = request.GetActionName()
queryParams["Format"] = request.GetAcceptFormat()
queryParams["Timestamp"] = hookGetDate(utils.GetTimeInFormatISO8601)
queryParams["SignatureMethod"] = signer.GetName()
queryParams["SignatureType"] = signer.GetType()
queryParams["SignatureVersion"] = signer.GetVersion()
queryParams["SignatureNonce"] = hookGetNonce(utils.GetUUID)
queryParams["AccessKeyId"], err = signer.GetAccessKeyId()
if err != nil {
return
}
if _, contains := queryParams["RegionId"]; !contains {
queryParams["RegionId"] = regionId
}
if extraParam := signer.GetExtraParam(); extraParam != nil {
for key, value := range extraParam {
queryParams[key] = value
}
}
request.GetHeaders()["Content-Type"] = requests.Form
formString := utils.GetUrlFormedMap(request.GetFormParams())
request.SetContent([]byte(formString))
return
}
func buildRpcStringToSign(request requests.AcsRequest) (stringToSign string) {
signParams := make(map[string]string)
for key, value := range request.GetQueryParams() {
signParams[key] = value
}
for key, value := range request.GetFormParams() {
signParams[key] = value
}
stringToSign = utils.GetUrlFormedMap(signParams)
stringToSign = strings.Replace(stringToSign, "+", "%20", -1)
stringToSign = strings.Replace(stringToSign, "*", "%2A", -1)
stringToSign = strings.Replace(stringToSign, "%7E", "~", -1)
stringToSign = url.QueryEscape(stringToSign)
stringToSign = request.GetMethod() + "&%2F&" + stringToSign
return
}

View File

@ -0,0 +1,98 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package auth
import (
"fmt"
"reflect"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
type Signer interface {
GetName() string
GetType() string
GetVersion() string
GetAccessKeyId() (string, error)
GetExtraParam() map[string]string
Sign(stringToSign, secretSuffix string) string
}
func NewSignerWithCredential(credential Credential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer Signer, err error) {
switch instance := credential.(type) {
case *credentials.AccessKeyCredential:
{
signer = signers.NewAccessKeySigner(instance)
}
case *credentials.StsTokenCredential:
{
signer = signers.NewStsTokenSigner(instance)
}
case *credentials.BearerTokenCredential:
{
signer = signers.NewBearerTokenSigner(instance)
}
case *credentials.RamRoleArnCredential:
{
signer, err = signers.NewRamRoleArnSigner(instance, commonApi)
}
case *credentials.RsaKeyPairCredential:
{
signer, err = signers.NewSignerKeyPair(instance, commonApi)
}
case *credentials.EcsRamRoleCredential:
{
signer = signers.NewEcsRamRoleSigner(instance, commonApi)
}
case *credentials.BaseCredential: // deprecated user interface
{
signer = signers.NewAccessKeySigner(instance.ToAccessKeyCredential())
}
case *credentials.StsRoleArnCredential: // deprecated user interface
{
signer, err = signers.NewRamRoleArnSigner(instance.ToRamRoleArnCredential(), commonApi)
}
case *credentials.StsRoleNameOnEcsCredential: // deprecated user interface
{
signer = signers.NewEcsRamRoleSigner(instance.ToEcsRamRoleCredential(), commonApi)
}
default:
message := fmt.Sprintf(errors.UnsupportedCredentialErrorMessage, reflect.TypeOf(credential))
err = errors.NewClientError(errors.UnsupportedCredentialErrorCode, message, nil)
}
return
}
func Sign(request requests.AcsRequest, signer Signer, regionId string) (err error) {
switch request.GetStyle() {
case requests.ROA:
{
err = signRoaRequest(request, signer, regionId)
}
case requests.RPC:
{
err = signRpcRequest(request, signer, regionId)
}
default:
message := fmt.Sprintf(errors.UnknownRequestTypeErrorMessage, reflect.TypeOf(request))
err = errors.NewClientError(errors.UnknownRequestTypeErrorCode, message, nil)
}
return
}

View File

@ -0,0 +1,57 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"crypto"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/base64"
)
func ShaHmac1(source, secret string) string {
key := []byte(secret)
hmac := hmac.New(sha1.New, key)
hmac.Write([]byte(source))
signedBytes := hmac.Sum(nil)
signedString := base64.StdEncoding.EncodeToString(signedBytes)
return signedString
}
func Sha256WithRsa(source, secret string) string {
// block, _ := pem.Decode([]byte(secret))
decodeString, err := base64.StdEncoding.DecodeString(secret)
if err != nil {
panic(err)
}
private, err := x509.ParsePKCS8PrivateKey(decodeString)
if err != nil {
panic(err)
}
h := crypto.Hash.New(crypto.SHA256)
h.Write([]byte(source))
hashed := h.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey),
crypto.SHA256, hashed)
if err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(signature)
}

View File

@ -0,0 +1,54 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
const defaultInAdvanceScale = 0.95
type credentialUpdater struct {
credentialExpiration int
lastUpdateTimestamp int64
inAdvanceScale float64
buildRequestMethod func() (*requests.CommonRequest, error)
responseCallBack func(response *responses.CommonResponse) error
refreshApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error)
}
func (updater *credentialUpdater) needUpdateCredential() (result bool) {
if updater.inAdvanceScale == 0 {
updater.inAdvanceScale = defaultInAdvanceScale
}
return time.Now().Unix()-updater.lastUpdateTimestamp >= int64(float64(updater.credentialExpiration)*updater.inAdvanceScale)
}
func (updater *credentialUpdater) updateCredential() (err error) {
request, err := updater.buildRequestMethod()
if err != nil {
return
}
response, err := updater.refreshApi(request)
if err != nil {
return
}
updater.lastUpdateTimestamp = time.Now().Unix()
err = updater.responseCallBack(response)
return
}

View File

@ -0,0 +1,7 @@
package signers
type SessionCredential struct {
AccessKeyId string
AccessKeySecret string
StsToken string
}

View File

@ -0,0 +1,54 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
type AccessKeySigner struct {
credential *credentials.AccessKeyCredential
}
func (signer *AccessKeySigner) GetExtraParam() map[string]string {
return nil
}
func NewAccessKeySigner(credential *credentials.AccessKeyCredential) *AccessKeySigner {
return &AccessKeySigner{
credential: credential,
}
}
func (*AccessKeySigner) GetName() string {
return "HMAC-SHA1"
}
func (*AccessKeySigner) GetType() string {
return ""
}
func (*AccessKeySigner) GetVersion() string {
return "1.0"
}
func (signer *AccessKeySigner) GetAccessKeyId() (accessKeyId string, err error) {
return signer.credential.AccessKeyId, nil
}
func (signer *AccessKeySigner) Sign(stringToSign, secretSuffix string) string {
secret := signer.credential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}

View File

@ -0,0 +1,35 @@
package signers
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
type BearerTokenSigner struct {
credential *credentials.BearerTokenCredential
}
func NewBearerTokenSigner(credential *credentials.BearerTokenCredential) *BearerTokenSigner {
return &BearerTokenSigner{
credential: credential,
}
}
func (signer *BearerTokenSigner) GetExtraParam() map[string]string {
return map[string]string{"BearerToken": signer.credential.BearerToken}
}
func (*BearerTokenSigner) GetName() string {
return ""
}
func (*BearerTokenSigner) GetType() string {
return "BEARERTOKEN"
}
func (*BearerTokenSigner) GetVersion() string {
return "1.0"
}
func (signer *BearerTokenSigner) GetAccessKeyId() (accessKeyId string, err error) {
return "", nil
}
func (signer *BearerTokenSigner) Sign(stringToSign, secretSuffix string) string {
return ""
}

View File

@ -0,0 +1,167 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
jmespath "github.com/jmespath/go-jmespath"
)
var securityCredURL = "http://100.100.100.200/latest/meta-data/ram/security-credentials/"
type EcsRamRoleSigner struct {
*credentialUpdater
sessionCredential *SessionCredential
credential *credentials.EcsRamRoleCredential
commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)
}
func NewEcsRamRoleSigner(credential *credentials.EcsRamRoleCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *EcsRamRoleSigner) {
signer = &EcsRamRoleSigner{
credential: credential,
commonApi: commonApi,
}
signer.credentialUpdater = &credentialUpdater{
credentialExpiration: defaultDurationSeconds / 60,
buildRequestMethod: signer.buildCommonRequest,
responseCallBack: signer.refreshCredential,
refreshApi: signer.refreshApi,
}
return signer
}
func (*EcsRamRoleSigner) GetName() string {
return "HMAC-SHA1"
}
func (*EcsRamRoleSigner) GetType() string {
return ""
}
func (*EcsRamRoleSigner) GetVersion() string {
return "1.0"
}
func (signer *EcsRamRoleSigner) GetAccessKeyId() (accessKeyId string, err error) {
if signer.sessionCredential == nil || signer.needUpdateCredential() {
err = signer.updateCredential()
if err != nil {
return
}
}
if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 {
return "", nil
}
return signer.sessionCredential.AccessKeyId, nil
}
func (signer *EcsRamRoleSigner) GetExtraParam() map[string]string {
if signer.sessionCredential == nil {
return make(map[string]string)
}
if len(signer.sessionCredential.StsToken) <= 0 {
return make(map[string]string)
}
return map[string]string{"SecurityToken": signer.sessionCredential.StsToken}
}
func (signer *EcsRamRoleSigner) Sign(stringToSign, secretSuffix string) string {
secret := signer.sessionCredential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}
func (signer *EcsRamRoleSigner) buildCommonRequest() (request *requests.CommonRequest, err error) {
return
}
func (signer *EcsRamRoleSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
requestUrl := securityCredURL + signer.credential.RoleName
httpRequest, err := http.NewRequest(requests.GET, requestUrl, strings.NewReader(""))
if err != nil {
err = fmt.Errorf("refresh Ecs sts token err: %s", err.Error())
return
}
httpClient := &http.Client{}
httpResponse, err := httpClient.Do(httpRequest)
if err != nil {
err = fmt.Errorf("refresh Ecs sts token err: %s", err.Error())
return
}
response = responses.NewCommonResponse()
err = responses.Unmarshal(response, httpResponse, "")
return
}
func (signer *EcsRamRoleSigner) refreshCredential(response *responses.CommonResponse) (err error) {
if response.GetHttpStatus() != http.StatusOK {
return fmt.Errorf("refresh Ecs sts token err, httpStatus: %d, message = %s", response.GetHttpStatus(), response.GetHttpContentString())
}
var data interface{}
err = json.Unmarshal(response.GetHttpContentBytes(), &data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, json.Unmarshal fail: %s", err.Error())
}
code, err := jmespath.Search("Code", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get Code: %s", err.Error())
}
if code.(string) != "Success" {
return fmt.Errorf("refresh Ecs sts token err, Code is not Success")
}
accessKeyId, err := jmespath.Search("AccessKeyId", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get AccessKeyId: %s", err.Error())
}
accessKeySecret, err := jmespath.Search("AccessKeySecret", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get AccessKeySecret: %s", err.Error())
}
securityToken, err := jmespath.Search("SecurityToken", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get SecurityToken: %s", err.Error())
}
expiration, err := jmespath.Search("Expiration", data)
if err != nil {
return fmt.Errorf("refresh Ecs sts token err, fail to get Expiration: %s", err.Error())
}
if accessKeyId == nil || accessKeySecret == nil || securityToken == nil || expiration == nil {
return
}
expirationTime, err := time.Parse("2006-01-02T15:04:05Z", expiration.(string))
signer.credentialExpiration = int(expirationTime.Unix() - time.Now().Unix())
signer.sessionCredential = &SessionCredential{
AccessKeyId: accessKeyId.(string),
AccessKeySecret: accessKeySecret.(string),
StsToken: securityToken.(string),
}
return
}
func (signer *EcsRamRoleSigner) GetSessionCredential() *SessionCredential {
return signer.sessionCredential
}

View File

@ -0,0 +1,148 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
jmespath "github.com/jmespath/go-jmespath"
)
type SignerKeyPair struct {
*credentialUpdater
sessionCredential *SessionCredential
credential *credentials.RsaKeyPairCredential
commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)
}
func NewSignerKeyPair(credential *credentials.RsaKeyPairCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *SignerKeyPair, err error) {
signer = &SignerKeyPair{
credential: credential,
commonApi: commonApi,
}
signer.credentialUpdater = &credentialUpdater{
credentialExpiration: credential.SessionExpiration,
buildRequestMethod: signer.buildCommonRequest,
responseCallBack: signer.refreshCredential,
refreshApi: signer.refreshApi,
}
if credential.SessionExpiration > 0 {
if credential.SessionExpiration >= 900 && credential.SessionExpiration <= 3600 {
signer.credentialExpiration = credential.SessionExpiration
} else {
err = errors.NewClientError(errors.InvalidParamErrorCode, "Key Pair session duration should be in the range of 15min - 1Hr", nil)
}
} else {
signer.credentialExpiration = defaultDurationSeconds
}
return
}
func (*SignerKeyPair) GetName() string {
return "HMAC-SHA1"
}
func (*SignerKeyPair) GetType() string {
return ""
}
func (*SignerKeyPair) GetVersion() string {
return "1.0"
}
func (signer *SignerKeyPair) ensureCredential() error {
if signer.sessionCredential == nil || signer.needUpdateCredential() {
return signer.updateCredential()
}
return nil
}
func (signer *SignerKeyPair) GetAccessKeyId() (accessKeyId string, err error) {
err = signer.ensureCredential()
if err != nil {
return
}
if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 {
accessKeyId = ""
return
}
accessKeyId = signer.sessionCredential.AccessKeyId
return
}
func (signer *SignerKeyPair) GetExtraParam() map[string]string {
return make(map[string]string)
}
func (signer *SignerKeyPair) Sign(stringToSign, secretSuffix string) string {
secret := signer.sessionCredential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}
func (signer *SignerKeyPair) buildCommonRequest() (request *requests.CommonRequest, err error) {
request = requests.NewCommonRequest()
request.Product = "Sts"
request.Version = "2015-04-01"
request.ApiName = "GenerateSessionAccessKey"
request.Scheme = requests.HTTPS
request.SetDomain("sts.ap-northeast-1.aliyuncs.com")
request.QueryParams["PublicKeyId"] = signer.credential.PublicKeyId
request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration)
return
}
func (signer *SignerKeyPair) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
signerV2 := NewSignerV2(signer.credential)
return signer.commonApi(request, signerV2)
}
func (signer *SignerKeyPair) refreshCredential(response *responses.CommonResponse) (err error) {
if response.GetHttpStatus() != http.StatusOK {
message := "refresh session AccessKey failed"
err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message)
return
}
var data interface{}
err = json.Unmarshal(response.GetHttpContentBytes(), &data)
if err != nil {
return fmt.Errorf("refresh KeyPair err, json.Unmarshal fail: %s", err.Error())
}
accessKeyId, err := jmespath.Search("SessionAccessKey.SessionAccessKeyId", data)
if err != nil {
return fmt.Errorf("refresh KeyPair err, fail to get SessionAccessKeyId: %s", err.Error())
}
accessKeySecret, err := jmespath.Search("SessionAccessKey.SessionAccessKeySecret", data)
if err != nil {
return fmt.Errorf("refresh KeyPair err, fail to get SessionAccessKeySecret: %s", err.Error())
}
if accessKeyId == nil || accessKeySecret == nil {
return
}
signer.sessionCredential = &SessionCredential{
AccessKeyId: accessKeyId.(string),
AccessKeySecret: accessKeySecret.(string),
}
return
}

View File

@ -0,0 +1,175 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
jmespath "github.com/jmespath/go-jmespath"
)
const (
defaultDurationSeconds = 3600
)
type RamRoleArnSigner struct {
*credentialUpdater
roleSessionName string
sessionCredential *SessionCredential
credential *credentials.RamRoleArnCredential
commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)
}
func NewRamRoleArnSigner(credential *credentials.RamRoleArnCredential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer *RamRoleArnSigner, err error) {
signer = &RamRoleArnSigner{
credential: credential,
commonApi: commonApi,
}
signer.credentialUpdater = &credentialUpdater{
credentialExpiration: credential.RoleSessionExpiration,
buildRequestMethod: signer.buildCommonRequest,
responseCallBack: signer.refreshCredential,
refreshApi: signer.refreshApi,
}
if len(credential.RoleSessionName) > 0 {
signer.roleSessionName = credential.RoleSessionName
} else {
signer.roleSessionName = "aliyun-go-sdk-" + strconv.FormatInt(time.Now().UnixNano()/1000, 10)
}
if credential.RoleSessionExpiration > 0 {
if credential.RoleSessionExpiration >= 900 && credential.RoleSessionExpiration <= 3600 {
signer.credentialExpiration = credential.RoleSessionExpiration
} else {
err = errors.NewClientError(errors.InvalidParamErrorCode, "Assume Role session duration should be in the range of 15min - 1Hr", nil)
}
} else {
signer.credentialExpiration = defaultDurationSeconds
}
return
}
func (*RamRoleArnSigner) GetName() string {
return "HMAC-SHA1"
}
func (*RamRoleArnSigner) GetType() string {
return ""
}
func (*RamRoleArnSigner) GetVersion() string {
return "1.0"
}
func (signer *RamRoleArnSigner) GetAccessKeyId() (accessKeyId string, err error) {
if signer.sessionCredential == nil || signer.needUpdateCredential() {
err = signer.updateCredential()
if err != nil {
return
}
}
if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 {
return "", err
}
return signer.sessionCredential.AccessKeyId, nil
}
func (signer *RamRoleArnSigner) GetExtraParam() map[string]string {
if signer.sessionCredential == nil || signer.needUpdateCredential() {
signer.updateCredential()
}
if signer.sessionCredential == nil || len(signer.sessionCredential.StsToken) <= 0 {
return make(map[string]string)
}
return map[string]string{"SecurityToken": signer.sessionCredential.StsToken}
}
func (signer *RamRoleArnSigner) Sign(stringToSign, secretSuffix string) string {
secret := signer.sessionCredential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}
func (signer *RamRoleArnSigner) buildCommonRequest() (request *requests.CommonRequest, err error) {
request = requests.NewCommonRequest()
request.Product = "Sts"
request.Version = "2015-04-01"
request.ApiName = "AssumeRole"
request.Scheme = requests.HTTPS
request.QueryParams["RoleArn"] = signer.credential.RoleArn
if signer.credential.Policy != "" {
request.QueryParams["Policy"] = signer.credential.Policy
}
request.QueryParams["RoleSessionName"] = signer.credential.RoleSessionName
request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration)
return
}
func (signer *RamRoleArnSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
credential := &credentials.AccessKeyCredential{
AccessKeyId: signer.credential.AccessKeyId,
AccessKeySecret: signer.credential.AccessKeySecret,
}
signerV1 := NewAccessKeySigner(credential)
return signer.commonApi(request, signerV1)
}
func (signer *RamRoleArnSigner) refreshCredential(response *responses.CommonResponse) (err error) {
if response.GetHttpStatus() != http.StatusOK {
message := "refresh session token failed"
err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message)
return
}
var data interface{}
err = json.Unmarshal(response.GetHttpContentBytes(), &data)
if err != nil {
return fmt.Errorf("refresh RoleArn sts token err, json.Unmarshal fail: %s", err.Error())
}
accessKeyId, err := jmespath.Search("Credentials.AccessKeyId", data)
if err != nil {
return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeyId: %s", err.Error())
}
accessKeySecret, err := jmespath.Search("Credentials.AccessKeySecret", data)
if err != nil {
return fmt.Errorf("refresh RoleArn sts token err, fail to get AccessKeySecret: %s", err.Error())
}
securityToken, err := jmespath.Search("Credentials.SecurityToken", data)
if err != nil {
return fmt.Errorf("refresh RoleArn sts token err, fail to get SecurityToken: %s", err.Error())
}
if accessKeyId == nil || accessKeySecret == nil || securityToken == nil {
return
}
signer.sessionCredential = &SessionCredential{
AccessKeyId: accessKeyId.(string),
AccessKeySecret: accessKeySecret.(string),
StsToken: securityToken.(string),
}
return
}
func (signer *RamRoleArnSigner) GetSessionCredential() *SessionCredential {
return signer.sessionCredential
}

View File

@ -0,0 +1,54 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
type StsTokenSigner struct {
credential *credentials.StsTokenCredential
}
func NewStsTokenSigner(credential *credentials.StsTokenCredential) *StsTokenSigner {
return &StsTokenSigner{
credential: credential,
}
}
func (*StsTokenSigner) GetName() string {
return "HMAC-SHA1"
}
func (*StsTokenSigner) GetType() string {
return ""
}
func (*StsTokenSigner) GetVersion() string {
return "1.0"
}
func (signer *StsTokenSigner) GetAccessKeyId() (accessKeyId string, err error) {
return signer.credential.AccessKeyId, nil
}
func (signer *StsTokenSigner) GetExtraParam() map[string]string {
return map[string]string{"SecurityToken": signer.credential.AccessKeyStsToken}
}
func (signer *StsTokenSigner) Sign(stringToSign, secretSuffix string) string {
secret := signer.credential.AccessKeySecret + secretSuffix
return ShaHmac1(stringToSign, secret)
}

View File

@ -0,0 +1,54 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package signers
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
type SignerV2 struct {
credential *credentials.RsaKeyPairCredential
}
func (signer *SignerV2) GetExtraParam() map[string]string {
return nil
}
func NewSignerV2(credential *credentials.RsaKeyPairCredential) *SignerV2 {
return &SignerV2{
credential: credential,
}
}
func (*SignerV2) GetName() string {
return "SHA256withRSA"
}
func (*SignerV2) GetType() string {
return "PRIVATEKEY"
}
func (*SignerV2) GetVersion() string {
return "1.0"
}
func (signer *SignerV2) GetAccessKeyId() (accessKeyId string, err error) {
return signer.credential.PublicKeyId, err
}
func (signer *SignerV2) Sign(stringToSign, secretSuffix string) string {
secret := signer.credential.PrivateKey
return Sha256WithRsa(stringToSign, secret)
}

View File

@ -0,0 +1,807 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sdk
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
var debug utils.Debug
func init() {
debug = utils.Init("sdk")
}
// Version this value will be replaced while build: -ldflags="-X sdk.version=x.x.x"
var Version = "0.0.1"
var defaultConnectTimeout = 5 * time.Second
var defaultReadTimeout = 10 * time.Second
var DefaultUserAgent = fmt.Sprintf("AlibabaCloud (%s; %s) Golang/%s Core/%s", runtime.GOOS, runtime.GOARCH, strings.Trim(runtime.Version(), "go"), Version)
var hookDo = func(fn func(req *http.Request) (*http.Response, error)) func(req *http.Request) (*http.Response, error) {
return fn
}
// Client the type Client
type Client struct {
isInsecure bool
regionId string
config *Config
httpProxy string
httpsProxy string
noProxy string
logger *Logger
userAgent map[string]string
signer auth.Signer
httpClient *http.Client
asyncTaskQueue chan func()
readTimeout time.Duration
connectTimeout time.Duration
EndpointMap map[string]string
EndpointType string
Network string
Domain string
debug bool
isRunning bool
// void "panic(write to close channel)" cause of addAsync() after Shutdown()
asyncChanLock *sync.RWMutex
}
func (client *Client) Init() (err error) {
panic("not support yet")
}
func (client *Client) SetEndpointRules(endpointMap map[string]string, endpointType string, netWork string) {
client.EndpointMap = endpointMap
client.Network = netWork
client.EndpointType = endpointType
}
func (client *Client) SetHTTPSInsecure(isInsecure bool) {
client.isInsecure = isInsecure
}
func (client *Client) GetHTTPSInsecure() bool {
return client.isInsecure
}
func (client *Client) SetHttpsProxy(httpsProxy string) {
client.httpsProxy = httpsProxy
}
func (client *Client) GetHttpsProxy() string {
return client.httpsProxy
}
func (client *Client) SetHttpProxy(httpProxy string) {
client.httpProxy = httpProxy
}
func (client *Client) GetHttpProxy() string {
return client.httpProxy
}
func (client *Client) SetNoProxy(noProxy string) {
client.noProxy = noProxy
}
func (client *Client) GetNoProxy() string {
return client.noProxy
}
func (client *Client) SetTransport(transport http.RoundTripper) {
if client.httpClient == nil {
client.httpClient = &http.Client{}
}
client.httpClient.Transport = transport
}
// InitWithProviderChain will get credential from the providerChain,
// the RsaKeyPairCredential Only applicable to regionID `ap-northeast-1`,
// if your providerChain may return a credential type with RsaKeyPairCredential,
// please ensure your regionID is `ap-northeast-1`.
func (client *Client) InitWithProviderChain(regionId string, provider provider.Provider) (err error) {
config := client.InitClientConfig()
credential, err := provider.Resolve()
if err != nil {
return
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithOptions(regionId string, config *Config, credential auth.Credential) (err error) {
client.isRunning = true
client.asyncChanLock = new(sync.RWMutex)
client.regionId = regionId
client.config = config
client.httpClient = &http.Client{}
if config.Transport != nil {
client.httpClient.Transport = config.Transport
} else if config.HttpTransport != nil {
client.httpClient.Transport = config.HttpTransport
}
if config.Timeout > 0 {
client.httpClient.Timeout = config.Timeout
}
if config.EnableAsync {
client.EnableAsync(config.GoRoutinePoolSize, config.MaxTaskQueueSize)
}
client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner)
return
}
func (client *Client) SetReadTimeout(readTimeout time.Duration) {
client.readTimeout = readTimeout
}
func (client *Client) SetConnectTimeout(connectTimeout time.Duration) {
client.connectTimeout = connectTimeout
}
func (client *Client) GetReadTimeout() time.Duration {
return client.readTimeout
}
func (client *Client) GetConnectTimeout() time.Duration {
return client.connectTimeout
}
func (client *Client) getHttpProxy(scheme string) (proxy *url.URL, err error) {
if scheme == "https" {
if client.GetHttpsProxy() != "" {
proxy, err = url.Parse(client.httpsProxy)
} else if rawurl := os.Getenv("HTTPS_PROXY"); rawurl != "" {
proxy, err = url.Parse(rawurl)
} else if rawurl := os.Getenv("https_proxy"); rawurl != "" {
proxy, err = url.Parse(rawurl)
}
} else {
if client.GetHttpProxy() != "" {
proxy, err = url.Parse(client.httpProxy)
} else if rawurl := os.Getenv("HTTP_PROXY"); rawurl != "" {
proxy, err = url.Parse(rawurl)
} else if rawurl := os.Getenv("http_proxy"); rawurl != "" {
proxy, err = url.Parse(rawurl)
}
}
return proxy, err
}
func (client *Client) getNoProxy(scheme string) []string {
var urls []string
if client.GetNoProxy() != "" {
urls = strings.Split(client.noProxy, ",")
} else if rawurl := os.Getenv("NO_PROXY"); rawurl != "" {
urls = strings.Split(rawurl, ",")
} else if rawurl := os.Getenv("no_proxy"); rawurl != "" {
urls = strings.Split(rawurl, ",")
}
return urls
}
// EnableAsync enable the async task queue
func (client *Client) EnableAsync(routinePoolSize, maxTaskQueueSize int) {
client.asyncTaskQueue = make(chan func(), maxTaskQueueSize)
for i := 0; i < routinePoolSize; i++ {
go func() {
for client.isRunning {
select {
case task, notClosed := <-client.asyncTaskQueue:
if notClosed {
task()
}
}
}
}()
}
}
func (client *Client) InitWithAccessKey(regionId, accessKeyId, accessKeySecret string) (err error) {
config := client.InitClientConfig()
credential := &credentials.BaseCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithStsToken(regionId, accessKeyId, accessKeySecret, securityToken string) (err error) {
config := client.InitClientConfig()
credential := &credentials.StsTokenCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
AccessKeyStsToken: securityToken,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (err error) {
config := client.InitClientConfig()
credential := &credentials.RamRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (err error) {
config := client.InitClientConfig()
credential := &credentials.RamRoleArnCredential{
AccessKeyId: accessKeyId,
AccessKeySecret: accessKeySecret,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
Policy: policy,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithRsaKeyPair(regionId, publicKeyId, privateKey string, sessionExpiration int) (err error) {
config := client.InitClientConfig()
credential := &credentials.RsaKeyPairCredential{
PrivateKey: privateKey,
PublicKeyId: publicKeyId,
SessionExpiration: sessionExpiration,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithEcsRamRole(regionId, roleName string) (err error) {
config := client.InitClientConfig()
credential := &credentials.EcsRamRoleCredential{
RoleName: roleName,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitWithBearerToken(regionId, bearerToken string) (err error) {
config := client.InitClientConfig()
credential := &credentials.BearerTokenCredential{
BearerToken: bearerToken,
}
return client.InitWithOptions(regionId, config, credential)
}
func (client *Client) InitClientConfig() (config *Config) {
if client.config != nil {
return client.config
} else {
return NewConfig()
}
}
func (client *Client) DoAction(request requests.AcsRequest, response responses.AcsResponse) (err error) {
return client.DoActionWithSigner(request, response, nil)
}
func (client *Client) GetEndpointRules(regionId string, product string) (endpointRaw string, err error) {
if client.EndpointType == "regional" {
if regionId == "" {
err = fmt.Errorf("RegionId is empty, please set a valid RegionId.")
return "", err
}
endpointRaw = strings.Replace("<product><network>.<region_id>.aliyuncs.com", "<region_id>", regionId, 1)
} else {
endpointRaw = "<product><network>.aliyuncs.com"
}
endpointRaw = strings.Replace(endpointRaw, "<product>", strings.ToLower(product), 1)
if client.Network == "" || client.Network == "public" {
endpointRaw = strings.Replace(endpointRaw, "<network>", "", 1)
} else {
endpointRaw = strings.Replace(endpointRaw, "<network>", "-"+client.Network, 1)
}
return endpointRaw, nil
}
func (client *Client) buildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (httpRequest *http.Request, err error) {
// add clientVersion
request.GetHeaders()["x-sdk-core-version"] = Version
regionId := client.regionId
if len(request.GetRegionId()) > 0 {
regionId = request.GetRegionId()
}
// resolve endpoint
endpoint := request.GetDomain()
if endpoint == "" && client.Domain != "" {
endpoint = client.Domain
}
if endpoint == "" {
endpoint = endpoints.GetEndpointFromMap(regionId, request.GetProduct())
}
if endpoint == "" && client.EndpointType != "" && request.GetProduct() != "Sts" {
if client.EndpointMap != nil && client.Network == "" || client.Network == "public" {
endpoint = client.EndpointMap[regionId]
}
if endpoint == "" {
endpoint, err = client.GetEndpointRules(regionId, request.GetProduct())
if err != nil {
return
}
}
}
if endpoint == "" {
resolveParam := &endpoints.ResolveParam{
Domain: request.GetDomain(),
Product: request.GetProduct(),
RegionId: regionId,
LocationProduct: request.GetLocationServiceCode(),
LocationEndpointType: request.GetLocationEndpointType(),
CommonApi: client.ProcessCommonRequest,
}
endpoint, err = endpoints.Resolve(resolveParam)
if err != nil {
return
}
}
request.SetDomain(endpoint)
if request.GetScheme() == "" {
request.SetScheme(client.config.Scheme)
}
// init request params
err = requests.InitParams(request)
if err != nil {
return
}
// signature
var finalSigner auth.Signer
if signer != nil {
finalSigner = signer
} else {
finalSigner = client.signer
}
httpRequest, err = buildHttpRequest(request, finalSigner, regionId)
if err == nil {
userAgent := DefaultUserAgent + getSendUserAgent(client.config.UserAgent, client.userAgent, request.GetUserAgent())
httpRequest.Header.Set("User-Agent", userAgent)
}
return
}
func getSendUserAgent(configUserAgent string, clientUserAgent, requestUserAgent map[string]string) string {
realUserAgent := ""
for key1, value1 := range clientUserAgent {
for key2, _ := range requestUserAgent {
if key1 == key2 {
key1 = ""
}
}
if key1 != "" {
realUserAgent += fmt.Sprintf(" %s/%s", key1, value1)
}
}
for key, value := range requestUserAgent {
realUserAgent += fmt.Sprintf(" %s/%s", key, value)
}
if configUserAgent != "" {
return realUserAgent + fmt.Sprintf(" Extra/%s", configUserAgent)
}
return realUserAgent
}
func (client *Client) AppendUserAgent(key, value string) {
newkey := true
if client.userAgent == nil {
client.userAgent = make(map[string]string)
}
if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" {
for tag, _ := range client.userAgent {
if tag == key {
client.userAgent[tag] = value
newkey = false
}
}
if newkey {
client.userAgent[key] = value
}
}
}
func (client *Client) BuildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (err error) {
_, err = client.buildRequestWithSigner(request, signer)
return
}
func (client *Client) getTimeout(request requests.AcsRequest) (time.Duration, time.Duration) {
readTimeout := defaultReadTimeout
connectTimeout := defaultConnectTimeout
reqReadTimeout := request.GetReadTimeout()
reqConnectTimeout := request.GetConnectTimeout()
if reqReadTimeout != 0*time.Millisecond {
readTimeout = reqReadTimeout
} else if client.readTimeout != 0*time.Millisecond {
readTimeout = client.readTimeout
} else if client.httpClient.Timeout != 0 {
readTimeout = client.httpClient.Timeout
} else if timeout, ok := getAPIMaxTimeout(request.GetProduct(), request.GetActionName()); ok {
readTimeout = timeout
}
if reqConnectTimeout != 0*time.Millisecond {
connectTimeout = reqConnectTimeout
} else if client.connectTimeout != 0*time.Millisecond {
connectTimeout = client.connectTimeout
}
return readTimeout, connectTimeout
}
func Timeout(connectTimeout time.Duration) func(cxt context.Context, net, addr string) (c net.Conn, err error) {
return func(ctx context.Context, network, address string) (net.Conn, error) {
return (&net.Dialer{
Timeout: connectTimeout,
DualStack: true,
}).DialContext(ctx, network, address)
}
}
func (client *Client) setTimeout(request requests.AcsRequest) {
readTimeout, connectTimeout := client.getTimeout(request)
client.httpClient.Timeout = readTimeout
if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
trans.DialContext = Timeout(connectTimeout)
client.httpClient.Transport = trans
} else if client.httpClient.Transport == nil {
client.httpClient.Transport = &http.Transport{
DialContext: Timeout(connectTimeout),
}
}
}
func (client *Client) getHTTPSInsecure(request requests.AcsRequest) (insecure bool) {
if request.GetHTTPSInsecure() != nil {
insecure = *request.GetHTTPSInsecure()
} else {
insecure = client.GetHTTPSInsecure()
}
return insecure
}
func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) {
fieldMap := make(map[string]string)
initLogMsg(fieldMap)
defer func() {
client.printLog(fieldMap, err)
}()
httpRequest, err := client.buildRequestWithSigner(request, signer)
if err != nil {
return
}
client.setTimeout(request)
proxy, err := client.getHttpProxy(httpRequest.URL.Scheme)
if err != nil {
return err
}
noProxy := client.getNoProxy(httpRequest.URL.Scheme)
var flag bool
for _, value := range noProxy {
if value == httpRequest.Host {
flag = true
break
}
}
// Set whether to ignore certificate validation.
// Default InsecureSkipVerify is false.
if trans, ok := client.httpClient.Transport.(*http.Transport); ok && trans != nil {
if trans.TLSClientConfig != nil {
trans.TLSClientConfig.InsecureSkipVerify = client.getHTTPSInsecure(request)
} else {
trans.TLSClientConfig = &tls.Config{
InsecureSkipVerify: client.getHTTPSInsecure(request),
}
}
if proxy != nil && !flag {
trans.Proxy = http.ProxyURL(proxy)
}
client.httpClient.Transport = trans
}
var httpResponse *http.Response
for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ {
if proxy != nil && proxy.User != nil {
if password, passwordSet := proxy.User.Password(); passwordSet {
httpRequest.SetBasicAuth(proxy.User.Username(), password)
}
}
if retryTimes > 0 {
client.printLog(fieldMap, err)
initLogMsg(fieldMap)
}
putMsgToMap(fieldMap, httpRequest)
debug("> %s %s %s", httpRequest.Method, httpRequest.URL.RequestURI(), httpRequest.Proto)
debug("> Host: %s", httpRequest.Host)
for key, value := range httpRequest.Header {
debug("> %s: %v", key, strings.Join(value, ""))
}
debug(">")
debug(" Retry Times: %d.", retryTimes)
startTime := time.Now()
fieldMap["{start_time}"] = startTime.Format("2006-01-02 15:04:05")
httpResponse, err = hookDo(client.httpClient.Do)(httpRequest)
fieldMap["{cost}"] = time.Now().Sub(startTime).String()
if err == nil {
fieldMap["{code}"] = strconv.Itoa(httpResponse.StatusCode)
fieldMap["{res_headers}"] = TransToString(httpResponse.Header)
debug("< %s %s", httpResponse.Proto, httpResponse.Status)
for key, value := range httpResponse.Header {
debug("< %s: %v", key, strings.Join(value, ""))
}
}
debug("<")
// receive error
if err != nil {
debug(" Error: %s.", err.Error())
if !client.config.AutoRetry {
return
} else if retryTimes >= client.config.MaxRetryTime {
// timeout but reached the max retry times, return
times := strconv.Itoa(retryTimes + 1)
timeoutErrorMsg := fmt.Sprintf(errors.TimeoutErrorMessage, times, times)
if strings.Contains(err.Error(), "Client.Timeout") {
timeoutErrorMsg += " Read timeout. Please set a valid ReadTimeout."
} else {
timeoutErrorMsg += " Connect timeout. Please set a valid ConnectTimeout."
}
err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err)
return
}
}
if isCertificateError(err) {
return
}
// if status code >= 500 or timeout, will trigger retry
if client.config.AutoRetry && (err != nil || isServerError(httpResponse)) {
client.setTimeout(request)
// rewrite signatureNonce and signature
httpRequest, err = client.buildRequestWithSigner(request, signer)
// buildHttpRequest(request, finalSigner, regionId)
if err != nil {
return
}
continue
}
break
}
err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat())
fieldMap["{res_body}"] = response.GetHttpContentString()
debug("%s", response.GetHttpContentString())
// wrap server errors
if serverErr, ok := err.(*errors.ServerError); ok {
var wrapInfo = map[string]string{}
wrapInfo["StringToSign"] = request.GetStringToSign()
err = errors.WrapServerError(serverErr, wrapInfo)
}
return
}
func isCertificateError(err error) bool {
if err != nil && strings.Contains(err.Error(), "x509: certificate signed by unknown authority") {
return true
}
return false
}
func putMsgToMap(fieldMap map[string]string, request *http.Request) {
fieldMap["{host}"] = request.Host
fieldMap["{method}"] = request.Method
fieldMap["{uri}"] = request.URL.RequestURI()
fieldMap["{pid}"] = strconv.Itoa(os.Getpid())
fieldMap["{version}"] = strings.Split(request.Proto, "/")[1]
hostname, _ := os.Hostname()
fieldMap["{hostname}"] = hostname
fieldMap["{req_headers}"] = TransToString(request.Header)
fieldMap["{target}"] = request.URL.Path + request.URL.RawQuery
}
func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) {
err = auth.Sign(request, singer, regionId)
if err != nil {
return
}
requestMethod := request.GetMethod()
requestUrl := request.BuildUrl()
body := request.GetBodyReader()
httpRequest, err = http.NewRequest(requestMethod, requestUrl, body)
if err != nil {
return
}
for key, value := range request.GetHeaders() {
httpRequest.Header[key] = []string{value}
}
// host is a special case
if host, containsHost := request.GetHeaders()["Host"]; containsHost {
httpRequest.Host = host
}
return
}
func isServerError(httpResponse *http.Response) bool {
return httpResponse.StatusCode >= http.StatusInternalServerError
}
/**
only block when any one of the following occurs:
1. the asyncTaskQueue is full, increase the queue size to avoid this
2. Shutdown() in progressing, the client is being closed
**/
func (client *Client) AddAsyncTask(task func()) (err error) {
if client.asyncTaskQueue != nil {
client.asyncChanLock.RLock()
defer client.asyncChanLock.RUnlock()
if client.isRunning {
client.asyncTaskQueue <- task
}
} else {
err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil)
}
return
}
func (client *Client) GetConfig() *Config {
return client.config
}
func NewClient() (client *Client, err error) {
client = &Client{}
err = client.Init()
return
}
func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) {
client = &Client{}
var pc provider.Provider
if len(providers) == 0 {
pc = provider.DefaultChain
} else {
pc = provider.NewProviderChain(providers)
}
err = client.InitWithProviderChain(regionId, pc)
return
}
func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) {
client = &Client{}
err = client.InitWithOptions(regionId, config, credential)
return
}
func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
client = &Client{}
err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
return
}
func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
return
}
func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
return
}
func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
return
}
func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithEcsRamRole(regionId, roleName)
return
}
func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
client = &Client{}
err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
return
}
func NewClientWithBearerToken(regionId, bearerToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithBearerToken(regionId, bearerToken)
return
}
func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) {
request.TransToAcsRequest()
response = responses.NewCommonResponse()
err = client.DoAction(request, response)
return
}
func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) {
if signer, isSigner := signerInterface.(auth.Signer); isSigner {
request.TransToAcsRequest()
response = responses.NewCommonResponse()
err = client.DoActionWithSigner(request, response, signer)
return
}
panic("should not be here")
}
func (client *Client) Shutdown() {
// lock the addAsync()
client.asyncChanLock.Lock()
defer client.asyncChanLock.Unlock()
if client.asyncTaskQueue != nil {
close(client.asyncTaskQueue)
}
client.isRunning = false
}
// Deprecated: Use NewClientWithRamRoleArn in this package instead.
func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
return NewClientWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
}
// Deprecated: Use NewClientWithEcsRamRole in this package instead.
func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) {
return NewClientWithEcsRamRole(regionId, roleName)
}

View File

@ -0,0 +1,92 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sdk
import (
"net/http"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
type Config struct {
AutoRetry bool `default:"true"`
MaxRetryTime int `default:"3"`
UserAgent string `default:""`
Debug bool `default:"false"`
HttpTransport *http.Transport `default:""`
Transport http.RoundTripper `default:""`
EnableAsync bool `default:"false"`
MaxTaskQueueSize int `default:"1000"`
GoRoutinePoolSize int `default:"5"`
Scheme string `default:"HTTP"`
Timeout time.Duration
}
func NewConfig() (config *Config) {
config = &Config{}
utils.InitStructWithDefaultTag(config)
return
}
func (c *Config) WithAutoRetry(isAutoRetry bool) *Config {
c.AutoRetry = isAutoRetry
return c
}
func (c *Config) WithMaxRetryTime(maxRetryTime int) *Config {
c.MaxRetryTime = maxRetryTime
return c
}
func (c *Config) WithUserAgent(userAgent string) *Config {
c.UserAgent = userAgent
return c
}
func (c *Config) WithDebug(isDebug bool) *Config {
c.Debug = isDebug
return c
}
func (c *Config) WithTimeout(timeout time.Duration) *Config {
c.Timeout = timeout
return c
}
func (c *Config) WithHttpTransport(httpTransport *http.Transport) *Config {
c.HttpTransport = httpTransport
return c
}
func (c *Config) WithEnableAsync(isEnableAsync bool) *Config {
c.EnableAsync = isEnableAsync
return c
}
func (c *Config) WithMaxTaskQueueSize(maxTaskQueueSize int) *Config {
c.MaxTaskQueueSize = maxTaskQueueSize
return c
}
func (c *Config) WithGoRoutinePoolSize(goRoutinePoolSize int) *Config {
c.GoRoutinePoolSize = goRoutinePoolSize
return c
}
func (c *Config) WithScheme(scheme string) *Config {
c.Scheme = scheme
return c
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"fmt"
"strings"
"github.com/jmespath/go-jmespath"
)
type LocalGlobalResolver struct {
}
func (resolver *LocalGlobalResolver) GetName() (name string) {
name = "local global resolver"
return
}
func (resolver *LocalGlobalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) {
// get the global endpoints configs
endpointExpression := fmt.Sprintf("products[?code=='%s'].global_endpoint", strings.ToLower(param.Product))
endpointData, err := jmespath.Search(endpointExpression, getEndpointConfigData())
if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 {
endpoint = endpointData.([]interface{})[0].(string)
support = len(endpoint) > 0
return
}
support = false
return
}

View File

@ -0,0 +1,48 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"fmt"
"strings"
"github.com/jmespath/go-jmespath"
)
type LocalRegionalResolver struct {
}
func (resolver *LocalRegionalResolver) GetName() (name string) {
name = "local regional resolver"
return
}
func (resolver *LocalRegionalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) {
// get the regional endpoints configs
regionalExpression := fmt.Sprintf("products[?code=='%s'].regional_endpoints", strings.ToLower(param.Product))
regionalData, err := jmespath.Search(regionalExpression, getEndpointConfigData())
if err == nil && regionalData != nil && len(regionalData.([]interface{})) > 0 {
endpointExpression := fmt.Sprintf("[0][?region=='%s'].endpoint", strings.ToLower(param.RegionId))
var endpointData interface{}
endpointData, err = jmespath.Search(endpointExpression, regionalData)
if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 {
endpoint = endpointData.([]interface{})[0].(string)
support = len(endpoint) > 0
return
}
}
support = false
return
}

View File

@ -0,0 +1,176 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"encoding/json"
"sync"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
)
const (
// EndpointCacheExpireTime ...
EndpointCacheExpireTime = 3600 //Seconds
)
// Cache caches endpoint for specific product and region
type Cache struct {
sync.RWMutex
cache map[string]interface{}
}
// Get ...
func (c *Cache) Get(k string) (v interface{}) {
c.RLock()
v = c.cache[k]
c.RUnlock()
return
}
// Set ...
func (c *Cache) Set(k string, v interface{}) {
c.Lock()
c.cache[k] = v
c.Unlock()
}
var lastClearTimePerProduct = &Cache{cache: make(map[string]interface{})}
var endpointCache = &Cache{cache: make(map[string]interface{})}
// LocationResolver ...
type LocationResolver struct {
}
func (resolver *LocationResolver) GetName() (name string) {
name = "location resolver"
return
}
// TryResolve resolves endpoint giving product and region
func (resolver *LocationResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) {
if len(param.LocationProduct) <= 0 {
support = false
return
}
//get from cache
cacheKey := param.Product + "#" + param.RegionId
var ok bool
endpoint, ok = endpointCache.Get(cacheKey).(string)
if ok && len(endpoint) > 0 && !CheckCacheIsExpire(cacheKey) {
support = true
return
}
//get from remote
getEndpointRequest := requests.NewCommonRequest()
getEndpointRequest.Product = "Location"
getEndpointRequest.Version = "2015-06-12"
getEndpointRequest.ApiName = "DescribeEndpoints"
getEndpointRequest.Domain = "location-readonly.aliyuncs.com"
getEndpointRequest.Method = "GET"
getEndpointRequest.Scheme = requests.HTTPS
getEndpointRequest.QueryParams["Id"] = param.RegionId
getEndpointRequest.QueryParams["ServiceCode"] = param.LocationProduct
if len(param.LocationEndpointType) > 0 {
getEndpointRequest.QueryParams["Type"] = param.LocationEndpointType
} else {
getEndpointRequest.QueryParams["Type"] = "openAPI"
}
response, err := param.CommonApi(getEndpointRequest)
if err != nil {
support = false
return
}
if !response.IsSuccess() {
support = false
return
}
var getEndpointResponse GetEndpointResponse
err = json.Unmarshal([]byte(response.GetHttpContentString()), &getEndpointResponse)
if err != nil {
support = false
return
}
if !getEndpointResponse.Success || getEndpointResponse.Endpoints == nil {
support = false
return
}
if len(getEndpointResponse.Endpoints.Endpoint) <= 0 {
support = false
return
}
if len(getEndpointResponse.Endpoints.Endpoint[0].Endpoint) > 0 {
endpoint = getEndpointResponse.Endpoints.Endpoint[0].Endpoint
endpointCache.Set(cacheKey, endpoint)
lastClearTimePerProduct.Set(cacheKey, time.Now().Unix())
support = true
return
}
support = false
return
}
// CheckCacheIsExpire ...
func CheckCacheIsExpire(cacheKey string) bool {
lastClearTime, ok := lastClearTimePerProduct.Get(cacheKey).(int64)
if !ok {
return true
}
if lastClearTime <= 0 {
lastClearTime = time.Now().Unix()
lastClearTimePerProduct.Set(cacheKey, lastClearTime)
}
now := time.Now().Unix()
elapsedTime := now - lastClearTime
if elapsedTime > EndpointCacheExpireTime {
return true
}
return false
}
// GetEndpointResponse ...
type GetEndpointResponse struct {
Endpoints *EndpointsObj
RequestId string
Success bool
}
// EndpointsObj ...
type EndpointsObj struct {
Endpoint []EndpointObj
}
// EndpointObj ...
type EndpointObj struct {
// Protocols map[string]string
Type string
Namespace string
Id string
SerivceCode string
Endpoint string
}

View File

@ -0,0 +1,49 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"fmt"
"strings"
"sync"
)
const keyFormatter = "%s::%s"
type EndpointMapping struct {
sync.RWMutex
endpoint map[string]string
}
var endpointMapping = EndpointMapping{endpoint: make(map[string]string)}
// AddEndpointMapping use productId and regionId as key to store the endpoint into inner map
// when using the same productId and regionId as key, the endpoint will be covered.
func AddEndpointMapping(regionId, productId, endpoint string) (err error) {
key := fmt.Sprintf(keyFormatter, strings.ToLower(regionId), strings.ToLower(productId))
endpointMapping.Lock()
endpointMapping.endpoint[key] = endpoint
endpointMapping.Unlock()
return nil
}
// GetEndpointFromMap use Product and RegionId as key to find endpoint from inner map
func GetEndpointFromMap(regionId, productId string) string {
key := fmt.Sprintf(keyFormatter, strings.ToLower(regionId), strings.ToLower(productId))
endpointMapping.RLock()
endpoint := endpointMapping.endpoint[key]
endpointMapping.RUnlock()
return endpoint
}

View File

@ -0,0 +1,96 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package endpoints
import (
"encoding/json"
"fmt"
"sync"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
var debug utils.Debug
func init() {
debug = utils.Init("sdk")
}
const (
ResolveEndpointUserGuideLink = ""
)
var once sync.Once
var resolvers []Resolver
type Resolver interface {
TryResolve(param *ResolveParam) (endpoint string, support bool, err error)
GetName() (name string)
}
// Resolve resolve endpoint with params
// It will resolve with each supported resolver until anyone resolved
func Resolve(param *ResolveParam) (endpoint string, err error) {
supportedResolvers := getAllResolvers()
var lastErr error
for _, resolver := range supportedResolvers {
endpoint, supported, resolveErr := resolver.TryResolve(param)
if resolveErr != nil {
lastErr = resolveErr
}
if supported {
debug("resolve endpoint with %s\n", param)
debug("\t%s by resolver(%s)\n", endpoint, resolver.GetName())
return endpoint, nil
}
}
// not support
errorMsg := fmt.Sprintf(errors.CanNotResolveEndpointErrorMessage, param, ResolveEndpointUserGuideLink)
err = errors.NewClientError(errors.CanNotResolveEndpointErrorCode, errorMsg, lastErr)
return
}
func getAllResolvers() []Resolver {
once.Do(func() {
resolvers = []Resolver{
&LocationResolver{},
&LocalRegionalResolver{},
&LocalGlobalResolver{},
}
})
return resolvers
}
type ResolveParam struct {
Domain string
Product string
RegionId string
LocationProduct string
LocationEndpointType string
CommonApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error) `json:"-"`
}
func (param *ResolveParam) String() string {
jsonBytes, err := json.Marshal(param)
if err != nil {
return fmt.Sprint("ResolveParam.String() process error:", err)
}
return string(jsonBytes)
}

View File

@ -0,0 +1,92 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package errors
import "fmt"
const (
DefaultClientErrorStatus = 400
DefaultClientErrorCode = "SDK.ClientError"
UnsupportedCredentialErrorCode = "SDK.UnsupportedCredential"
UnsupportedCredentialErrorMessage = "Specified credential (type = %s) is not supported, please check"
CanNotResolveEndpointErrorCode = "SDK.CanNotResolveEndpoint"
CanNotResolveEndpointErrorMessage = "Can not resolve endpoint(param = %s), please check your accessKey with secret, and read the user guide\n %s"
UnsupportedParamPositionErrorCode = "SDK.UnsupportedParamPosition"
UnsupportedParamPositionErrorMessage = "Specified param position (%s) is not supported, please upgrade sdk and retry"
AsyncFunctionNotEnabledCode = "SDK.AsyncFunctionNotEnabled"
AsyncFunctionNotEnabledMessage = "Async function is not enabled in client, please invoke 'client.EnableAsync' function"
UnknownRequestTypeErrorCode = "SDK.UnknownRequestType"
UnknownRequestTypeErrorMessage = "Unknown Request Type: %s"
MissingParamErrorCode = "SDK.MissingParam"
InvalidParamErrorCode = "SDK.InvalidParam"
JsonUnmarshalErrorCode = "SDK.JsonUnmarshalError"
JsonUnmarshalErrorMessage = "Failed to unmarshal response, but you can get the data via response.GetHttpStatusCode() and response.GetHttpContentString()"
TimeoutErrorCode = "SDK.TimeoutError"
TimeoutErrorMessage = "The request timed out %s times(%s for retry), perhaps we should have the threshold raised a little?"
)
type ClientError struct {
errorCode string
message string
originError error
}
func NewClientError(errorCode, message string, originErr error) Error {
return &ClientError{
errorCode: errorCode,
message: message,
originError: originErr,
}
}
func (err *ClientError) Error() string {
clientErrMsg := fmt.Sprintf("[%s] %s", err.ErrorCode(), err.message)
if err.originError != nil {
return clientErrMsg + "\ncaused by:\n" + err.originError.Error()
}
return clientErrMsg
}
func (err *ClientError) OriginError() error {
return err.originError
}
func (*ClientError) HttpStatus() int {
return DefaultClientErrorStatus
}
func (err *ClientError) ErrorCode() string {
if err.errorCode == "" {
return DefaultClientErrorCode
} else {
return err.errorCode
}
}
func (err *ClientError) Message() string {
return err.message
}
func (err *ClientError) String() string {
return err.Error()
}

View File

@ -0,0 +1,23 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package errors
type Error interface {
error
HttpStatus() int
ErrorCode() string
Message() string
OriginError() error
}

View File

@ -0,0 +1,123 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package errors
import (
"encoding/json"
"fmt"
"github.com/jmespath/go-jmespath"
)
var wrapperList = []ServerErrorWrapper{
&SignatureDostNotMatchWrapper{},
}
type ServerError struct {
httpStatus int
requestId string
hostId string
errorCode string
recommend string
message string
comment string
}
type ServerErrorWrapper interface {
tryWrap(error *ServerError, wrapInfo map[string]string) bool
}
func (err *ServerError) Error() string {
return fmt.Sprintf("SDK.ServerError\nErrorCode: %s\nRecommend: %s\nRequestId: %s\nMessage: %s",
err.errorCode, err.comment+err.recommend, err.requestId, err.message)
}
func NewServerError(httpStatus int, responseContent, comment string) Error {
result := &ServerError{
httpStatus: httpStatus,
message: responseContent,
comment: comment,
}
var data interface{}
err := json.Unmarshal([]byte(responseContent), &data)
if err == nil {
requestId, _ := jmespath.Search("RequestId", data)
hostId, _ := jmespath.Search("HostId", data)
errorCode, _ := jmespath.Search("Code", data)
recommend, _ := jmespath.Search("Recommend", data)
message, _ := jmespath.Search("Message", data)
if requestId != nil {
result.requestId = requestId.(string)
}
if hostId != nil {
result.hostId = hostId.(string)
}
if errorCode != nil {
result.errorCode = errorCode.(string)
}
if recommend != nil {
result.recommend = recommend.(string)
}
if message != nil {
result.message = message.(string)
}
}
return result
}
func WrapServerError(originError *ServerError, wrapInfo map[string]string) *ServerError {
for _, wrapper := range wrapperList {
ok := wrapper.tryWrap(originError, wrapInfo)
if ok {
return originError
}
}
return originError
}
func (err *ServerError) HttpStatus() int {
return err.httpStatus
}
func (err *ServerError) ErrorCode() string {
return err.errorCode
}
func (err *ServerError) Message() string {
return err.message
}
func (err *ServerError) OriginError() error {
return nil
}
func (err *ServerError) HostId() string {
return err.hostId
}
func (err *ServerError) RequestId() string {
return err.requestId
}
func (err *ServerError) Recommend() string {
return err.recommend
}
func (err *ServerError) Comment() string {
return err.comment
}

View File

@ -0,0 +1,45 @@
package errors
import (
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
const SignatureDostNotMatchErrorCode = "SignatureDoesNotMatch"
const IncompleteSignatureErrorCode = "IncompleteSignature"
const MessageContain = "server string to sign is:"
var debug utils.Debug
func init() {
debug = utils.Init("sdk")
}
type SignatureDostNotMatchWrapper struct {
}
func (*SignatureDostNotMatchWrapper) tryWrap(error *ServerError, wrapInfo map[string]string) (ok bool) {
clientStringToSign := wrapInfo["StringToSign"]
if (error.errorCode == SignatureDostNotMatchErrorCode || error.errorCode == IncompleteSignatureErrorCode) && clientStringToSign != "" {
message := error.message
if strings.Contains(message, MessageContain) {
str := strings.Split(message, MessageContain)
serverStringToSign := str[1]
if clientStringToSign == serverStringToSign {
// user secret is error
error.recommend = "InvalidAccessKeySecret: Please check you AccessKeySecret"
} else {
debug("Client StringToSign: %s", clientStringToSign)
debug("Server StringToSign: %s", serverStringToSign)
error.recommend = "This may be a bug with the SDK and we hope you can submit this question in the " +
"github issue(https://github.com/aliyun/alibaba-cloud-sdk-go/issues), thanks very much"
}
}
ok = true
return
}
ok = false
return
}

View File

@ -0,0 +1,116 @@
package sdk
import (
"encoding/json"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
"io"
"log"
"os"
"strings"
"time"
)
var logChannel string
var defaultChannel = "AlibabaCloud"
type Logger struct {
*log.Logger
formatTemplate string
isOpen bool
lastLogMsg string
}
var defaultLoggerTemplate = `{time} {channel}: "{method} {uri} HTTP/{version}" {code} {cost} {hostname}`
var loggerParam = []string{"{time}", "{start_time}", "{ts}", "{channel}", "{pid}", "{host}", "{method}", "{uri}", "{version}", "{target}", "{hostname}", "{code}", "{error}", "{req_headers}", "{res_body}", "{res_headers}", "{cost}"}
func initLogMsg(fieldMap map[string]string) {
for _, value := range loggerParam {
fieldMap[value] = ""
}
}
func (client *Client) GetLogger() *Logger {
return client.logger
}
func (client *Client) GetLoggerMsg() string {
if client.logger == nil {
client.SetLogger("", "", os.Stdout, "")
}
return client.logger.lastLogMsg
}
func (client *Client) SetLogger(level string, channel string, out io.Writer, template string) {
if level == "" {
level = "info"
}
logChannel = "AlibabaCloud"
if channel != "" {
logChannel = channel
}
log := log.New(out, "["+strings.ToUpper(level)+"]", log.Lshortfile)
if template == "" {
template = defaultLoggerTemplate
}
client.logger = &Logger{
Logger: log,
formatTemplate: template,
isOpen: true,
}
}
func (client *Client) OpenLogger() {
if client.logger == nil {
client.SetLogger("", "", os.Stdout, "")
}
client.logger.isOpen = true
}
func (client *Client) CloseLogger() {
if client.logger != nil {
client.logger.isOpen = false
}
}
func (client *Client) SetTemplate(template string) {
if client.logger == nil {
client.SetLogger("", "", os.Stdout, "")
}
client.logger.formatTemplate = template
}
func (client *Client) GetTemplate() string {
if client.logger == nil {
client.SetLogger("", "", os.Stdout, "")
}
return client.logger.formatTemplate
}
func TransToString(object interface{}) string {
byt, err := json.Marshal(object)
if err != nil {
return ""
}
return string(byt)
}
func (client *Client) printLog(fieldMap map[string]string, err error) {
if err != nil {
fieldMap["{error}"] = err.Error()
}
fieldMap["{time}"] = time.Now().Format("2006-01-02 15:04:05")
fieldMap["{ts}"] = utils.GetTimeInFormatISO8601()
fieldMap["{channel}"] = logChannel
if client.logger != nil {
logMsg := client.logger.formatTemplate
for key, value := range fieldMap {
logMsg = strings.Replace(logMsg, key, value, -1)
}
client.logger.lastLogMsg = logMsg
if client.logger.isOpen == true {
client.logger.Output(2, logMsg)
}
}
}

View File

@ -0,0 +1,443 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package requests
import (
"encoding/json"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
)
const (
RPC = "RPC"
ROA = "ROA"
HTTP = "HTTP"
HTTPS = "HTTPS"
DefaultHttpPort = "80"
GET = "GET"
PUT = "PUT"
POST = "POST"
DELETE = "DELETE"
PATCH = "PATCH"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
Json = "application/json"
Xml = "application/xml"
Raw = "application/octet-stream"
Form = "application/x-www-form-urlencoded"
Header = "Header"
Query = "Query"
Body = "Body"
Path = "Path"
HeaderSeparator = "\n"
)
// interface
type AcsRequest interface {
GetScheme() string
GetMethod() string
GetDomain() string
GetPort() string
GetRegionId() string
GetHeaders() map[string]string
GetQueryParams() map[string]string
GetFormParams() map[string]string
GetContent() []byte
GetBodyReader() io.Reader
GetStyle() string
GetProduct() string
GetVersion() string
SetVersion(version string)
GetActionName() string
GetAcceptFormat() string
GetLocationServiceCode() string
GetLocationEndpointType() string
GetReadTimeout() time.Duration
GetConnectTimeout() time.Duration
SetReadTimeout(readTimeout time.Duration)
SetConnectTimeout(connectTimeout time.Duration)
SetHTTPSInsecure(isInsecure bool)
GetHTTPSInsecure() *bool
GetUserAgent() map[string]string
SetStringToSign(stringToSign string)
GetStringToSign() string
SetDomain(domain string)
SetContent(content []byte)
SetScheme(scheme string)
BuildUrl() string
BuildQueries() string
addHeaderParam(key, value string)
addQueryParam(key, value string)
addFormParam(key, value string)
addPathParam(key, value string)
}
// base class
type baseRequest struct {
Scheme string
Method string
Domain string
Port string
RegionId string
ReadTimeout time.Duration
ConnectTimeout time.Duration
isInsecure *bool
userAgent map[string]string
product string
version string
actionName string
AcceptFormat string
QueryParams map[string]string
Headers map[string]string
FormParams map[string]string
Content []byte
locationServiceCode string
locationEndpointType string
queries string
stringToSign string
}
func (request *baseRequest) GetQueryParams() map[string]string {
return request.QueryParams
}
func (request *baseRequest) GetFormParams() map[string]string {
return request.FormParams
}
func (request *baseRequest) GetReadTimeout() time.Duration {
return request.ReadTimeout
}
func (request *baseRequest) GetConnectTimeout() time.Duration {
return request.ConnectTimeout
}
func (request *baseRequest) SetReadTimeout(readTimeout time.Duration) {
request.ReadTimeout = readTimeout
}
func (request *baseRequest) SetConnectTimeout(connectTimeout time.Duration) {
request.ConnectTimeout = connectTimeout
}
func (request *baseRequest) GetHTTPSInsecure() *bool {
return request.isInsecure
}
func (request *baseRequest) SetHTTPSInsecure(isInsecure bool) {
request.isInsecure = &isInsecure
}
func (request *baseRequest) GetContent() []byte {
return request.Content
}
func (request *baseRequest) SetVersion(version string) {
request.version = version
}
func (request *baseRequest) GetVersion() string {
return request.version
}
func (request *baseRequest) GetActionName() string {
return request.actionName
}
func (request *baseRequest) SetContent(content []byte) {
request.Content = content
}
func (request *baseRequest) GetUserAgent() map[string]string {
return request.userAgent
}
func (request *baseRequest) AppendUserAgent(key, value string) {
newkey := true
if request.userAgent == nil {
request.userAgent = make(map[string]string)
}
if strings.ToLower(key) != "core" && strings.ToLower(key) != "go" {
for tag, _ := range request.userAgent {
if tag == key {
request.userAgent[tag] = value
newkey = false
}
}
if newkey {
request.userAgent[key] = value
}
}
}
func (request *baseRequest) addHeaderParam(key, value string) {
request.Headers[key] = value
}
func (request *baseRequest) addQueryParam(key, value string) {
request.QueryParams[key] = value
}
func (request *baseRequest) addFormParam(key, value string) {
request.FormParams[key] = value
}
func (request *baseRequest) GetAcceptFormat() string {
return request.AcceptFormat
}
func (request *baseRequest) GetLocationServiceCode() string {
return request.locationServiceCode
}
func (request *baseRequest) GetLocationEndpointType() string {
return request.locationEndpointType
}
func (request *baseRequest) GetProduct() string {
return request.product
}
func (request *baseRequest) GetScheme() string {
return request.Scheme
}
func (request *baseRequest) SetScheme(scheme string) {
request.Scheme = scheme
}
func (request *baseRequest) GetMethod() string {
return request.Method
}
func (request *baseRequest) GetDomain() string {
return request.Domain
}
func (request *baseRequest) SetDomain(host string) {
request.Domain = host
}
func (request *baseRequest) GetPort() string {
return request.Port
}
func (request *baseRequest) GetRegionId() string {
return request.RegionId
}
func (request *baseRequest) GetHeaders() map[string]string {
return request.Headers
}
func (request *baseRequest) SetContentType(contentType string) {
request.addHeaderParam("Content-Type", contentType)
}
func (request *baseRequest) GetContentType() (contentType string, contains bool) {
contentType, contains = request.Headers["Content-Type"]
return
}
func (request *baseRequest) SetStringToSign(stringToSign string) {
request.stringToSign = stringToSign
}
func (request *baseRequest) GetStringToSign() string {
return request.stringToSign
}
func defaultBaseRequest() (request *baseRequest) {
request = &baseRequest{
Scheme: "",
AcceptFormat: "JSON",
Method: GET,
QueryParams: make(map[string]string),
Headers: map[string]string{
"x-sdk-client": "golang/1.0.0",
"x-sdk-invoke-type": "normal",
"Accept-Encoding": "identity",
},
FormParams: make(map[string]string),
}
return
}
func InitParams(request AcsRequest) (err error) {
requestValue := reflect.ValueOf(request).Elem()
err = flatRepeatedList(requestValue, request, "", "")
return
}
func flatRepeatedList(dataValue reflect.Value, request AcsRequest, position, prefix string) (err error) {
dataType := dataValue.Type()
for i := 0; i < dataType.NumField(); i++ {
field := dataType.Field(i)
name, containsNameTag := field.Tag.Lookup("name")
fieldPosition := position
if fieldPosition == "" {
fieldPosition, _ = field.Tag.Lookup("position")
}
typeTag, containsTypeTag := field.Tag.Lookup("type")
if containsNameTag {
if !containsTypeTag {
// simple param
key := prefix + name
value := dataValue.Field(i).String()
if dataValue.Field(i).Kind().String() == "map" {
byt, _ := json.Marshal(dataValue.Field(i).Interface())
value = string(byt)
if value == "null" {
value = ""
}
}
err = addParam(request, fieldPosition, key, value)
if err != nil {
return
}
} else if typeTag == "Repeated" {
// repeated param
err = handleRepeatedParams(request, dataValue, prefix, name, fieldPosition, i)
if err != nil {
return
}
} else if typeTag == "Struct" {
err = handleStruct(request, dataValue, prefix, name, fieldPosition, i)
if err != nil {
return
}
}
}
}
return
}
func handleRepeatedParams(request AcsRequest, dataValue reflect.Value, prefix, name, fieldPosition string, index int) (err error) {
repeatedFieldValue := dataValue.Field(index)
if repeatedFieldValue.Kind() != reflect.Slice {
// possible value: {"[]string", "*[]struct"}, we must call Elem() in the last condition
repeatedFieldValue = repeatedFieldValue.Elem()
}
if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() {
for m := 0; m < repeatedFieldValue.Len(); m++ {
elementValue := repeatedFieldValue.Index(m)
key := prefix + name + "." + strconv.Itoa(m+1)
if elementValue.Type().Kind().String() == "string" {
value := elementValue.String()
err = addParam(request, fieldPosition, key, value)
if err != nil {
return
}
} else {
err = flatRepeatedList(elementValue, request, fieldPosition, key+".")
if err != nil {
return
}
}
}
}
return nil
}
func handleStruct(request AcsRequest, dataValue reflect.Value, prefix, name, fieldPosition string, index int) (err error) {
valueField := dataValue.Field(index)
if valueField.IsValid() && valueField.String() != "" {
valueFieldType := valueField.Type()
for m := 0; m < valueFieldType.NumField(); m++ {
fieldName := valueFieldType.Field(m).Name
elementValue := valueField.FieldByName(fieldName)
key := prefix + name + "." + fieldName
if elementValue.Type().String() == "[]string" {
if elementValue.IsNil() {
continue
}
for j := 0; j < elementValue.Len(); j++ {
err = addParam(request, fieldPosition, key+"."+strconv.Itoa(j+1), elementValue.Index(j).String())
if err != nil {
return
}
}
} else {
if elementValue.Type().Kind().String() == "string" {
value := elementValue.String()
err = addParam(request, fieldPosition, key, value)
if err != nil {
return
}
} else if elementValue.Type().Kind().String() == "struct" {
err = flatRepeatedList(elementValue, request, fieldPosition, key+".")
if err != nil {
return
}
} else if !elementValue.IsNil() {
repeatedFieldValue := elementValue.Elem()
if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() {
for m := 0; m < repeatedFieldValue.Len(); m++ {
elementValue := repeatedFieldValue.Index(m)
err = flatRepeatedList(elementValue, request, fieldPosition, key+"."+strconv.Itoa(m+1)+".")
if err != nil {
return
}
}
}
}
}
}
}
return nil
}
func addParam(request AcsRequest, position, name, value string) (err error) {
if len(value) > 0 {
switch position {
case Header:
request.addHeaderParam(name, value)
case Query:
request.addQueryParam(name, value)
case Path:
request.addPathParam(name, value)
case Body:
request.addFormParam(name, value)
default:
errMsg := fmt.Sprintf(errors.UnsupportedParamPositionErrorMessage, position)
err = errors.NewClientError(errors.UnsupportedParamPositionErrorCode, errMsg, nil)
}
}
return
}

View File

@ -0,0 +1,108 @@
package requests
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
)
type CommonRequest struct {
*baseRequest
Version string
ApiName string
Product string
ServiceCode string
// roa params
PathPattern string
PathParams map[string]string
Ontology AcsRequest
}
func NewCommonRequest() (request *CommonRequest) {
request = &CommonRequest{
baseRequest: defaultBaseRequest(),
}
request.Headers["x-sdk-invoke-type"] = "common"
request.PathParams = make(map[string]string)
return
}
func (request *CommonRequest) String() string {
request.TransToAcsRequest()
resultBuilder := bytes.Buffer{}
mapOutput := func(m map[string]string) {
if len(m) > 0 {
sortedKeys := make([]string, 0)
for k := range m {
sortedKeys = append(sortedKeys, k)
}
// sort 'string' key in increasing order
sort.Strings(sortedKeys)
for _, key := range sortedKeys {
resultBuilder.WriteString(key + ": " + m[key] + "\n")
}
}
}
// Request Line
resultBuilder.WriteString(fmt.Sprintf("%s %s %s/1.1\n", request.Method, request.BuildQueries(), strings.ToUpper(request.Scheme)))
// Headers
resultBuilder.WriteString("Host" + ": " + request.Domain + "\n")
mapOutput(request.Headers)
resultBuilder.WriteString("\n")
// Body
if len(request.Content) > 0 {
resultBuilder.WriteString(string(request.Content) + "\n")
} else {
mapOutput(request.FormParams)
}
return resultBuilder.String()
}
func (request *CommonRequest) TransToAcsRequest() {
if len(request.PathPattern) > 0 {
roaRequest := &RoaRequest{}
roaRequest.initWithCommonRequest(request)
request.Ontology = roaRequest
} else {
rpcRequest := &RpcRequest{}
rpcRequest.baseRequest = request.baseRequest
rpcRequest.product = request.Product
rpcRequest.version = request.Version
rpcRequest.locationServiceCode = request.ServiceCode
rpcRequest.actionName = request.ApiName
request.Ontology = rpcRequest
}
}
func (request *CommonRequest) BuildUrl() string {
return request.Ontology.BuildUrl()
}
func (request *CommonRequest) BuildQueries() string {
return request.Ontology.BuildQueries()
}
func (request *CommonRequest) GetBodyReader() io.Reader {
return request.Ontology.GetBodyReader()
}
func (request *CommonRequest) GetStyle() string {
return request.Ontology.GetStyle()
}
func (request *CommonRequest) addPathParam(key, value string) {
request.PathParams[key] = value
}

View File

@ -0,0 +1,152 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package requests
import (
"bytes"
"fmt"
"io"
"net/url"
"sort"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
type RoaRequest struct {
*baseRequest
pathPattern string
PathParams map[string]string
}
func (*RoaRequest) GetStyle() string {
return ROA
}
func (request *RoaRequest) GetBodyReader() io.Reader {
if request.FormParams != nil && len(request.FormParams) > 0 {
formString := utils.GetUrlFormedMap(request.FormParams)
return strings.NewReader(formString)
} else if len(request.Content) > 0 {
return bytes.NewReader(request.Content)
} else {
return nil
}
}
// for sign method, need not url encoded
func (request *RoaRequest) BuildQueries() string {
return request.buildQueries()
}
func (request *RoaRequest) buildPath() string {
path := request.pathPattern
for key, value := range request.PathParams {
path = strings.Replace(path, "["+key+"]", value, 1)
}
return path
}
func (request *RoaRequest) buildQueries() string {
// replace path params with value
path := request.buildPath()
queryParams := request.QueryParams
// sort QueryParams by key
var queryKeys []string
for key := range queryParams {
queryKeys = append(queryKeys, key)
}
sort.Strings(queryKeys)
// append urlBuilder
urlBuilder := bytes.Buffer{}
urlBuilder.WriteString(path)
if len(queryKeys) > 0 {
urlBuilder.WriteString("?")
}
for i := 0; i < len(queryKeys); i++ {
queryKey := queryKeys[i]
urlBuilder.WriteString(queryKey)
if value := queryParams[queryKey]; len(value) > 0 {
urlBuilder.WriteString("=")
urlBuilder.WriteString(value)
}
if i < len(queryKeys)-1 {
urlBuilder.WriteString("&")
}
}
result := urlBuilder.String()
result = popStandardUrlencode(result)
return result
}
func (request *RoaRequest) buildQueryString() string {
queryParams := request.QueryParams
// sort QueryParams by key
q := url.Values{}
for key, value := range queryParams {
q.Add(key, value)
}
return q.Encode()
}
func popStandardUrlencode(stringToSign string) (result string) {
result = strings.Replace(stringToSign, "+", "%20", -1)
result = strings.Replace(result, "*", "%2A", -1)
result = strings.Replace(result, "%7E", "~", -1)
return
}
func (request *RoaRequest) BuildUrl() string {
// for network trans, need url encoded
scheme := strings.ToLower(request.Scheme)
domain := request.Domain
port := request.Port
path := request.buildPath()
url := fmt.Sprintf("%s://%s:%s%s", scheme, domain, port, path)
querystring := request.buildQueryString()
if len(querystring) > 0 {
url = fmt.Sprintf("%s?%s", url, querystring)
}
return url
}
func (request *RoaRequest) addPathParam(key, value string) {
request.PathParams[key] = value
}
func (request *RoaRequest) InitWithApiInfo(product, version, action, uriPattern, serviceCode, endpointType string) {
request.baseRequest = defaultBaseRequest()
request.PathParams = make(map[string]string)
request.Headers["x-acs-version"] = version
request.pathPattern = uriPattern
request.locationServiceCode = serviceCode
request.locationEndpointType = endpointType
request.product = product
//request.version = version
request.actionName = action
}
func (request *RoaRequest) initWithCommonRequest(commonRequest *CommonRequest) {
request.baseRequest = commonRequest.baseRequest
request.PathParams = commonRequest.PathParams
request.product = commonRequest.Product
//request.version = commonRequest.Version
request.Headers["x-acs-version"] = commonRequest.Version
request.actionName = commonRequest.ApiName
request.pathPattern = commonRequest.PathPattern
request.locationServiceCode = commonRequest.ServiceCode
request.locationEndpointType = ""
}

View File

@ -0,0 +1,79 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package requests
import (
"fmt"
"io"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils"
)
type RpcRequest struct {
*baseRequest
}
func (request *RpcRequest) init() {
request.baseRequest = defaultBaseRequest()
request.Method = POST
}
func (*RpcRequest) GetStyle() string {
return RPC
}
func (request *RpcRequest) GetBodyReader() io.Reader {
if request.FormParams != nil && len(request.FormParams) > 0 {
formString := utils.GetUrlFormedMap(request.FormParams)
return strings.NewReader(formString)
} else {
return strings.NewReader("")
}
}
func (request *RpcRequest) BuildQueries() string {
request.queries = "/?" + utils.GetUrlFormedMap(request.QueryParams)
return request.queries
}
func (request *RpcRequest) BuildUrl() string {
url := fmt.Sprintf("%s://%s", strings.ToLower(request.Scheme), request.Domain)
if len(request.Port) > 0 {
url = fmt.Sprintf("%s:%s", url, request.Port)
}
return url + request.BuildQueries()
}
func (request *RpcRequest) GetVersion() string {
return request.version
}
func (request *RpcRequest) GetActionName() string {
return request.actionName
}
func (request *RpcRequest) addPathParam(key, value string) {
panic("not support")
}
func (request *RpcRequest) InitWithApiInfo(product, version, action, serviceCode, endpointType string) {
request.init()
request.product = product
request.version = version
request.actionName = action
request.locationServiceCode = serviceCode
request.locationEndpointType = endpointType
}

View File

@ -0,0 +1,53 @@
package requests
import "strconv"
type Integer string
func NewInteger(integer int) Integer {
return Integer(strconv.Itoa(integer))
}
func (integer Integer) HasValue() bool {
return integer != ""
}
func (integer Integer) GetValue() (int, error) {
return strconv.Atoi(string(integer))
}
func NewInteger64(integer int64) Integer {
return Integer(strconv.FormatInt(integer, 10))
}
func (integer Integer) GetValue64() (int64, error) {
return strconv.ParseInt(string(integer), 10, 0)
}
type Boolean string
func NewBoolean(bool bool) Boolean {
return Boolean(strconv.FormatBool(bool))
}
func (boolean Boolean) HasValue() bool {
return boolean != ""
}
func (boolean Boolean) GetValue() (bool, error) {
return strconv.ParseBool(string(boolean))
}
type Float string
func NewFloat(f float64) Float {
return Float(strconv.FormatFloat(f, 'f', 6, 64))
}
func (float Float) HasValue() bool {
return float != ""
}
func (float Float) GetValue() (float64, error) {
return strconv.ParseFloat(string(float), 64)
}

View File

@ -0,0 +1,328 @@
package responses
import (
"encoding/json"
"io"
"math"
"strconv"
"strings"
"unsafe"
jsoniter "github.com/json-iterator/go"
)
const maxUint = ^uint(0)
const maxInt = int(maxUint >> 1)
const minInt = -maxInt - 1
var jsonParser jsoniter.API
func init() {
registerBetterFuzzyDecoder()
jsonParser = jsoniter.Config{
EscapeHTML: true,
SortMapKeys: true,
ValidateJsonRawMessage: true,
CaseSensitive: true,
}.Froze()
}
func registerBetterFuzzyDecoder() {
jsoniter.RegisterTypeDecoder("string", &nullableFuzzyStringDecoder{})
jsoniter.RegisterTypeDecoder("bool", &fuzzyBoolDecoder{})
jsoniter.RegisterTypeDecoder("float32", &nullableFuzzyFloat32Decoder{})
jsoniter.RegisterTypeDecoder("float64", &nullableFuzzyFloat64Decoder{})
jsoniter.RegisterTypeDecoder("int", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(maxInt) || val < float64(minInt) {
iter.ReportError("fuzzy decode int", "exceed range")
return
}
*((*int)(ptr)) = int(val)
} else {
*((*int)(ptr)) = iter.ReadInt()
}
}})
jsoniter.RegisterTypeDecoder("uint", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(maxUint) || val < 0 {
iter.ReportError("fuzzy decode uint", "exceed range")
return
}
*((*uint)(ptr)) = uint(val)
} else {
*((*uint)(ptr)) = iter.ReadUint()
}
}})
jsoniter.RegisterTypeDecoder("int8", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt8) || val < float64(math.MinInt8) {
iter.ReportError("fuzzy decode int8", "exceed range")
return
}
*((*int8)(ptr)) = int8(val)
} else {
*((*int8)(ptr)) = iter.ReadInt8()
}
}})
jsoniter.RegisterTypeDecoder("uint8", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint8) || val < 0 {
iter.ReportError("fuzzy decode uint8", "exceed range")
return
}
*((*uint8)(ptr)) = uint8(val)
} else {
*((*uint8)(ptr)) = iter.ReadUint8()
}
}})
jsoniter.RegisterTypeDecoder("int16", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt16) || val < float64(math.MinInt16) {
iter.ReportError("fuzzy decode int16", "exceed range")
return
}
*((*int16)(ptr)) = int16(val)
} else {
*((*int16)(ptr)) = iter.ReadInt16()
}
}})
jsoniter.RegisterTypeDecoder("uint16", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint16) || val < 0 {
iter.ReportError("fuzzy decode uint16", "exceed range")
return
}
*((*uint16)(ptr)) = uint16(val)
} else {
*((*uint16)(ptr)) = iter.ReadUint16()
}
}})
jsoniter.RegisterTypeDecoder("int32", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt32) || val < float64(math.MinInt32) {
iter.ReportError("fuzzy decode int32", "exceed range")
return
}
*((*int32)(ptr)) = int32(val)
} else {
*((*int32)(ptr)) = iter.ReadInt32()
}
}})
jsoniter.RegisterTypeDecoder("uint32", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint32) || val < 0 {
iter.ReportError("fuzzy decode uint32", "exceed range")
return
}
*((*uint32)(ptr)) = uint32(val)
} else {
*((*uint32)(ptr)) = iter.ReadUint32()
}
}})
jsoniter.RegisterTypeDecoder("int64", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxInt64) || val < float64(math.MinInt64) {
iter.ReportError("fuzzy decode int64", "exceed range")
return
}
*((*int64)(ptr)) = int64(val)
} else {
*((*int64)(ptr)) = iter.ReadInt64()
}
}})
jsoniter.RegisterTypeDecoder("uint64", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
if isFloat {
val := iter.ReadFloat64()
if val > float64(math.MaxUint64) || val < 0 {
iter.ReportError("fuzzy decode uint64", "exceed range")
return
}
*((*uint64)(ptr)) = uint64(val)
} else {
*((*uint64)(ptr)) = iter.ReadUint64()
}
}})
}
type nullableFuzzyStringDecoder struct {
}
func (decoder *nullableFuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
switch valueType {
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
*((*string)(ptr)) = string(number)
case jsoniter.StringValue:
*((*string)(ptr)) = iter.ReadString()
case jsoniter.BoolValue:
*((*string)(ptr)) = strconv.FormatBool(iter.ReadBool())
case jsoniter.NilValue:
iter.ReadNil()
*((*string)(ptr)) = ""
default:
iter.ReportError("fuzzyStringDecoder", "not number or string or bool")
}
}
type fuzzyBoolDecoder struct {
}
func (decoder *fuzzyBoolDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
switch valueType {
case jsoniter.BoolValue:
*((*bool)(ptr)) = iter.ReadBool()
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
num, err := number.Int64()
if err != nil {
iter.ReportError("fuzzyBoolDecoder", "get value from json.number failed")
}
if num == 0 {
*((*bool)(ptr)) = false
} else {
*((*bool)(ptr)) = true
}
case jsoniter.StringValue:
strValue := strings.ToLower(iter.ReadString())
if strValue == "true" {
*((*bool)(ptr)) = true
} else if strValue == "false" || strValue == "" {
*((*bool)(ptr)) = false
} else {
iter.ReportError("fuzzyBoolDecoder", "unsupported bool value: "+strValue)
}
case jsoniter.NilValue:
iter.ReadNil()
*((*bool)(ptr)) = false
default:
iter.ReportError("fuzzyBoolDecoder", "not number or string or nil")
}
}
type nullableFuzzyIntegerDecoder struct {
fun func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator)
}
func (decoder *nullableFuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
var number json.Number
iter.ReadVal(&number)
str = string(number)
case jsoniter.StringValue:
str = iter.ReadString()
// support empty string
if str == "" {
str = "0"
}
case jsoniter.BoolValue:
if iter.ReadBool() {
str = "1"
} else {
str = "0"
}
case jsoniter.NilValue:
iter.ReadNil()
str = "0"
default:
iter.ReportError("fuzzyIntegerDecoder", "not number or string")
}
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
isFloat := strings.IndexByte(str, '.') != -1
decoder.fun(isFloat, ptr, newIter)
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
}
type nullableFuzzyFloat32Decoder struct {
}
func (decoder *nullableFuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
*((*float32)(ptr)) = iter.ReadFloat32()
case jsoniter.StringValue:
str = iter.ReadString()
// support empty string
if str == "" {
*((*float32)(ptr)) = 0
return
}
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
*((*float32)(ptr)) = newIter.ReadFloat32()
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
case jsoniter.BoolValue:
// support bool to float32
if iter.ReadBool() {
*((*float32)(ptr)) = 1
} else {
*((*float32)(ptr)) = 0
}
case jsoniter.NilValue:
iter.ReadNil()
*((*float32)(ptr)) = 0
default:
iter.ReportError("nullableFuzzyFloat32Decoder", "not number or string")
}
}
type nullableFuzzyFloat64Decoder struct {
}
func (decoder *nullableFuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
valueType := iter.WhatIsNext()
var str string
switch valueType {
case jsoniter.NumberValue:
*((*float64)(ptr)) = iter.ReadFloat64()
case jsoniter.StringValue:
str = iter.ReadString()
// support empty string
if str == "" {
*((*float64)(ptr)) = 0
return
}
newIter := iter.Pool().BorrowIterator([]byte(str))
defer iter.Pool().ReturnIterator(newIter)
*((*float64)(ptr)) = newIter.ReadFloat64()
if newIter.Error != nil && newIter.Error != io.EOF {
iter.Error = newIter.Error
}
case jsoniter.BoolValue:
// support bool to float64
if iter.ReadBool() {
*((*float64)(ptr)) = 1
} else {
*((*float64)(ptr)) = 0
}
case jsoniter.NilValue:
// support empty string
iter.ReadNil()
*((*float64)(ptr)) = 0
default:
iter.ReportError("nullableFuzzyFloat64Decoder", "not number or string")
}
}

View File

@ -0,0 +1,144 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package responses
import (
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
)
type AcsResponse interface {
IsSuccess() bool
GetHttpStatus() int
GetHttpHeaders() map[string][]string
GetHttpContentString() string
GetHttpContentBytes() []byte
GetOriginHttpResponse() *http.Response
parseFromHttpResponse(httpResponse *http.Response) error
}
// Unmarshal object from http response body to target Response
func Unmarshal(response AcsResponse, httpResponse *http.Response, format string) (err error) {
err = response.parseFromHttpResponse(httpResponse)
if err != nil {
return
}
if !response.IsSuccess() {
err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), "")
return
}
if _, isCommonResponse := response.(*CommonResponse); isCommonResponse {
// common response need not unmarshal
return
}
if len(response.GetHttpContentBytes()) == 0 {
return
}
if strings.ToUpper(format) == "JSON" {
err = jsonParser.Unmarshal(response.GetHttpContentBytes(), response)
if err != nil {
err = errors.NewClientError(errors.JsonUnmarshalErrorCode, errors.JsonUnmarshalErrorMessage, err)
}
} else if strings.ToUpper(format) == "XML" {
err = xml.Unmarshal(response.GetHttpContentBytes(), response)
}
return
}
type BaseResponse struct {
httpStatus int
httpHeaders map[string][]string
httpContentString string
httpContentBytes []byte
originHttpResponse *http.Response
}
func (baseResponse *BaseResponse) GetHttpStatus() int {
return baseResponse.httpStatus
}
func (baseResponse *BaseResponse) GetHttpHeaders() map[string][]string {
return baseResponse.httpHeaders
}
func (baseResponse *BaseResponse) GetHttpContentString() string {
return baseResponse.httpContentString
}
func (baseResponse *BaseResponse) GetHttpContentBytes() []byte {
return baseResponse.httpContentBytes
}
func (baseResponse *BaseResponse) GetOriginHttpResponse() *http.Response {
return baseResponse.originHttpResponse
}
func (baseResponse *BaseResponse) IsSuccess() bool {
if baseResponse.GetHttpStatus() >= 200 && baseResponse.GetHttpStatus() < 300 {
return true
}
return false
}
func (baseResponse *BaseResponse) parseFromHttpResponse(httpResponse *http.Response) (err error) {
defer httpResponse.Body.Close()
body, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
return
}
baseResponse.httpStatus = httpResponse.StatusCode
baseResponse.httpHeaders = httpResponse.Header
baseResponse.httpContentBytes = body
baseResponse.httpContentString = string(body)
baseResponse.originHttpResponse = httpResponse
return
}
func (baseResponse *BaseResponse) String() string {
resultBuilder := bytes.Buffer{}
// statusCode
// resultBuilder.WriteString("\n")
resultBuilder.WriteString(fmt.Sprintf("%s %s\n", baseResponse.originHttpResponse.Proto, baseResponse.originHttpResponse.Status))
// httpHeaders
//resultBuilder.WriteString("Headers:\n")
for key, value := range baseResponse.httpHeaders {
resultBuilder.WriteString(key + ": " + strings.Join(value, ";") + "\n")
}
resultBuilder.WriteString("\n")
// content
//resultBuilder.WriteString("Content:\n")
resultBuilder.WriteString(baseResponse.httpContentString + "\n")
return resultBuilder.String()
}
type CommonResponse struct {
*BaseResponse
}
func NewCommonResponse() (response *CommonResponse) {
return &CommonResponse{
BaseResponse: &BaseResponse{},
}
}

View File

@ -0,0 +1,36 @@
package utils
import (
"fmt"
"os"
"strings"
)
type Debug func(format string, v ...interface{})
var hookGetEnv = func() string {
return os.Getenv("DEBUG")
}
var hookPrint = func(input string) {
fmt.Println(input)
}
func Init(flag string) Debug {
enable := false
env := hookGetEnv()
parts := strings.Split(env, ",")
for _, part := range parts {
if part == flag {
enable = true
break
}
}
return func(format string, v ...interface{}) {
if enable {
hookPrint(fmt.Sprintf(format, v...))
}
}
}

View File

@ -0,0 +1,141 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package utils
import (
"crypto/md5"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"hash"
rand2 "math/rand"
"net/url"
"reflect"
"strconv"
"time"
)
type UUID [16]byte
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func GetUUID() (uuidHex string) {
uuid := NewUUID()
uuidHex = hex.EncodeToString(uuid[:])
return
}
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand2.Intn(len(letterBytes))]
}
return string(b)
}
func GetMD5Base64(bytes []byte) (base64Value string) {
md5Ctx := md5.New()
md5Ctx.Write(bytes)
md5Value := md5Ctx.Sum(nil)
base64Value = base64.StdEncoding.EncodeToString(md5Value)
return
}
func GetTimeInFormatISO8601() (timeStr string) {
gmt := time.FixedZone("GMT", 0)
return time.Now().In(gmt).Format("2006-01-02T15:04:05Z")
}
func GetTimeInFormatRFC2616() (timeStr string) {
gmt := time.FixedZone("GMT", 0)
return time.Now().In(gmt).Format("Mon, 02 Jan 2006 15:04:05 GMT")
}
func GetUrlFormedMap(source map[string]string) (urlEncoded string) {
urlEncoder := url.Values{}
for key, value := range source {
urlEncoder.Add(key, value)
}
urlEncoded = urlEncoder.Encode()
return
}
func InitStructWithDefaultTag(bean interface{}) {
configType := reflect.TypeOf(bean)
for i := 0; i < configType.Elem().NumField(); i++ {
field := configType.Elem().Field(i)
defaultValue := field.Tag.Get("default")
if defaultValue == "" {
continue
}
setter := reflect.ValueOf(bean).Elem().Field(i)
switch field.Type.String() {
case "int":
intValue, _ := strconv.ParseInt(defaultValue, 10, 64)
setter.SetInt(intValue)
case "time.Duration":
intValue, _ := strconv.ParseInt(defaultValue, 10, 64)
setter.SetInt(intValue)
case "string":
setter.SetString(defaultValue)
case "bool":
boolValue, _ := strconv.ParseBool(defaultValue)
setter.SetBool(boolValue)
}
}
}
func NewUUID() UUID {
ns := UUID{}
safeRandom(ns[:])
u := newFromHash(md5.New(), ns, RandStringBytes(16))
u[6] = (u[6] & 0x0f) | (byte(2) << 4)
u[8] = (u[8]&(0xff>>2) | (0x02 << 6))
return u
}
func newFromHash(h hash.Hash, ns UUID, name string) UUID {
u := UUID{}
h.Write(ns[:])
h.Write([]byte(name))
copy(u[:], h.Sum(nil))
return u
}
func safeRandom(dest []byte) {
if _, err := rand.Read(dest); err != nil {
panic(err)
}
}
func (u UUID) String() string {
buf := make([]byte, 36)
hex.Encode(buf[0:8], u[0:4])
buf[8] = '-'
hex.Encode(buf[9:13], u[4:6])
buf[13] = '-'
hex.Encode(buf[14:18], u[6:8])
buf[18] = '-'
hex.Encode(buf[19:23], u[8:10])
buf[23] = '-'
hex.Encode(buf[24:], u[10:])
return string(buf)
}

View File

@ -0,0 +1,109 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// AsymmetricDecrypt invokes the kms.AsymmetricDecrypt API synchronously
// api document: https://help.aliyun.com/api/kms/asymmetricdecrypt.html
func (client *Client) AsymmetricDecrypt(request *AsymmetricDecryptRequest) (response *AsymmetricDecryptResponse, err error) {
response = CreateAsymmetricDecryptResponse()
err = client.DoAction(request, response)
return
}
// AsymmetricDecryptWithChan invokes the kms.AsymmetricDecrypt API asynchronously
// api document: https://help.aliyun.com/api/kms/asymmetricdecrypt.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AsymmetricDecryptWithChan(request *AsymmetricDecryptRequest) (<-chan *AsymmetricDecryptResponse, <-chan error) {
responseChan := make(chan *AsymmetricDecryptResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.AsymmetricDecrypt(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// AsymmetricDecryptWithCallback invokes the kms.AsymmetricDecrypt API asynchronously
// api document: https://help.aliyun.com/api/kms/asymmetricdecrypt.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AsymmetricDecryptWithCallback(request *AsymmetricDecryptRequest, callback func(response *AsymmetricDecryptResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *AsymmetricDecryptResponse
var err error
defer close(result)
response, err = client.AsymmetricDecrypt(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// AsymmetricDecryptRequest is the request struct for api AsymmetricDecrypt
type AsymmetricDecryptRequest struct {
*requests.RpcRequest
KeyVersionId string `position:"Query" name:"KeyVersionId"`
KeyId string `position:"Query" name:"KeyId"`
CiphertextBlob string `position:"Query" name:"CiphertextBlob"`
Algorithm string `position:"Query" name:"Algorithm"`
}
// AsymmetricDecryptResponse is the response struct for api AsymmetricDecrypt
type AsymmetricDecryptResponse struct {
*responses.BaseResponse
Plaintext string `json:"Plaintext" xml:"Plaintext"`
KeyId string `json:"KeyId" xml:"KeyId"`
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersionId string `json:"KeyVersionId" xml:"KeyVersionId"`
}
// CreateAsymmetricDecryptRequest creates a request to invoke AsymmetricDecrypt API
func CreateAsymmetricDecryptRequest() (request *AsymmetricDecryptRequest) {
request = &AsymmetricDecryptRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "AsymmetricDecrypt", "kms", "openAPI")
return
}
// CreateAsymmetricDecryptResponse creates a response to parse from AsymmetricDecrypt response
func CreateAsymmetricDecryptResponse() (response *AsymmetricDecryptResponse) {
response = &AsymmetricDecryptResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// AsymmetricEncrypt invokes the kms.AsymmetricEncrypt API synchronously
// api document: https://help.aliyun.com/api/kms/asymmetricencrypt.html
func (client *Client) AsymmetricEncrypt(request *AsymmetricEncryptRequest) (response *AsymmetricEncryptResponse, err error) {
response = CreateAsymmetricEncryptResponse()
err = client.DoAction(request, response)
return
}
// AsymmetricEncryptWithChan invokes the kms.AsymmetricEncrypt API asynchronously
// api document: https://help.aliyun.com/api/kms/asymmetricencrypt.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AsymmetricEncryptWithChan(request *AsymmetricEncryptRequest) (<-chan *AsymmetricEncryptResponse, <-chan error) {
responseChan := make(chan *AsymmetricEncryptResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.AsymmetricEncrypt(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// AsymmetricEncryptWithCallback invokes the kms.AsymmetricEncrypt API asynchronously
// api document: https://help.aliyun.com/api/kms/asymmetricencrypt.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AsymmetricEncryptWithCallback(request *AsymmetricEncryptRequest, callback func(response *AsymmetricEncryptResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *AsymmetricEncryptResponse
var err error
defer close(result)
response, err = client.AsymmetricEncrypt(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// AsymmetricEncryptRequest is the request struct for api AsymmetricEncrypt
type AsymmetricEncryptRequest struct {
*requests.RpcRequest
KeyVersionId string `position:"Query" name:"KeyVersionId"`
KeyId string `position:"Query" name:"KeyId"`
Plaintext string `position:"Query" name:"Plaintext"`
Algorithm string `position:"Query" name:"Algorithm"`
}
// AsymmetricEncryptResponse is the response struct for api AsymmetricEncrypt
type AsymmetricEncryptResponse struct {
*responses.BaseResponse
CiphertextBlob string `json:"CiphertextBlob" xml:"CiphertextBlob"`
KeyId string `json:"KeyId" xml:"KeyId"`
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersionId string `json:"KeyVersionId" xml:"KeyVersionId"`
}
// CreateAsymmetricEncryptRequest creates a request to invoke AsymmetricEncrypt API
func CreateAsymmetricEncryptRequest() (request *AsymmetricEncryptRequest) {
request = &AsymmetricEncryptRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "AsymmetricEncrypt", "kms", "openAPI")
return
}
// CreateAsymmetricEncryptResponse creates a response to parse from AsymmetricEncrypt response
func CreateAsymmetricEncryptResponse() (response *AsymmetricEncryptResponse) {
response = &AsymmetricEncryptResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// AsymmetricSign invokes the kms.AsymmetricSign API synchronously
// api document: https://help.aliyun.com/api/kms/asymmetricsign.html
func (client *Client) AsymmetricSign(request *AsymmetricSignRequest) (response *AsymmetricSignResponse, err error) {
response = CreateAsymmetricSignResponse()
err = client.DoAction(request, response)
return
}
// AsymmetricSignWithChan invokes the kms.AsymmetricSign API asynchronously
// api document: https://help.aliyun.com/api/kms/asymmetricsign.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AsymmetricSignWithChan(request *AsymmetricSignRequest) (<-chan *AsymmetricSignResponse, <-chan error) {
responseChan := make(chan *AsymmetricSignResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.AsymmetricSign(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// AsymmetricSignWithCallback invokes the kms.AsymmetricSign API asynchronously
// api document: https://help.aliyun.com/api/kms/asymmetricsign.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AsymmetricSignWithCallback(request *AsymmetricSignRequest, callback func(response *AsymmetricSignResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *AsymmetricSignResponse
var err error
defer close(result)
response, err = client.AsymmetricSign(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// AsymmetricSignRequest is the request struct for api AsymmetricSign
type AsymmetricSignRequest struct {
*requests.RpcRequest
KeyVersionId string `position:"Query" name:"KeyVersionId"`
Digest string `position:"Query" name:"Digest"`
KeyId string `position:"Query" name:"KeyId"`
Algorithm string `position:"Query" name:"Algorithm"`
}
// AsymmetricSignResponse is the response struct for api AsymmetricSign
type AsymmetricSignResponse struct {
*responses.BaseResponse
Value string `json:"Value" xml:"Value"`
KeyId string `json:"KeyId" xml:"KeyId"`
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersionId string `json:"KeyVersionId" xml:"KeyVersionId"`
}
// CreateAsymmetricSignRequest creates a request to invoke AsymmetricSign API
func CreateAsymmetricSignRequest() (request *AsymmetricSignRequest) {
request = &AsymmetricSignRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "AsymmetricSign", "kms", "openAPI")
return
}
// CreateAsymmetricSignResponse creates a response to parse from AsymmetricSign response
func CreateAsymmetricSignResponse() (response *AsymmetricSignResponse) {
response = &AsymmetricSignResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,110 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// AsymmetricVerify invokes the kms.AsymmetricVerify API synchronously
// api document: https://help.aliyun.com/api/kms/asymmetricverify.html
func (client *Client) AsymmetricVerify(request *AsymmetricVerifyRequest) (response *AsymmetricVerifyResponse, err error) {
response = CreateAsymmetricVerifyResponse()
err = client.DoAction(request, response)
return
}
// AsymmetricVerifyWithChan invokes the kms.AsymmetricVerify API asynchronously
// api document: https://help.aliyun.com/api/kms/asymmetricverify.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AsymmetricVerifyWithChan(request *AsymmetricVerifyRequest) (<-chan *AsymmetricVerifyResponse, <-chan error) {
responseChan := make(chan *AsymmetricVerifyResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.AsymmetricVerify(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// AsymmetricVerifyWithCallback invokes the kms.AsymmetricVerify API asynchronously
// api document: https://help.aliyun.com/api/kms/asymmetricverify.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) AsymmetricVerifyWithCallback(request *AsymmetricVerifyRequest, callback func(response *AsymmetricVerifyResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *AsymmetricVerifyResponse
var err error
defer close(result)
response, err = client.AsymmetricVerify(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// AsymmetricVerifyRequest is the request struct for api AsymmetricVerify
type AsymmetricVerifyRequest struct {
*requests.RpcRequest
KeyVersionId string `position:"Query" name:"KeyVersionId"`
Digest string `position:"Query" name:"Digest"`
KeyId string `position:"Query" name:"KeyId"`
Value string `position:"Query" name:"Value"`
Algorithm string `position:"Query" name:"Algorithm"`
}
// AsymmetricVerifyResponse is the response struct for api AsymmetricVerify
type AsymmetricVerifyResponse struct {
*responses.BaseResponse
Value bool `json:"Value" xml:"Value"`
KeyId string `json:"KeyId" xml:"KeyId"`
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersionId string `json:"KeyVersionId" xml:"KeyVersionId"`
}
// CreateAsymmetricVerifyRequest creates a request to invoke AsymmetricVerify API
func CreateAsymmetricVerifyRequest() (request *AsymmetricVerifyRequest) {
request = &AsymmetricVerifyRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "AsymmetricVerify", "kms", "openAPI")
return
}
// CreateAsymmetricVerifyResponse creates a response to parse from AsymmetricVerify response
func CreateAsymmetricVerifyResponse() (response *AsymmetricVerifyResponse) {
response = &AsymmetricVerifyResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CancelKeyDeletion invokes the kms.CancelKeyDeletion API synchronously
// api document: https://help.aliyun.com/api/kms/cancelkeydeletion.html
func (client *Client) CancelKeyDeletion(request *CancelKeyDeletionRequest) (response *CancelKeyDeletionResponse, err error) {
response = CreateCancelKeyDeletionResponse()
err = client.DoAction(request, response)
return
}
// CancelKeyDeletionWithChan invokes the kms.CancelKeyDeletion API asynchronously
// api document: https://help.aliyun.com/api/kms/cancelkeydeletion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CancelKeyDeletionWithChan(request *CancelKeyDeletionRequest) (<-chan *CancelKeyDeletionResponse, <-chan error) {
responseChan := make(chan *CancelKeyDeletionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CancelKeyDeletion(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CancelKeyDeletionWithCallback invokes the kms.CancelKeyDeletion API asynchronously
// api document: https://help.aliyun.com/api/kms/cancelkeydeletion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CancelKeyDeletionWithCallback(request *CancelKeyDeletionRequest, callback func(response *CancelKeyDeletionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CancelKeyDeletionResponse
var err error
defer close(result)
response, err = client.CancelKeyDeletion(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CancelKeyDeletionRequest is the request struct for api CancelKeyDeletion
type CancelKeyDeletionRequest struct {
*requests.RpcRequest
KeyId string `position:"Query" name:"KeyId"`
}
// CancelKeyDeletionResponse is the response struct for api CancelKeyDeletion
type CancelKeyDeletionResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateCancelKeyDeletionRequest creates a request to invoke CancelKeyDeletion API
func CreateCancelKeyDeletionRequest() (request *CancelKeyDeletionRequest) {
request = &CancelKeyDeletionRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "CancelKeyDeletion", "kms", "openAPI")
return
}
// CreateCancelKeyDeletionResponse creates a response to parse from CancelKeyDeletion response
func CreateCancelKeyDeletionResponse() (response *CancelKeyDeletionResponse) {
response = &CancelKeyDeletionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,129 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"reflect"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
)
// Client is the sdk client struct, each func corresponds to an OpenAPI
type Client struct {
sdk.Client
}
// SetClientProperty Set Property by Reflect
func SetClientProperty(client *Client, propertyName string, propertyValue interface{}) {
v := reflect.ValueOf(client).Elem()
if v.FieldByName(propertyName).IsValid() && v.FieldByName(propertyName).CanSet() {
v.FieldByName(propertyName).Set(reflect.ValueOf(propertyValue))
}
}
// SetEndpointDataToClient Set EndpointMap and ENdpointType
func SetEndpointDataToClient(client *Client) {
SetClientProperty(client, "EndpointMap", GetEndpointMap())
SetClientProperty(client, "EndpointType", GetEndpointType())
}
// NewClient creates a sdk client with environment variables
func NewClient() (client *Client, err error) {
client = &Client{}
err = client.Init()
SetEndpointDataToClient(client)
return
}
// NewClientWithProvider creates a sdk client with providers
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) {
client = &Client{}
var pc provider.Provider
if len(providers) == 0 {
pc = provider.DefaultChain
} else {
pc = provider.NewProviderChain(providers)
}
err = client.InitWithProviderChain(regionId, pc)
SetEndpointDataToClient(client)
return
}
// NewClientWithOptions creates a sdk client with regionId/sdkConfig/credential
// this is the common api to create a sdk client
func NewClientWithOptions(regionId string, config *sdk.Config, credential auth.Credential) (client *Client, err error) {
client = &Client{}
err = client.InitWithOptions(regionId, config, credential)
SetEndpointDataToClient(client)
return
}
// NewClientWithAccessKey is a shortcut to create sdk client with accesskey
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
client = &Client{}
err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
SetEndpointDataToClient(client)
return
}
// NewClientWithStsToken is a shortcut to create sdk client with sts token
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
SetEndpointDataToClient(client)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
SetEndpointDataToClient(client)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn and policy
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
SetEndpointDataToClient(client)
return
}
// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithEcsRamRole(regionId, roleName)
SetEndpointDataToClient(client)
return
}
// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
client = &Client{}
err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
SetEndpointDataToClient(client)
return
}

View File

@ -0,0 +1,104 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateAlias invokes the kms.CreateAlias API synchronously
// api document: https://help.aliyun.com/api/kms/createalias.html
func (client *Client) CreateAlias(request *CreateAliasRequest) (response *CreateAliasResponse, err error) {
response = CreateCreateAliasResponse()
err = client.DoAction(request, response)
return
}
// CreateAliasWithChan invokes the kms.CreateAlias API asynchronously
// api document: https://help.aliyun.com/api/kms/createalias.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateAliasWithChan(request *CreateAliasRequest) (<-chan *CreateAliasResponse, <-chan error) {
responseChan := make(chan *CreateAliasResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateAlias(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateAliasWithCallback invokes the kms.CreateAlias API asynchronously
// api document: https://help.aliyun.com/api/kms/createalias.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateAliasWithCallback(request *CreateAliasRequest, callback func(response *CreateAliasResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateAliasResponse
var err error
defer close(result)
response, err = client.CreateAlias(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateAliasRequest is the request struct for api CreateAlias
type CreateAliasRequest struct {
*requests.RpcRequest
AliasName string `position:"Query" name:"AliasName"`
KeyId string `position:"Query" name:"KeyId"`
}
// CreateAliasResponse is the response struct for api CreateAlias
type CreateAliasResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateCreateAliasRequest creates a request to invoke CreateAlias API
func CreateCreateAliasRequest() (request *CreateAliasRequest) {
request = &CreateAliasRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "CreateAlias", "kms", "openAPI")
return
}
// CreateCreateAliasResponse creates a response to parse from CreateAlias response
func CreateCreateAliasResponse() (response *CreateAliasResponse) {
response = &CreateAliasResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,110 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateKey invokes the kms.CreateKey API synchronously
// api document: https://help.aliyun.com/api/kms/createkey.html
func (client *Client) CreateKey(request *CreateKeyRequest) (response *CreateKeyResponse, err error) {
response = CreateCreateKeyResponse()
err = client.DoAction(request, response)
return
}
// CreateKeyWithChan invokes the kms.CreateKey API asynchronously
// api document: https://help.aliyun.com/api/kms/createkey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateKeyWithChan(request *CreateKeyRequest) (<-chan *CreateKeyResponse, <-chan error) {
responseChan := make(chan *CreateKeyResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateKey(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateKeyWithCallback invokes the kms.CreateKey API asynchronously
// api document: https://help.aliyun.com/api/kms/createkey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateKeyWithCallback(request *CreateKeyRequest, callback func(response *CreateKeyResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateKeyResponse
var err error
defer close(result)
response, err = client.CreateKey(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateKeyRequest is the request struct for api CreateKey
type CreateKeyRequest struct {
*requests.RpcRequest
ProtectionLevel string `position:"Query" name:"ProtectionLevel"`
KeyUsage string `position:"Query" name:"KeyUsage"`
Origin string `position:"Query" name:"Origin"`
Description string `position:"Query" name:"Description"`
KeySpec string `position:"Query" name:"KeySpec"`
RotationInterval string `position:"Query" name:"RotationInterval"`
EnableAutomaticRotation requests.Boolean `position:"Query" name:"EnableAutomaticRotation"`
}
// CreateKeyResponse is the response struct for api CreateKey
type CreateKeyResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
KeyMetadata KeyMetadata `json:"KeyMetadata" xml:"KeyMetadata"`
}
// CreateCreateKeyRequest creates a request to invoke CreateKey API
func CreateCreateKeyRequest() (request *CreateKeyRequest) {
request = &CreateKeyRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "CreateKey", "kms", "openAPI")
return
}
// CreateCreateKeyResponse creates a response to parse from CreateKey response
func CreateCreateKeyResponse() (response *CreateKeyResponse) {
response = &CreateKeyResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateKeyVersion invokes the kms.CreateKeyVersion API synchronously
// api document: https://help.aliyun.com/api/kms/createkeyversion.html
func (client *Client) CreateKeyVersion(request *CreateKeyVersionRequest) (response *CreateKeyVersionResponse, err error) {
response = CreateCreateKeyVersionResponse()
err = client.DoAction(request, response)
return
}
// CreateKeyVersionWithChan invokes the kms.CreateKeyVersion API asynchronously
// api document: https://help.aliyun.com/api/kms/createkeyversion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateKeyVersionWithChan(request *CreateKeyVersionRequest) (<-chan *CreateKeyVersionResponse, <-chan error) {
responseChan := make(chan *CreateKeyVersionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateKeyVersion(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateKeyVersionWithCallback invokes the kms.CreateKeyVersion API asynchronously
// api document: https://help.aliyun.com/api/kms/createkeyversion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateKeyVersionWithCallback(request *CreateKeyVersionRequest, callback func(response *CreateKeyVersionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateKeyVersionResponse
var err error
defer close(result)
response, err = client.CreateKeyVersion(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateKeyVersionRequest is the request struct for api CreateKeyVersion
type CreateKeyVersionRequest struct {
*requests.RpcRequest
KeyId string `position:"Query" name:"KeyId"`
}
// CreateKeyVersionResponse is the response struct for api CreateKeyVersion
type CreateKeyVersionResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersion KeyVersion `json:"KeyVersion" xml:"KeyVersion"`
}
// CreateCreateKeyVersionRequest creates a request to invoke CreateKeyVersion API
func CreateCreateKeyVersionRequest() (request *CreateKeyVersionRequest) {
request = &CreateKeyVersionRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "CreateKeyVersion", "kms", "openAPI")
return
}
// CreateCreateKeyVersionResponse creates a response to parse from CreateKeyVersion response
func CreateCreateKeyVersionResponse() (response *CreateKeyVersionResponse) {
response = &CreateKeyVersionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,112 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// CreateSecret invokes the kms.CreateSecret API synchronously
// api document: https://help.aliyun.com/api/kms/createsecret.html
func (client *Client) CreateSecret(request *CreateSecretRequest) (response *CreateSecretResponse, err error) {
response = CreateCreateSecretResponse()
err = client.DoAction(request, response)
return
}
// CreateSecretWithChan invokes the kms.CreateSecret API asynchronously
// api document: https://help.aliyun.com/api/kms/createsecret.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateSecretWithChan(request *CreateSecretRequest) (<-chan *CreateSecretResponse, <-chan error) {
responseChan := make(chan *CreateSecretResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateSecret(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateSecretWithCallback invokes the kms.CreateSecret API asynchronously
// api document: https://help.aliyun.com/api/kms/createsecret.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateSecretWithCallback(request *CreateSecretRequest, callback func(response *CreateSecretResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateSecretResponse
var err error
defer close(result)
response, err = client.CreateSecret(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateSecretRequest is the request struct for api CreateSecret
type CreateSecretRequest struct {
*requests.RpcRequest
VersionId string `position:"Query" name:"VersionId"`
SecretData string `position:"Query" name:"SecretData"`
Description string `position:"Query" name:"Description"`
SecretName string `position:"Query" name:"SecretName"`
EncryptionKeyId string `position:"Query" name:"EncryptionKeyId"`
SecretDataType string `position:"Query" name:"SecretDataType"`
Tags string `position:"Query" name:"Tags"`
}
// CreateSecretResponse is the response struct for api CreateSecret
type CreateSecretResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
Arn string `json:"Arn" xml:"Arn"`
VersionId string `json:"VersionId" xml:"VersionId"`
SecretName string `json:"SecretName" xml:"SecretName"`
}
// CreateCreateSecretRequest creates a request to invoke CreateSecret API
func CreateCreateSecretRequest() (request *CreateSecretRequest) {
request = &CreateSecretRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "CreateSecret", "kms", "openAPI")
return
}
// CreateCreateSecretResponse creates a response to parse from CreateSecret response
func CreateCreateSecretResponse() (response *CreateSecretResponse) {
response = &CreateSecretResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,107 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// Decrypt invokes the kms.Decrypt API synchronously
// api document: https://help.aliyun.com/api/kms/decrypt.html
func (client *Client) Decrypt(request *DecryptRequest) (response *DecryptResponse, err error) {
response = CreateDecryptResponse()
err = client.DoAction(request, response)
return
}
// DecryptWithChan invokes the kms.Decrypt API asynchronously
// api document: https://help.aliyun.com/api/kms/decrypt.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DecryptWithChan(request *DecryptRequest) (<-chan *DecryptResponse, <-chan error) {
responseChan := make(chan *DecryptResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.Decrypt(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DecryptWithCallback invokes the kms.Decrypt API asynchronously
// api document: https://help.aliyun.com/api/kms/decrypt.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DecryptWithCallback(request *DecryptRequest, callback func(response *DecryptResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DecryptResponse
var err error
defer close(result)
response, err = client.Decrypt(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DecryptRequest is the request struct for api Decrypt
type DecryptRequest struct {
*requests.RpcRequest
EncryptionContext string `position:"Query" name:"EncryptionContext"`
CiphertextBlob string `position:"Query" name:"CiphertextBlob"`
}
// DecryptResponse is the response struct for api Decrypt
type DecryptResponse struct {
*responses.BaseResponse
Plaintext string `json:"Plaintext" xml:"Plaintext"`
KeyId string `json:"KeyId" xml:"KeyId"`
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersionId string `json:"KeyVersionId" xml:"KeyVersionId"`
}
// CreateDecryptRequest creates a request to invoke Decrypt API
func CreateDecryptRequest() (request *DecryptRequest) {
request = &DecryptRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "Decrypt", "kms", "openAPI")
return
}
// CreateDecryptResponse creates a response to parse from Decrypt response
func CreateDecryptResponse() (response *DecryptResponse) {
response = &DecryptResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteAlias invokes the kms.DeleteAlias API synchronously
// api document: https://help.aliyun.com/api/kms/deletealias.html
func (client *Client) DeleteAlias(request *DeleteAliasRequest) (response *DeleteAliasResponse, err error) {
response = CreateDeleteAliasResponse()
err = client.DoAction(request, response)
return
}
// DeleteAliasWithChan invokes the kms.DeleteAlias API asynchronously
// api document: https://help.aliyun.com/api/kms/deletealias.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteAliasWithChan(request *DeleteAliasRequest) (<-chan *DeleteAliasResponse, <-chan error) {
responseChan := make(chan *DeleteAliasResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteAlias(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteAliasWithCallback invokes the kms.DeleteAlias API asynchronously
// api document: https://help.aliyun.com/api/kms/deletealias.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteAliasWithCallback(request *DeleteAliasRequest, callback func(response *DeleteAliasResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteAliasResponse
var err error
defer close(result)
response, err = client.DeleteAlias(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteAliasRequest is the request struct for api DeleteAlias
type DeleteAliasRequest struct {
*requests.RpcRequest
AliasName string `position:"Query" name:"AliasName"`
}
// DeleteAliasResponse is the response struct for api DeleteAlias
type DeleteAliasResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteAliasRequest creates a request to invoke DeleteAlias API
func CreateDeleteAliasRequest() (request *DeleteAliasRequest) {
request = &DeleteAliasRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "DeleteAlias", "kms", "openAPI")
return
}
// CreateDeleteAliasResponse creates a response to parse from DeleteAlias response
func CreateDeleteAliasResponse() (response *DeleteAliasResponse) {
response = &DeleteAliasResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteKeyMaterial invokes the kms.DeleteKeyMaterial API synchronously
// api document: https://help.aliyun.com/api/kms/deletekeymaterial.html
func (client *Client) DeleteKeyMaterial(request *DeleteKeyMaterialRequest) (response *DeleteKeyMaterialResponse, err error) {
response = CreateDeleteKeyMaterialResponse()
err = client.DoAction(request, response)
return
}
// DeleteKeyMaterialWithChan invokes the kms.DeleteKeyMaterial API asynchronously
// api document: https://help.aliyun.com/api/kms/deletekeymaterial.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteKeyMaterialWithChan(request *DeleteKeyMaterialRequest) (<-chan *DeleteKeyMaterialResponse, <-chan error) {
responseChan := make(chan *DeleteKeyMaterialResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteKeyMaterial(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteKeyMaterialWithCallback invokes the kms.DeleteKeyMaterial API asynchronously
// api document: https://help.aliyun.com/api/kms/deletekeymaterial.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteKeyMaterialWithCallback(request *DeleteKeyMaterialRequest, callback func(response *DeleteKeyMaterialResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteKeyMaterialResponse
var err error
defer close(result)
response, err = client.DeleteKeyMaterial(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteKeyMaterialRequest is the request struct for api DeleteKeyMaterial
type DeleteKeyMaterialRequest struct {
*requests.RpcRequest
KeyId string `position:"Query" name:"KeyId"`
}
// DeleteKeyMaterialResponse is the response struct for api DeleteKeyMaterial
type DeleteKeyMaterialResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDeleteKeyMaterialRequest creates a request to invoke DeleteKeyMaterial API
func CreateDeleteKeyMaterialRequest() (request *DeleteKeyMaterialRequest) {
request = &DeleteKeyMaterialRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "DeleteKeyMaterial", "kms", "openAPI")
return
}
// CreateDeleteKeyMaterialResponse creates a response to parse from DeleteKeyMaterial response
func CreateDeleteKeyMaterialResponse() (response *DeleteKeyMaterialResponse) {
response = &DeleteKeyMaterialResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,107 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DeleteSecret invokes the kms.DeleteSecret API synchronously
// api document: https://help.aliyun.com/api/kms/deletesecret.html
func (client *Client) DeleteSecret(request *DeleteSecretRequest) (response *DeleteSecretResponse, err error) {
response = CreateDeleteSecretResponse()
err = client.DoAction(request, response)
return
}
// DeleteSecretWithChan invokes the kms.DeleteSecret API asynchronously
// api document: https://help.aliyun.com/api/kms/deletesecret.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteSecretWithChan(request *DeleteSecretRequest) (<-chan *DeleteSecretResponse, <-chan error) {
responseChan := make(chan *DeleteSecretResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteSecret(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteSecretWithCallback invokes the kms.DeleteSecret API asynchronously
// api document: https://help.aliyun.com/api/kms/deletesecret.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteSecretWithCallback(request *DeleteSecretRequest, callback func(response *DeleteSecretResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteSecretResponse
var err error
defer close(result)
response, err = client.DeleteSecret(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteSecretRequest is the request struct for api DeleteSecret
type DeleteSecretRequest struct {
*requests.RpcRequest
ForceDeleteWithoutRecovery string `position:"Query" name:"ForceDeleteWithoutRecovery"`
RecoveryWindowInDays string `position:"Query" name:"RecoveryWindowInDays"`
SecretName string `position:"Query" name:"SecretName"`
}
// DeleteSecretResponse is the response struct for api DeleteSecret
type DeleteSecretResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
SecretName string `json:"SecretName" xml:"SecretName"`
PlannedDeleteTime string `json:"PlannedDeleteTime" xml:"PlannedDeleteTime"`
}
// CreateDeleteSecretRequest creates a request to invoke DeleteSecret API
func CreateDeleteSecretRequest() (request *DeleteSecretRequest) {
request = &DeleteSecretRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "DeleteSecret", "kms", "openAPI")
return
}
// CreateDeleteSecretResponse creates a response to parse from DeleteSecret response
func CreateDeleteSecretResponse() (response *DeleteSecretResponse) {
response = &DeleteSecretResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeKey invokes the kms.DescribeKey API synchronously
// api document: https://help.aliyun.com/api/kms/describekey.html
func (client *Client) DescribeKey(request *DescribeKeyRequest) (response *DescribeKeyResponse, err error) {
response = CreateDescribeKeyResponse()
err = client.DoAction(request, response)
return
}
// DescribeKeyWithChan invokes the kms.DescribeKey API asynchronously
// api document: https://help.aliyun.com/api/kms/describekey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeKeyWithChan(request *DescribeKeyRequest) (<-chan *DescribeKeyResponse, <-chan error) {
responseChan := make(chan *DescribeKeyResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeKey(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeKeyWithCallback invokes the kms.DescribeKey API asynchronously
// api document: https://help.aliyun.com/api/kms/describekey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeKeyWithCallback(request *DescribeKeyRequest, callback func(response *DescribeKeyResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeKeyResponse
var err error
defer close(result)
response, err = client.DescribeKey(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeKeyRequest is the request struct for api DescribeKey
type DescribeKeyRequest struct {
*requests.RpcRequest
KeyId string `position:"Query" name:"KeyId"`
}
// DescribeKeyResponse is the response struct for api DescribeKey
type DescribeKeyResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
KeyMetadata KeyMetadata `json:"KeyMetadata" xml:"KeyMetadata"`
}
// CreateDescribeKeyRequest creates a request to invoke DescribeKey API
func CreateDescribeKeyRequest() (request *DescribeKeyRequest) {
request = &DescribeKeyRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "DescribeKey", "kms", "openAPI")
return
}
// CreateDescribeKeyResponse creates a response to parse from DescribeKey response
func CreateDescribeKeyResponse() (response *DescribeKeyResponse) {
response = &DescribeKeyResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeKeyVersion invokes the kms.DescribeKeyVersion API synchronously
// api document: https://help.aliyun.com/api/kms/describekeyversion.html
func (client *Client) DescribeKeyVersion(request *DescribeKeyVersionRequest) (response *DescribeKeyVersionResponse, err error) {
response = CreateDescribeKeyVersionResponse()
err = client.DoAction(request, response)
return
}
// DescribeKeyVersionWithChan invokes the kms.DescribeKeyVersion API asynchronously
// api document: https://help.aliyun.com/api/kms/describekeyversion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeKeyVersionWithChan(request *DescribeKeyVersionRequest) (<-chan *DescribeKeyVersionResponse, <-chan error) {
responseChan := make(chan *DescribeKeyVersionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeKeyVersion(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeKeyVersionWithCallback invokes the kms.DescribeKeyVersion API asynchronously
// api document: https://help.aliyun.com/api/kms/describekeyversion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeKeyVersionWithCallback(request *DescribeKeyVersionRequest, callback func(response *DescribeKeyVersionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeKeyVersionResponse
var err error
defer close(result)
response, err = client.DescribeKeyVersion(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeKeyVersionRequest is the request struct for api DescribeKeyVersion
type DescribeKeyVersionRequest struct {
*requests.RpcRequest
KeyVersionId string `position:"Query" name:"KeyVersionId"`
KeyId string `position:"Query" name:"KeyId"`
}
// DescribeKeyVersionResponse is the response struct for api DescribeKeyVersion
type DescribeKeyVersionResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersion KeyVersion `json:"KeyVersion" xml:"KeyVersion"`
}
// CreateDescribeKeyVersionRequest creates a request to invoke DescribeKeyVersion API
func CreateDescribeKeyVersionRequest() (request *DescribeKeyVersionRequest) {
request = &DescribeKeyVersionRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "DescribeKeyVersion", "kms", "openAPI")
return
}
// CreateDescribeKeyVersionResponse creates a response to parse from DescribeKeyVersion response
func CreateDescribeKeyVersionResponse() (response *DescribeKeyVersionResponse) {
response = &DescribeKeyVersionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeRegions invokes the kms.DescribeRegions API synchronously
// api document: https://help.aliyun.com/api/kms/describeregions.html
func (client *Client) DescribeRegions(request *DescribeRegionsRequest) (response *DescribeRegionsResponse, err error) {
response = CreateDescribeRegionsResponse()
err = client.DoAction(request, response)
return
}
// DescribeRegionsWithChan invokes the kms.DescribeRegions API asynchronously
// api document: https://help.aliyun.com/api/kms/describeregions.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeRegionsWithChan(request *DescribeRegionsRequest) (<-chan *DescribeRegionsResponse, <-chan error) {
responseChan := make(chan *DescribeRegionsResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeRegions(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeRegionsWithCallback invokes the kms.DescribeRegions API asynchronously
// api document: https://help.aliyun.com/api/kms/describeregions.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeRegionsWithCallback(request *DescribeRegionsRequest, callback func(response *DescribeRegionsResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeRegionsResponse
var err error
defer close(result)
response, err = client.DescribeRegions(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeRegionsRequest is the request struct for api DescribeRegions
type DescribeRegionsRequest struct {
*requests.RpcRequest
}
// DescribeRegionsResponse is the response struct for api DescribeRegions
type DescribeRegionsResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
Regions Regions `json:"Regions" xml:"Regions"`
}
// CreateDescribeRegionsRequest creates a request to invoke DescribeRegions API
func CreateDescribeRegionsRequest() (request *DescribeRegionsRequest) {
request = &DescribeRegionsRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "DescribeRegions", "kms", "openAPI")
return
}
// CreateDescribeRegionsResponse creates a response to parse from DescribeRegions response
func CreateDescribeRegionsResponse() (response *DescribeRegionsResponse) {
response = &DescribeRegionsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,112 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeSecret invokes the kms.DescribeSecret API synchronously
// api document: https://help.aliyun.com/api/kms/describesecret.html
func (client *Client) DescribeSecret(request *DescribeSecretRequest) (response *DescribeSecretResponse, err error) {
response = CreateDescribeSecretResponse()
err = client.DoAction(request, response)
return
}
// DescribeSecretWithChan invokes the kms.DescribeSecret API asynchronously
// api document: https://help.aliyun.com/api/kms/describesecret.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeSecretWithChan(request *DescribeSecretRequest) (<-chan *DescribeSecretResponse, <-chan error) {
responseChan := make(chan *DescribeSecretResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeSecret(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeSecretWithCallback invokes the kms.DescribeSecret API asynchronously
// api document: https://help.aliyun.com/api/kms/describesecret.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeSecretWithCallback(request *DescribeSecretRequest, callback func(response *DescribeSecretResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeSecretResponse
var err error
defer close(result)
response, err = client.DescribeSecret(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeSecretRequest is the request struct for api DescribeSecret
type DescribeSecretRequest struct {
*requests.RpcRequest
SecretName string `position:"Query" name:"SecretName"`
FetchTags string `position:"Query" name:"FetchTags"`
}
// DescribeSecretResponse is the response struct for api DescribeSecret
type DescribeSecretResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
Arn string `json:"Arn" xml:"Arn"`
SecretName string `json:"SecretName" xml:"SecretName"`
EncryptionKeyId string `json:"EncryptionKeyId" xml:"EncryptionKeyId"`
Description string `json:"Description" xml:"Description"`
CreateTime string `json:"CreateTime" xml:"CreateTime"`
UpdateTime string `json:"UpdateTime" xml:"UpdateTime"`
PlannedDeleteTime string `json:"PlannedDeleteTime" xml:"PlannedDeleteTime"`
Tags []Tag `json:"Tags" xml:"Tags"`
}
// CreateDescribeSecretRequest creates a request to invoke DescribeSecret API
func CreateDescribeSecretRequest() (request *DescribeSecretRequest) {
request = &DescribeSecretRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "DescribeSecret", "kms", "openAPI")
return
}
// CreateDescribeSecretResponse creates a response to parse from DescribeSecret response
func CreateDescribeSecretResponse() (response *DescribeSecretResponse) {
response = &DescribeSecretResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DescribeService invokes the kms.DescribeService API synchronously
// api document: https://help.aliyun.com/api/kms/describeservice.html
func (client *Client) DescribeService(request *DescribeServiceRequest) (response *DescribeServiceResponse, err error) {
response = CreateDescribeServiceResponse()
err = client.DoAction(request, response)
return
}
// DescribeServiceWithChan invokes the kms.DescribeService API asynchronously
// api document: https://help.aliyun.com/api/kms/describeservice.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeServiceWithChan(request *DescribeServiceRequest) (<-chan *DescribeServiceResponse, <-chan error) {
responseChan := make(chan *DescribeServiceResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DescribeService(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DescribeServiceWithCallback invokes the kms.DescribeService API asynchronously
// api document: https://help.aliyun.com/api/kms/describeservice.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeServiceWithCallback(request *DescribeServiceRequest, callback func(response *DescribeServiceResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DescribeServiceResponse
var err error
defer close(result)
response, err = client.DescribeService(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DescribeServiceRequest is the request struct for api DescribeService
type DescribeServiceRequest struct {
*requests.RpcRequest
}
// DescribeServiceResponse is the response struct for api DescribeService
type DescribeServiceResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
ProtectionLevels ProtectionLevels `json:"ProtectionLevels" xml:"ProtectionLevels"`
KeySpecs KeySpecs `json:"KeySpecs" xml:"KeySpecs"`
}
// CreateDescribeServiceRequest creates a request to invoke DescribeService API
func CreateDescribeServiceRequest() (request *DescribeServiceRequest) {
request = &DescribeServiceRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "DescribeService", "kms", "openAPI")
return
}
// CreateDescribeServiceResponse creates a response to parse from DescribeService response
func CreateDescribeServiceResponse() (response *DescribeServiceResponse) {
response = &DescribeServiceResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// DisableKey invokes the kms.DisableKey API synchronously
// api document: https://help.aliyun.com/api/kms/disablekey.html
func (client *Client) DisableKey(request *DisableKeyRequest) (response *DisableKeyResponse, err error) {
response = CreateDisableKeyResponse()
err = client.DoAction(request, response)
return
}
// DisableKeyWithChan invokes the kms.DisableKey API asynchronously
// api document: https://help.aliyun.com/api/kms/disablekey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DisableKeyWithChan(request *DisableKeyRequest) (<-chan *DisableKeyResponse, <-chan error) {
responseChan := make(chan *DisableKeyResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DisableKey(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DisableKeyWithCallback invokes the kms.DisableKey API asynchronously
// api document: https://help.aliyun.com/api/kms/disablekey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DisableKeyWithCallback(request *DisableKeyRequest, callback func(response *DisableKeyResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DisableKeyResponse
var err error
defer close(result)
response, err = client.DisableKey(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DisableKeyRequest is the request struct for api DisableKey
type DisableKeyRequest struct {
*requests.RpcRequest
KeyId string `position:"Query" name:"KeyId"`
}
// DisableKeyResponse is the response struct for api DisableKey
type DisableKeyResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateDisableKeyRequest creates a request to invoke DisableKey API
func CreateDisableKeyRequest() (request *DisableKeyRequest) {
request = &DisableKeyRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "DisableKey", "kms", "openAPI")
return
}
// CreateDisableKeyResponse creates a response to parse from DisableKey response
func CreateDisableKeyResponse() (response *DisableKeyResponse) {
response = &DisableKeyResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// EnableKey invokes the kms.EnableKey API synchronously
// api document: https://help.aliyun.com/api/kms/enablekey.html
func (client *Client) EnableKey(request *EnableKeyRequest) (response *EnableKeyResponse, err error) {
response = CreateEnableKeyResponse()
err = client.DoAction(request, response)
return
}
// EnableKeyWithChan invokes the kms.EnableKey API asynchronously
// api document: https://help.aliyun.com/api/kms/enablekey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) EnableKeyWithChan(request *EnableKeyRequest) (<-chan *EnableKeyResponse, <-chan error) {
responseChan := make(chan *EnableKeyResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.EnableKey(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// EnableKeyWithCallback invokes the kms.EnableKey API asynchronously
// api document: https://help.aliyun.com/api/kms/enablekey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) EnableKeyWithCallback(request *EnableKeyRequest, callback func(response *EnableKeyResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *EnableKeyResponse
var err error
defer close(result)
response, err = client.EnableKey(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// EnableKeyRequest is the request struct for api EnableKey
type EnableKeyRequest struct {
*requests.RpcRequest
KeyId string `position:"Query" name:"KeyId"`
}
// EnableKeyResponse is the response struct for api EnableKey
type EnableKeyResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateEnableKeyRequest creates a request to invoke EnableKey API
func CreateEnableKeyRequest() (request *EnableKeyRequest) {
request = &EnableKeyRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "EnableKey", "kms", "openAPI")
return
}
// CreateEnableKeyResponse creates a response to parse from EnableKey response
func CreateEnableKeyResponse() (response *EnableKeyResponse) {
response = &EnableKeyResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,108 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// Encrypt invokes the kms.Encrypt API synchronously
// api document: https://help.aliyun.com/api/kms/encrypt.html
func (client *Client) Encrypt(request *EncryptRequest) (response *EncryptResponse, err error) {
response = CreateEncryptResponse()
err = client.DoAction(request, response)
return
}
// EncryptWithChan invokes the kms.Encrypt API asynchronously
// api document: https://help.aliyun.com/api/kms/encrypt.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) EncryptWithChan(request *EncryptRequest) (<-chan *EncryptResponse, <-chan error) {
responseChan := make(chan *EncryptResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.Encrypt(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// EncryptWithCallback invokes the kms.Encrypt API asynchronously
// api document: https://help.aliyun.com/api/kms/encrypt.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) EncryptWithCallback(request *EncryptRequest, callback func(response *EncryptResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *EncryptResponse
var err error
defer close(result)
response, err = client.Encrypt(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// EncryptRequest is the request struct for api Encrypt
type EncryptRequest struct {
*requests.RpcRequest
EncryptionContext string `position:"Query" name:"EncryptionContext"`
KeyId string `position:"Query" name:"KeyId"`
Plaintext string `position:"Query" name:"Plaintext"`
}
// EncryptResponse is the response struct for api Encrypt
type EncryptResponse struct {
*responses.BaseResponse
CiphertextBlob string `json:"CiphertextBlob" xml:"CiphertextBlob"`
KeyId string `json:"KeyId" xml:"KeyId"`
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersionId string `json:"KeyVersionId" xml:"KeyVersionId"`
}
// CreateEncryptRequest creates a request to invoke Encrypt API
func CreateEncryptRequest() (request *EncryptRequest) {
request = &EncryptRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "Encrypt", "kms", "openAPI")
return
}
// CreateEncryptResponse creates a response to parse from Encrypt response
func CreateEncryptResponse() (response *EncryptResponse) {
response = &EncryptResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,20 @@
package kms
// EndpointMap Endpoint Data
var EndpointMap map[string]string
// EndpointType regional or central
var EndpointType = "regional"
// GetEndpointMap Get Endpoint Data Map
func GetEndpointMap() map[string]string {
if EndpointMap == nil {
EndpointMap = map[string]string{}
}
return EndpointMap
}
// GetEndpointType Get Endpoint Type Value
func GetEndpointType() string {
return EndpointType
}

View File

@ -0,0 +1,110 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// GenerateDataKey invokes the kms.GenerateDataKey API synchronously
// api document: https://help.aliyun.com/api/kms/generatedatakey.html
func (client *Client) GenerateDataKey(request *GenerateDataKeyRequest) (response *GenerateDataKeyResponse, err error) {
response = CreateGenerateDataKeyResponse()
err = client.DoAction(request, response)
return
}
// GenerateDataKeyWithChan invokes the kms.GenerateDataKey API asynchronously
// api document: https://help.aliyun.com/api/kms/generatedatakey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GenerateDataKeyWithChan(request *GenerateDataKeyRequest) (<-chan *GenerateDataKeyResponse, <-chan error) {
responseChan := make(chan *GenerateDataKeyResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GenerateDataKey(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GenerateDataKeyWithCallback invokes the kms.GenerateDataKey API asynchronously
// api document: https://help.aliyun.com/api/kms/generatedatakey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GenerateDataKeyWithCallback(request *GenerateDataKeyRequest, callback func(response *GenerateDataKeyResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GenerateDataKeyResponse
var err error
defer close(result)
response, err = client.GenerateDataKey(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GenerateDataKeyRequest is the request struct for api GenerateDataKey
type GenerateDataKeyRequest struct {
*requests.RpcRequest
EncryptionContext string `position:"Query" name:"EncryptionContext"`
KeyId string `position:"Query" name:"KeyId"`
KeySpec string `position:"Query" name:"KeySpec"`
NumberOfBytes requests.Integer `position:"Query" name:"NumberOfBytes"`
}
// GenerateDataKeyResponse is the response struct for api GenerateDataKey
type GenerateDataKeyResponse struct {
*responses.BaseResponse
CiphertextBlob string `json:"CiphertextBlob" xml:"CiphertextBlob"`
KeyId string `json:"KeyId" xml:"KeyId"`
Plaintext string `json:"Plaintext" xml:"Plaintext"`
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersionId string `json:"KeyVersionId" xml:"KeyVersionId"`
}
// CreateGenerateDataKeyRequest creates a request to invoke GenerateDataKey API
func CreateGenerateDataKeyRequest() (request *GenerateDataKeyRequest) {
request = &GenerateDataKeyRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "GenerateDataKey", "kms", "openAPI")
return
}
// CreateGenerateDataKeyResponse creates a response to parse from GenerateDataKey response
func CreateGenerateDataKeyResponse() (response *GenerateDataKeyResponse) {
response = &GenerateDataKeyResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// GenerateDataKeyWithoutPlaintext invokes the kms.GenerateDataKeyWithoutPlaintext API synchronously
// api document: https://help.aliyun.com/api/kms/generatedatakeywithoutplaintext.html
func (client *Client) GenerateDataKeyWithoutPlaintext(request *GenerateDataKeyWithoutPlaintextRequest) (response *GenerateDataKeyWithoutPlaintextResponse, err error) {
response = CreateGenerateDataKeyWithoutPlaintextResponse()
err = client.DoAction(request, response)
return
}
// GenerateDataKeyWithoutPlaintextWithChan invokes the kms.GenerateDataKeyWithoutPlaintext API asynchronously
// api document: https://help.aliyun.com/api/kms/generatedatakeywithoutplaintext.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GenerateDataKeyWithoutPlaintextWithChan(request *GenerateDataKeyWithoutPlaintextRequest) (<-chan *GenerateDataKeyWithoutPlaintextResponse, <-chan error) {
responseChan := make(chan *GenerateDataKeyWithoutPlaintextResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GenerateDataKeyWithoutPlaintext(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GenerateDataKeyWithoutPlaintextWithCallback invokes the kms.GenerateDataKeyWithoutPlaintext API asynchronously
// api document: https://help.aliyun.com/api/kms/generatedatakeywithoutplaintext.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GenerateDataKeyWithoutPlaintextWithCallback(request *GenerateDataKeyWithoutPlaintextRequest, callback func(response *GenerateDataKeyWithoutPlaintextResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GenerateDataKeyWithoutPlaintextResponse
var err error
defer close(result)
response, err = client.GenerateDataKeyWithoutPlaintext(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GenerateDataKeyWithoutPlaintextRequest is the request struct for api GenerateDataKeyWithoutPlaintext
type GenerateDataKeyWithoutPlaintextRequest struct {
*requests.RpcRequest
EncryptionContext string `position:"Query" name:"EncryptionContext"`
KeyId string `position:"Query" name:"KeyId"`
KeySpec string `position:"Query" name:"KeySpec"`
NumberOfBytes requests.Integer `position:"Query" name:"NumberOfBytes"`
}
// GenerateDataKeyWithoutPlaintextResponse is the response struct for api GenerateDataKeyWithoutPlaintext
type GenerateDataKeyWithoutPlaintextResponse struct {
*responses.BaseResponse
CiphertextBlob string `json:"CiphertextBlob" xml:"CiphertextBlob"`
KeyId string `json:"KeyId" xml:"KeyId"`
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersionId string `json:"KeyVersionId" xml:"KeyVersionId"`
}
// CreateGenerateDataKeyWithoutPlaintextRequest creates a request to invoke GenerateDataKeyWithoutPlaintext API
func CreateGenerateDataKeyWithoutPlaintextRequest() (request *GenerateDataKeyWithoutPlaintextRequest) {
request = &GenerateDataKeyWithoutPlaintextRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "GenerateDataKeyWithoutPlaintext", "kms", "openAPI")
return
}
// CreateGenerateDataKeyWithoutPlaintextResponse creates a response to parse from GenerateDataKeyWithoutPlaintext response
func CreateGenerateDataKeyWithoutPlaintextResponse() (response *GenerateDataKeyWithoutPlaintextResponse) {
response = &GenerateDataKeyWithoutPlaintextResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// GetParametersForImport invokes the kms.GetParametersForImport API synchronously
// api document: https://help.aliyun.com/api/kms/getparametersforimport.html
func (client *Client) GetParametersForImport(request *GetParametersForImportRequest) (response *GetParametersForImportResponse, err error) {
response = CreateGetParametersForImportResponse()
err = client.DoAction(request, response)
return
}
// GetParametersForImportWithChan invokes the kms.GetParametersForImport API asynchronously
// api document: https://help.aliyun.com/api/kms/getparametersforimport.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetParametersForImportWithChan(request *GetParametersForImportRequest) (<-chan *GetParametersForImportResponse, <-chan error) {
responseChan := make(chan *GetParametersForImportResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetParametersForImport(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetParametersForImportWithCallback invokes the kms.GetParametersForImport API asynchronously
// api document: https://help.aliyun.com/api/kms/getparametersforimport.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetParametersForImportWithCallback(request *GetParametersForImportRequest, callback func(response *GetParametersForImportResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetParametersForImportResponse
var err error
defer close(result)
response, err = client.GetParametersForImport(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetParametersForImportRequest is the request struct for api GetParametersForImport
type GetParametersForImportRequest struct {
*requests.RpcRequest
KeyId string `position:"Query" name:"KeyId"`
WrappingAlgorithm string `position:"Query" name:"WrappingAlgorithm"`
WrappingKeySpec string `position:"Query" name:"WrappingKeySpec"`
}
// GetParametersForImportResponse is the response struct for api GetParametersForImport
type GetParametersForImportResponse struct {
*responses.BaseResponse
KeyId string `json:"KeyId" xml:"KeyId"`
RequestId string `json:"RequestId" xml:"RequestId"`
ImportToken string `json:"ImportToken" xml:"ImportToken"`
PublicKey string `json:"PublicKey" xml:"PublicKey"`
TokenExpireTime string `json:"TokenExpireTime" xml:"TokenExpireTime"`
}
// CreateGetParametersForImportRequest creates a request to invoke GetParametersForImport API
func CreateGetParametersForImportRequest() (request *GetParametersForImportRequest) {
request = &GetParametersForImportRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "GetParametersForImport", "kms", "openAPI")
return
}
// CreateGetParametersForImportResponse creates a response to parse from GetParametersForImport response
func CreateGetParametersForImportResponse() (response *GetParametersForImportResponse) {
response = &GetParametersForImportResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,107 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// GetPublicKey invokes the kms.GetPublicKey API synchronously
// api document: https://help.aliyun.com/api/kms/getpublickey.html
func (client *Client) GetPublicKey(request *GetPublicKeyRequest) (response *GetPublicKeyResponse, err error) {
response = CreateGetPublicKeyResponse()
err = client.DoAction(request, response)
return
}
// GetPublicKeyWithChan invokes the kms.GetPublicKey API asynchronously
// api document: https://help.aliyun.com/api/kms/getpublickey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetPublicKeyWithChan(request *GetPublicKeyRequest) (<-chan *GetPublicKeyResponse, <-chan error) {
responseChan := make(chan *GetPublicKeyResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetPublicKey(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetPublicKeyWithCallback invokes the kms.GetPublicKey API asynchronously
// api document: https://help.aliyun.com/api/kms/getpublickey.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetPublicKeyWithCallback(request *GetPublicKeyRequest, callback func(response *GetPublicKeyResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetPublicKeyResponse
var err error
defer close(result)
response, err = client.GetPublicKey(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetPublicKeyRequest is the request struct for api GetPublicKey
type GetPublicKeyRequest struct {
*requests.RpcRequest
KeyVersionId string `position:"Query" name:"KeyVersionId"`
KeyId string `position:"Query" name:"KeyId"`
}
// GetPublicKeyResponse is the response struct for api GetPublicKey
type GetPublicKeyResponse struct {
*responses.BaseResponse
PublicKey string `json:"PublicKey" xml:"PublicKey"`
KeyId string `json:"KeyId" xml:"KeyId"`
RequestId string `json:"RequestId" xml:"RequestId"`
KeyVersionId string `json:"KeyVersionId" xml:"KeyVersionId"`
}
// CreateGetPublicKeyRequest creates a request to invoke GetPublicKey API
func CreateGetPublicKeyRequest() (request *GetPublicKeyRequest) {
request = &GetPublicKeyRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "GetPublicKey", "kms", "openAPI")
return
}
// CreateGetPublicKeyResponse creates a response to parse from GetPublicKey response
func CreateGetPublicKeyResponse() (response *GetPublicKeyResponse) {
response = &GetPublicKeyResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,110 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// GetRandomPassword invokes the kms.GetRandomPassword API synchronously
// api document: https://help.aliyun.com/api/kms/getrandompassword.html
func (client *Client) GetRandomPassword(request *GetRandomPasswordRequest) (response *GetRandomPasswordResponse, err error) {
response = CreateGetRandomPasswordResponse()
err = client.DoAction(request, response)
return
}
// GetRandomPasswordWithChan invokes the kms.GetRandomPassword API asynchronously
// api document: https://help.aliyun.com/api/kms/getrandompassword.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRandomPasswordWithChan(request *GetRandomPasswordRequest) (<-chan *GetRandomPasswordResponse, <-chan error) {
responseChan := make(chan *GetRandomPasswordResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRandomPassword(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRandomPasswordWithCallback invokes the kms.GetRandomPassword API asynchronously
// api document: https://help.aliyun.com/api/kms/getrandompassword.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRandomPasswordWithCallback(request *GetRandomPasswordRequest, callback func(response *GetRandomPasswordResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRandomPasswordResponse
var err error
defer close(result)
response, err = client.GetRandomPassword(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRandomPasswordRequest is the request struct for api GetRandomPassword
type GetRandomPasswordRequest struct {
*requests.RpcRequest
ExcludeLowercase string `position:"Query" name:"ExcludeLowercase"`
ExcludeCharacters string `position:"Query" name:"ExcludeCharacters"`
PasswordLength string `position:"Query" name:"PasswordLength"`
ExcludePunctuation string `position:"Query" name:"ExcludePunctuation"`
ExcludeUppercase string `position:"Query" name:"ExcludeUppercase"`
RequireEachIncludedType string `position:"Query" name:"RequireEachIncludedType"`
ExcludeNumbers string `position:"Query" name:"ExcludeNumbers"`
}
// GetRandomPasswordResponse is the response struct for api GetRandomPassword
type GetRandomPasswordResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
RandomPassword string `json:"RandomPassword" xml:"RandomPassword"`
}
// CreateGetRandomPasswordRequest creates a request to invoke GetRandomPassword API
func CreateGetRandomPasswordRequest() (request *GetRandomPasswordRequest) {
request = &GetRandomPasswordRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "GetRandomPassword", "kms", "openAPI")
return
}
// CreateGetRandomPasswordResponse creates a response to parse from GetRandomPassword response
func CreateGetRandomPasswordResponse() (response *GetRandomPasswordResponse) {
response = &GetRandomPasswordResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,111 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// GetSecretValue invokes the kms.GetSecretValue API synchronously
// api document: https://help.aliyun.com/api/kms/getsecretvalue.html
func (client *Client) GetSecretValue(request *GetSecretValueRequest) (response *GetSecretValueResponse, err error) {
response = CreateGetSecretValueResponse()
err = client.DoAction(request, response)
return
}
// GetSecretValueWithChan invokes the kms.GetSecretValue API asynchronously
// api document: https://help.aliyun.com/api/kms/getsecretvalue.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetSecretValueWithChan(request *GetSecretValueRequest) (<-chan *GetSecretValueResponse, <-chan error) {
responseChan := make(chan *GetSecretValueResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetSecretValue(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetSecretValueWithCallback invokes the kms.GetSecretValue API asynchronously
// api document: https://help.aliyun.com/api/kms/getsecretvalue.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetSecretValueWithCallback(request *GetSecretValueRequest, callback func(response *GetSecretValueResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetSecretValueResponse
var err error
defer close(result)
response, err = client.GetSecretValue(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetSecretValueRequest is the request struct for api GetSecretValue
type GetSecretValueRequest struct {
*requests.RpcRequest
VersionId string `position:"Query" name:"VersionId"`
VersionStage string `position:"Query" name:"VersionStage"`
SecretName string `position:"Query" name:"SecretName"`
}
// GetSecretValueResponse is the response struct for api GetSecretValue
type GetSecretValueResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
SecretName string `json:"SecretName" xml:"SecretName"`
VersionId string `json:"VersionId" xml:"VersionId"`
CreateTime string `json:"CreateTime" xml:"CreateTime"`
SecretData string `json:"SecretData" xml:"SecretData"`
SecretDataType string `json:"SecretDataType" xml:"SecretDataType"`
VersionStages []string `json:"VersionStages" xml:"VersionStages"`
}
// CreateGetSecretValueRequest creates a request to invoke GetSecretValue API
func CreateGetSecretValueRequest() (request *GetSecretValueRequest) {
request = &GetSecretValueRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "GetSecretValue", "kms", "openAPI")
return
}
// CreateGetSecretValueResponse creates a response to parse from GetSecretValue response
func CreateGetSecretValueResponse() (response *GetSecretValueResponse) {
response = &GetSecretValueResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,106 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ImportKeyMaterial invokes the kms.ImportKeyMaterial API synchronously
// api document: https://help.aliyun.com/api/kms/importkeymaterial.html
func (client *Client) ImportKeyMaterial(request *ImportKeyMaterialRequest) (response *ImportKeyMaterialResponse, err error) {
response = CreateImportKeyMaterialResponse()
err = client.DoAction(request, response)
return
}
// ImportKeyMaterialWithChan invokes the kms.ImportKeyMaterial API asynchronously
// api document: https://help.aliyun.com/api/kms/importkeymaterial.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ImportKeyMaterialWithChan(request *ImportKeyMaterialRequest) (<-chan *ImportKeyMaterialResponse, <-chan error) {
responseChan := make(chan *ImportKeyMaterialResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ImportKeyMaterial(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ImportKeyMaterialWithCallback invokes the kms.ImportKeyMaterial API asynchronously
// api document: https://help.aliyun.com/api/kms/importkeymaterial.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ImportKeyMaterialWithCallback(request *ImportKeyMaterialRequest, callback func(response *ImportKeyMaterialResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ImportKeyMaterialResponse
var err error
defer close(result)
response, err = client.ImportKeyMaterial(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ImportKeyMaterialRequest is the request struct for api ImportKeyMaterial
type ImportKeyMaterialRequest struct {
*requests.RpcRequest
ImportToken string `position:"Query" name:"ImportToken"`
EncryptedKeyMaterial string `position:"Query" name:"EncryptedKeyMaterial"`
KeyMaterialExpireUnix requests.Integer `position:"Query" name:"KeyMaterialExpireUnix"`
KeyId string `position:"Query" name:"KeyId"`
}
// ImportKeyMaterialResponse is the response struct for api ImportKeyMaterial
type ImportKeyMaterialResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateImportKeyMaterialRequest creates a request to invoke ImportKeyMaterial API
func CreateImportKeyMaterialRequest() (request *ImportKeyMaterialRequest) {
request = &ImportKeyMaterialRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "ImportKeyMaterial", "kms", "openAPI")
return
}
// CreateImportKeyMaterialResponse creates a response to parse from ImportKeyMaterial response
func CreateImportKeyMaterialResponse() (response *ImportKeyMaterialResponse) {
response = &ImportKeyMaterialResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,108 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ListAliases invokes the kms.ListAliases API synchronously
// api document: https://help.aliyun.com/api/kms/listaliases.html
func (client *Client) ListAliases(request *ListAliasesRequest) (response *ListAliasesResponse, err error) {
response = CreateListAliasesResponse()
err = client.DoAction(request, response)
return
}
// ListAliasesWithChan invokes the kms.ListAliases API asynchronously
// api document: https://help.aliyun.com/api/kms/listaliases.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListAliasesWithChan(request *ListAliasesRequest) (<-chan *ListAliasesResponse, <-chan error) {
responseChan := make(chan *ListAliasesResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ListAliases(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ListAliasesWithCallback invokes the kms.ListAliases API asynchronously
// api document: https://help.aliyun.com/api/kms/listaliases.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListAliasesWithCallback(request *ListAliasesRequest, callback func(response *ListAliasesResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ListAliasesResponse
var err error
defer close(result)
response, err = client.ListAliases(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ListAliasesRequest is the request struct for api ListAliases
type ListAliasesRequest struct {
*requests.RpcRequest
PageSize requests.Integer `position:"Query" name:"PageSize"`
PageNumber requests.Integer `position:"Query" name:"PageNumber"`
}
// ListAliasesResponse is the response struct for api ListAliases
type ListAliasesResponse struct {
*responses.BaseResponse
TotalCount int `json:"TotalCount" xml:"TotalCount"`
PageNumber int `json:"PageNumber" xml:"PageNumber"`
PageSize int `json:"PageSize" xml:"PageSize"`
RequestId string `json:"RequestId" xml:"RequestId"`
Aliases AliasesInListAliases `json:"Aliases" xml:"Aliases"`
}
// CreateListAliasesRequest creates a request to invoke ListAliases API
func CreateListAliasesRequest() (request *ListAliasesRequest) {
request = &ListAliasesRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "ListAliases", "kms", "openAPI")
return
}
// CreateListAliasesResponse creates a response to parse from ListAliases response
func CreateListAliasesResponse() (response *ListAliasesResponse) {
response = &ListAliasesResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ListAliasesByKeyId invokes the kms.ListAliasesByKeyId API synchronously
// api document: https://help.aliyun.com/api/kms/listaliasesbykeyid.html
func (client *Client) ListAliasesByKeyId(request *ListAliasesByKeyIdRequest) (response *ListAliasesByKeyIdResponse, err error) {
response = CreateListAliasesByKeyIdResponse()
err = client.DoAction(request, response)
return
}
// ListAliasesByKeyIdWithChan invokes the kms.ListAliasesByKeyId API asynchronously
// api document: https://help.aliyun.com/api/kms/listaliasesbykeyid.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListAliasesByKeyIdWithChan(request *ListAliasesByKeyIdRequest) (<-chan *ListAliasesByKeyIdResponse, <-chan error) {
responseChan := make(chan *ListAliasesByKeyIdResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ListAliasesByKeyId(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ListAliasesByKeyIdWithCallback invokes the kms.ListAliasesByKeyId API asynchronously
// api document: https://help.aliyun.com/api/kms/listaliasesbykeyid.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListAliasesByKeyIdWithCallback(request *ListAliasesByKeyIdRequest, callback func(response *ListAliasesByKeyIdResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ListAliasesByKeyIdResponse
var err error
defer close(result)
response, err = client.ListAliasesByKeyId(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ListAliasesByKeyIdRequest is the request struct for api ListAliasesByKeyId
type ListAliasesByKeyIdRequest struct {
*requests.RpcRequest
PageSize requests.Integer `position:"Query" name:"PageSize"`
KeyId string `position:"Query" name:"KeyId"`
PageNumber requests.Integer `position:"Query" name:"PageNumber"`
}
// ListAliasesByKeyIdResponse is the response struct for api ListAliasesByKeyId
type ListAliasesByKeyIdResponse struct {
*responses.BaseResponse
TotalCount int `json:"TotalCount" xml:"TotalCount"`
PageNumber int `json:"PageNumber" xml:"PageNumber"`
PageSize int `json:"PageSize" xml:"PageSize"`
RequestId string `json:"RequestId" xml:"RequestId"`
Aliases AliasesInListAliasesByKeyId `json:"Aliases" xml:"Aliases"`
}
// CreateListAliasesByKeyIdRequest creates a request to invoke ListAliasesByKeyId API
func CreateListAliasesByKeyIdRequest() (request *ListAliasesByKeyIdRequest) {
request = &ListAliasesByKeyIdRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "ListAliasesByKeyId", "kms", "openAPI")
return
}
// CreateListAliasesByKeyIdResponse creates a response to parse from ListAliasesByKeyId response
func CreateListAliasesByKeyIdResponse() (response *ListAliasesByKeyIdResponse) {
response = &ListAliasesByKeyIdResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ListKeyVersions invokes the kms.ListKeyVersions API synchronously
// api document: https://help.aliyun.com/api/kms/listkeyversions.html
func (client *Client) ListKeyVersions(request *ListKeyVersionsRequest) (response *ListKeyVersionsResponse, err error) {
response = CreateListKeyVersionsResponse()
err = client.DoAction(request, response)
return
}
// ListKeyVersionsWithChan invokes the kms.ListKeyVersions API asynchronously
// api document: https://help.aliyun.com/api/kms/listkeyversions.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListKeyVersionsWithChan(request *ListKeyVersionsRequest) (<-chan *ListKeyVersionsResponse, <-chan error) {
responseChan := make(chan *ListKeyVersionsResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ListKeyVersions(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ListKeyVersionsWithCallback invokes the kms.ListKeyVersions API asynchronously
// api document: https://help.aliyun.com/api/kms/listkeyversions.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListKeyVersionsWithCallback(request *ListKeyVersionsRequest, callback func(response *ListKeyVersionsResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ListKeyVersionsResponse
var err error
defer close(result)
response, err = client.ListKeyVersions(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ListKeyVersionsRequest is the request struct for api ListKeyVersions
type ListKeyVersionsRequest struct {
*requests.RpcRequest
PageSize requests.Integer `position:"Query" name:"PageSize"`
KeyId string `position:"Query" name:"KeyId"`
PageNumber requests.Integer `position:"Query" name:"PageNumber"`
}
// ListKeyVersionsResponse is the response struct for api ListKeyVersions
type ListKeyVersionsResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
TotalCount int `json:"TotalCount" xml:"TotalCount"`
PageNumber int `json:"PageNumber" xml:"PageNumber"`
PageSize int `json:"PageSize" xml:"PageSize"`
KeyVersions KeyVersions `json:"KeyVersions" xml:"KeyVersions"`
}
// CreateListKeyVersionsRequest creates a request to invoke ListKeyVersions API
func CreateListKeyVersionsRequest() (request *ListKeyVersionsRequest) {
request = &ListKeyVersionsRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "ListKeyVersions", "kms", "openAPI")
return
}
// CreateListKeyVersionsResponse creates a response to parse from ListKeyVersions response
func CreateListKeyVersionsResponse() (response *ListKeyVersionsResponse) {
response = &ListKeyVersionsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,108 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ListKeys invokes the kms.ListKeys API synchronously
// api document: https://help.aliyun.com/api/kms/listkeys.html
func (client *Client) ListKeys(request *ListKeysRequest) (response *ListKeysResponse, err error) {
response = CreateListKeysResponse()
err = client.DoAction(request, response)
return
}
// ListKeysWithChan invokes the kms.ListKeys API asynchronously
// api document: https://help.aliyun.com/api/kms/listkeys.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListKeysWithChan(request *ListKeysRequest) (<-chan *ListKeysResponse, <-chan error) {
responseChan := make(chan *ListKeysResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ListKeys(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ListKeysWithCallback invokes the kms.ListKeys API asynchronously
// api document: https://help.aliyun.com/api/kms/listkeys.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListKeysWithCallback(request *ListKeysRequest, callback func(response *ListKeysResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ListKeysResponse
var err error
defer close(result)
response, err = client.ListKeys(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ListKeysRequest is the request struct for api ListKeys
type ListKeysRequest struct {
*requests.RpcRequest
PageSize requests.Integer `position:"Query" name:"PageSize"`
PageNumber requests.Integer `position:"Query" name:"PageNumber"`
}
// ListKeysResponse is the response struct for api ListKeys
type ListKeysResponse struct {
*responses.BaseResponse
TotalCount int `json:"TotalCount" xml:"TotalCount"`
PageNumber int `json:"PageNumber" xml:"PageNumber"`
PageSize int `json:"PageSize" xml:"PageSize"`
RequestId string `json:"RequestId" xml:"RequestId"`
Keys Keys `json:"Keys" xml:"Keys"`
}
// CreateListKeysRequest creates a request to invoke ListKeys API
func CreateListKeysRequest() (request *ListKeysRequest) {
request = &ListKeysRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "ListKeys", "kms", "openAPI")
return
}
// CreateListKeysResponse creates a response to parse from ListKeys response
func CreateListKeysResponse() (response *ListKeysResponse) {
response = &ListKeysResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ListResourceTags invokes the kms.ListResourceTags API synchronously
// api document: https://help.aliyun.com/api/kms/listresourcetags.html
func (client *Client) ListResourceTags(request *ListResourceTagsRequest) (response *ListResourceTagsResponse, err error) {
response = CreateListResourceTagsResponse()
err = client.DoAction(request, response)
return
}
// ListResourceTagsWithChan invokes the kms.ListResourceTags API asynchronously
// api document: https://help.aliyun.com/api/kms/listresourcetags.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListResourceTagsWithChan(request *ListResourceTagsRequest) (<-chan *ListResourceTagsResponse, <-chan error) {
responseChan := make(chan *ListResourceTagsResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ListResourceTags(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ListResourceTagsWithCallback invokes the kms.ListResourceTags API asynchronously
// api document: https://help.aliyun.com/api/kms/listresourcetags.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListResourceTagsWithCallback(request *ListResourceTagsRequest, callback func(response *ListResourceTagsResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ListResourceTagsResponse
var err error
defer close(result)
response, err = client.ListResourceTags(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ListResourceTagsRequest is the request struct for api ListResourceTags
type ListResourceTagsRequest struct {
*requests.RpcRequest
KeyId string `position:"Query" name:"KeyId"`
}
// ListResourceTagsResponse is the response struct for api ListResourceTags
type ListResourceTagsResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
Tags TagsInListResourceTags `json:"Tags" xml:"Tags"`
}
// CreateListResourceTagsRequest creates a request to invoke ListResourceTags API
func CreateListResourceTagsRequest() (request *ListResourceTagsRequest) {
request = &ListResourceTagsRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "ListResourceTags", "kms", "openAPI")
return
}
// CreateListResourceTagsResponse creates a response to parse from ListResourceTags response
func CreateListResourceTagsResponse() (response *ListResourceTagsResponse) {
response = &ListResourceTagsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,111 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ListSecretVersionIds invokes the kms.ListSecretVersionIds API synchronously
// api document: https://help.aliyun.com/api/kms/listsecretversionids.html
func (client *Client) ListSecretVersionIds(request *ListSecretVersionIdsRequest) (response *ListSecretVersionIdsResponse, err error) {
response = CreateListSecretVersionIdsResponse()
err = client.DoAction(request, response)
return
}
// ListSecretVersionIdsWithChan invokes the kms.ListSecretVersionIds API asynchronously
// api document: https://help.aliyun.com/api/kms/listsecretversionids.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListSecretVersionIdsWithChan(request *ListSecretVersionIdsRequest) (<-chan *ListSecretVersionIdsResponse, <-chan error) {
responseChan := make(chan *ListSecretVersionIdsResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ListSecretVersionIds(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ListSecretVersionIdsWithCallback invokes the kms.ListSecretVersionIds API asynchronously
// api document: https://help.aliyun.com/api/kms/listsecretversionids.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListSecretVersionIdsWithCallback(request *ListSecretVersionIdsRequest, callback func(response *ListSecretVersionIdsResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ListSecretVersionIdsResponse
var err error
defer close(result)
response, err = client.ListSecretVersionIds(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ListSecretVersionIdsRequest is the request struct for api ListSecretVersionIds
type ListSecretVersionIdsRequest struct {
*requests.RpcRequest
IncludeDeprecated string `position:"Query" name:"IncludeDeprecated"`
PageSize requests.Integer `position:"Query" name:"PageSize"`
SecretName string `position:"Query" name:"SecretName"`
PageNumber requests.Integer `position:"Query" name:"PageNumber"`
}
// ListSecretVersionIdsResponse is the response struct for api ListSecretVersionIds
type ListSecretVersionIdsResponse struct {
*responses.BaseResponse
PageNumber int `json:"PageNumber" xml:"PageNumber"`
PageSize int `json:"PageSize" xml:"PageSize"`
RequestId string `json:"RequestId" xml:"RequestId"`
SecretName string `json:"SecretName" xml:"SecretName"`
TotalCount int `json:"TotalCount" xml:"TotalCount"`
VersionIds []VersionId `json:"VersionIds" xml:"VersionIds"`
}
// CreateListSecretVersionIdsRequest creates a request to invoke ListSecretVersionIds API
func CreateListSecretVersionIdsRequest() (request *ListSecretVersionIdsRequest) {
request = &ListSecretVersionIdsRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "ListSecretVersionIds", "kms", "openAPI")
return
}
// CreateListSecretVersionIdsResponse creates a response to parse from ListSecretVersionIds response
func CreateListSecretVersionIdsResponse() (response *ListSecretVersionIdsResponse) {
response = &ListSecretVersionIdsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,109 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ListSecrets invokes the kms.ListSecrets API synchronously
// api document: https://help.aliyun.com/api/kms/listsecrets.html
func (client *Client) ListSecrets(request *ListSecretsRequest) (response *ListSecretsResponse, err error) {
response = CreateListSecretsResponse()
err = client.DoAction(request, response)
return
}
// ListSecretsWithChan invokes the kms.ListSecrets API asynchronously
// api document: https://help.aliyun.com/api/kms/listsecrets.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListSecretsWithChan(request *ListSecretsRequest) (<-chan *ListSecretsResponse, <-chan error) {
responseChan := make(chan *ListSecretsResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ListSecrets(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ListSecretsWithCallback invokes the kms.ListSecrets API asynchronously
// api document: https://help.aliyun.com/api/kms/listsecrets.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ListSecretsWithCallback(request *ListSecretsRequest, callback func(response *ListSecretsResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ListSecretsResponse
var err error
defer close(result)
response, err = client.ListSecrets(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ListSecretsRequest is the request struct for api ListSecrets
type ListSecretsRequest struct {
*requests.RpcRequest
PageSize requests.Integer `position:"Query" name:"PageSize"`
FetchTags string `position:"Query" name:"FetchTags"`
PageNumber requests.Integer `position:"Query" name:"PageNumber"`
}
// ListSecretsResponse is the response struct for api ListSecrets
type ListSecretsResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
PageNumber int `json:"PageNumber" xml:"PageNumber"`
PageSize int `json:"PageSize" xml:"PageSize"`
TotalCount int `json:"TotalCount" xml:"TotalCount"`
SecretList []Secret `json:"SecretList" xml:"SecretList"`
}
// CreateListSecretsRequest creates a request to invoke ListSecrets API
func CreateListSecretsRequest() (request *ListSecretsRequest) {
request = &ListSecretsRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "ListSecrets", "kms", "openAPI")
return
}
// CreateListSecretsResponse creates a response to parse from ListSecrets response
func CreateListSecretsResponse() (response *ListSecretsResponse) {
response = &ListSecretsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,110 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// PutSecretValue invokes the kms.PutSecretValue API synchronously
// api document: https://help.aliyun.com/api/kms/putsecretvalue.html
func (client *Client) PutSecretValue(request *PutSecretValueRequest) (response *PutSecretValueResponse, err error) {
response = CreatePutSecretValueResponse()
err = client.DoAction(request, response)
return
}
// PutSecretValueWithChan invokes the kms.PutSecretValue API asynchronously
// api document: https://help.aliyun.com/api/kms/putsecretvalue.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) PutSecretValueWithChan(request *PutSecretValueRequest) (<-chan *PutSecretValueResponse, <-chan error) {
responseChan := make(chan *PutSecretValueResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.PutSecretValue(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// PutSecretValueWithCallback invokes the kms.PutSecretValue API asynchronously
// api document: https://help.aliyun.com/api/kms/putsecretvalue.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) PutSecretValueWithCallback(request *PutSecretValueRequest, callback func(response *PutSecretValueResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *PutSecretValueResponse
var err error
defer close(result)
response, err = client.PutSecretValue(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// PutSecretValueRequest is the request struct for api PutSecretValue
type PutSecretValueRequest struct {
*requests.RpcRequest
VersionId string `position:"Query" name:"VersionId"`
VersionStages string `position:"Query" name:"VersionStages"`
SecretData string `position:"Query" name:"SecretData"`
SecretName string `position:"Query" name:"SecretName"`
SecretDataType string `position:"Query" name:"SecretDataType"`
}
// PutSecretValueResponse is the response struct for api PutSecretValue
type PutSecretValueResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
SecretName string `json:"SecretName" xml:"SecretName"`
VersionId string `json:"VersionId" xml:"VersionId"`
VersionStages []string `json:"VersionStages" xml:"VersionStages"`
}
// CreatePutSecretValueRequest creates a request to invoke PutSecretValue API
func CreatePutSecretValueRequest() (request *PutSecretValueRequest) {
request = &PutSecretValueRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "PutSecretValue", "kms", "openAPI")
return
}
// CreatePutSecretValueResponse creates a response to parse from PutSecretValue response
func CreatePutSecretValueResponse() (response *PutSecretValueResponse) {
response = &PutSecretValueResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// RestoreSecret invokes the kms.RestoreSecret API synchronously
// api document: https://help.aliyun.com/api/kms/restoresecret.html
func (client *Client) RestoreSecret(request *RestoreSecretRequest) (response *RestoreSecretResponse, err error) {
response = CreateRestoreSecretResponse()
err = client.DoAction(request, response)
return
}
// RestoreSecretWithChan invokes the kms.RestoreSecret API asynchronously
// api document: https://help.aliyun.com/api/kms/restoresecret.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) RestoreSecretWithChan(request *RestoreSecretRequest) (<-chan *RestoreSecretResponse, <-chan error) {
responseChan := make(chan *RestoreSecretResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.RestoreSecret(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// RestoreSecretWithCallback invokes the kms.RestoreSecret API asynchronously
// api document: https://help.aliyun.com/api/kms/restoresecret.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) RestoreSecretWithCallback(request *RestoreSecretRequest, callback func(response *RestoreSecretResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *RestoreSecretResponse
var err error
defer close(result)
response, err = client.RestoreSecret(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// RestoreSecretRequest is the request struct for api RestoreSecret
type RestoreSecretRequest struct {
*requests.RpcRequest
SecretName string `position:"Query" name:"SecretName"`
}
// RestoreSecretResponse is the response struct for api RestoreSecret
type RestoreSecretResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
SecretName string `json:"SecretName" xml:"SecretName"`
}
// CreateRestoreSecretRequest creates a request to invoke RestoreSecret API
func CreateRestoreSecretRequest() (request *RestoreSecretRequest) {
request = &RestoreSecretRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "RestoreSecret", "kms", "openAPI")
return
}
// CreateRestoreSecretResponse creates a response to parse from RestoreSecret response
func CreateRestoreSecretResponse() (response *RestoreSecretResponse) {
response = &RestoreSecretResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)
// ScheduleKeyDeletion invokes the kms.ScheduleKeyDeletion API synchronously
// api document: https://help.aliyun.com/api/kms/schedulekeydeletion.html
func (client *Client) ScheduleKeyDeletion(request *ScheduleKeyDeletionRequest) (response *ScheduleKeyDeletionResponse, err error) {
response = CreateScheduleKeyDeletionResponse()
err = client.DoAction(request, response)
return
}
// ScheduleKeyDeletionWithChan invokes the kms.ScheduleKeyDeletion API asynchronously
// api document: https://help.aliyun.com/api/kms/schedulekeydeletion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ScheduleKeyDeletionWithChan(request *ScheduleKeyDeletionRequest) (<-chan *ScheduleKeyDeletionResponse, <-chan error) {
responseChan := make(chan *ScheduleKeyDeletionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.ScheduleKeyDeletion(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// ScheduleKeyDeletionWithCallback invokes the kms.ScheduleKeyDeletion API asynchronously
// api document: https://help.aliyun.com/api/kms/schedulekeydeletion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) ScheduleKeyDeletionWithCallback(request *ScheduleKeyDeletionRequest, callback func(response *ScheduleKeyDeletionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *ScheduleKeyDeletionResponse
var err error
defer close(result)
response, err = client.ScheduleKeyDeletion(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// ScheduleKeyDeletionRequest is the request struct for api ScheduleKeyDeletion
type ScheduleKeyDeletionRequest struct {
*requests.RpcRequest
PendingWindowInDays requests.Integer `position:"Query" name:"PendingWindowInDays"`
KeyId string `position:"Query" name:"KeyId"`
}
// ScheduleKeyDeletionResponse is the response struct for api ScheduleKeyDeletion
type ScheduleKeyDeletionResponse struct {
*responses.BaseResponse
RequestId string `json:"RequestId" xml:"RequestId"`
}
// CreateScheduleKeyDeletionRequest creates a request to invoke ScheduleKeyDeletion API
func CreateScheduleKeyDeletionRequest() (request *ScheduleKeyDeletionRequest) {
request = &ScheduleKeyDeletionRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Kms", "2016-01-20", "ScheduleKeyDeletion", "kms", "openAPI")
return
}
// CreateScheduleKeyDeletionResponse creates a response to parse from ScheduleKeyDeletion response
func CreateScheduleKeyDeletionResponse() (response *ScheduleKeyDeletionResponse) {
response = &ScheduleKeyDeletionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,23 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// Alias is a nested struct in kms response
type Alias struct {
AliasArn string `json:"AliasArn" xml:"AliasArn"`
AliasName string `json:"AliasName" xml:"AliasName"`
KeyId string `json:"KeyId" xml:"KeyId"`
}

View File

@ -0,0 +1,21 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// AliasesInListAliases is a nested struct in kms response
type AliasesInListAliases struct {
Alias []Alias `json:"Alias" xml:"Alias"`
}

View File

@ -0,0 +1,21 @@
package kms
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// AliasesInListAliasesByKeyId is a nested struct in kms response
type AliasesInListAliasesByKeyId struct {
Alias []Alias `json:"Alias" xml:"Alias"`
}

Some files were not shown because too many files have changed in this diff Show More