Aliyun ACR adapter

1. aliyun ACR registry adapter.
2. Unit test case.
3. Update go modules and vendor.

Signed-off-by: 疯魔慕薇 <kfanjian@gmail.com>
This commit is contained in:
慕薇疯魔 2019-07-02 22:39:15 +08:00 committed by 疯魔慕薇
parent 7fd06edccf
commit 0d71eb363a
137 changed files with 19678 additions and 1 deletions

View File

@ -11,6 +11,7 @@ require (
github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d // indirect
github.com/Unknwon/goconfig v0.0.0-20160216183935-5f601ca6ef4d // indirect
github.com/agl/ed25519 v0.0.0-20170116200512-5312a6153412 // indirect
github.com/aliyun/alibaba-cloud-sdk-go v0.0.0-20190726115642-cd293c93fd97
github.com/astaxie/beego v1.9.0
github.com/aws/aws-sdk-go v1.19.47
github.com/beego/i18n v0.0.0-20140604031826-e87155e8f0c0
@ -64,7 +65,6 @@ require (
github.com/prometheus/client_golang v0.9.4 // indirect
github.com/robfig/cron v1.0.0
github.com/sirupsen/logrus v1.4.1 // indirect
github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a // indirect
github.com/spf13/viper v1.4.0 // indirect
github.com/stretchr/testify v1.3.0
github.com/theupdateframework/notary v0.6.1

View File

@ -21,12 +21,16 @@ github.com/agl/ed25519 v0.0.0-20170116200512-5312a6153412 h1:w1UutsfOrms1J05zt7I
github.com/agl/ed25519 v0.0.0-20170116200512-5312a6153412/go.mod h1:WPjqKcmVOxf0XSf3YxCJs6N6AOSrOx3obionmG7T0y0=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/aliyun/alibaba-cloud-sdk-go v0.0.0-20190726115642-cd293c93fd97 h1:bNE5ID4C3YOkROfvBjXJUG53gyb+8az3TQN02LqnGBk=
github.com/aliyun/alibaba-cloud-sdk-go v0.0.0-20190726115642-cd293c93fd97/go.mod h1:myCDvQSzCW+wB1WAlocEru4wMGJxy+vlxHdhegi1CDQ=
github.com/aliyun/aliyun-oss-go-sdk v0.0.0-20190307165228-86c17b95fcd5/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/astaxie/beego v1.9.0 h1:tPzS+D1oCLi+SEb/TLNRNYpCjaMVfAGoy9OTLwS5ul4=
github.com/astaxie/beego v1.9.0/go.mod h1:0R4++1tUqERR0WYFWdfkcrsyoVBCG4DgpDGokT3yb+U=
github.com/aws/aws-sdk-go v1.19.47 h1:ZEze0mpk8Fttrsz6UNLqhH/jRGYbMPfWFA2ILas4AmM=
github.com/aws/aws-sdk-go v1.19.47/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod h1:AuiFmCCPBSrqvVMvuqFuk0qogytodnVFVSN5CeJB8Gc=
github.com/beego/i18n v0.0.0-20140604031826-e87155e8f0c0 h1:fQaDnUQvBXHHQdGBu9hz8nPznB4BeiPQokvmQVjmNEw=
github.com/beego/i18n v0.0.0-20140604031826-e87155e8f0c0/go.mod h1:KLeFCpAMq2+50NkXC8iiJxLLiiTfTqrGtKEVm+2fk7s=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
@ -110,6 +114,7 @@ github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7a
github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1 h1:/s5zKNz0uPFCZ5hddgPdo2TK2TVrUNMn0OOX8/aZMTE=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A=
github.com/golang-migrate/migrate v3.3.0+incompatible h1:RuACw4Vio/z4aebypBmpU9xKKmSiZBiHOx/Ro1QLcYc=
github.com/golang-migrate/migrate v3.3.0+incompatible/go.mod h1:IsVUlFN5puWOmXrqjgGUfIRIbU7mr8oNBE2tyERd9Wk=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
@ -165,6 +170,7 @@ github.com/jinzhu/now v1.0.0/go.mod h1:oHTiXerJ20+SfYcrdlBO7rzZRJWGwSTQ0iUY2jI6G
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.6 h1:MrUvLMLTMxbqFJ9kzlvat/rYZqZnW3u4wkLzWTaFwKs=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
@ -202,6 +208,7 @@ github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQz
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
@ -252,6 +259,7 @@ github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqn
github.com/robfig/cron v1.0.0 h1:slmQxIUH6U9ruw4XoJ7C2pyyx4yYeiHx8S9pNootHsM=
github.com/robfig/cron v1.0.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.1 h1:GL2rEmy6nsikmW0r8opw9JIRScdMF5hA8cOYLH7In1k=
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
@ -363,6 +371,8 @@ gopkg.in/gorethink/gorethink.v3 v3.0.5 h1:e2Uc/Xe+hpcVQFsj6MuHlYog3r0JYpnTzwDj/y
gopkg.in/gorethink/gorethink.v3 v3.0.5/go.mod h1:+3yIIHJUGMBK+wyPH+iN5TP+88ikFDfZdqTlK3Y9q8I=
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/ini.v1 v1.42.0 h1:7N3gPTt50s8GuLortA00n8AqRTk75qOP98+mTPpgzRk=
gopkg.in/ini.v1 v1.42.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ldap.v2 v2.5.0 h1:1rO3ojzsHUk+gq4ZYhC4Pg+EzWaaKIV8+DJwExS5/QQ=
gopkg.in/ldap.v2 v2.5.0/go.mod h1:oI0cpe/D7HRtBQl8aTg+ZmzFUAvu4lsv3eLXMLGFxWk=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=

View File

@ -40,6 +40,8 @@ import (
_ "github.com/goharbor/harbor/src/replication/adapter/awsecr"
// register the AzureAcr adapter
_ "github.com/goharbor/harbor/src/replication/adapter/azurecr"
// register the AliACR adapter
_ "github.com/goharbor/harbor/src/replication/adapter/aliacr"
)
// Replication implements the job interface

View File

@ -0,0 +1,242 @@
package aliacr
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"path/filepath"
"regexp"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr"
"github.com/goharbor/harbor/src/common/utils/registry/auth"
"github.com/goharbor/harbor/src/replication/adapter/native"
"github.com/goharbor/harbor/src/replication/util"
"github.com/goharbor/harbor/src/common/utils/log"
adp "github.com/goharbor/harbor/src/replication/adapter"
"github.com/goharbor/harbor/src/replication/model"
)
func init() {
if err := adp.RegisterFactory(model.RegistryTypeAliAcr, func(registry *model.Registry) (adp.Adapter, error) {
return newAdapter(registry)
}); err != nil {
log.Errorf("failed to register factory for %s: %v", model.RegistryTypeAliAcr, err)
return
}
log.Infof("the factory for adapter %s registered", model.RegistryTypeAliAcr)
}
// example:
// https://registry.%s.aliyuncs.com
// https://cr.%s.aliyuncs.com
var regRegion = regexp.MustCompile("https://(registry|cr)\\.([\\w\\-]+)\\.aliyuncs\\.com")
func getRegion(url string) (region string, err error) {
if url == "" {
return "", errors.New("empty url")
}
rs := regRegion.FindStringSubmatch(url)
if rs == nil {
return "", errors.New("Invalid Rgistry|CR service url")
}
// fmt.Println(rs)
return rs[2], nil
}
func newAdapter(registry *model.Registry) (*adapter, error) {
region, err := getRegion(registry.URL)
if err != nil {
return nil, err
}
// fix url (allow user input cr service url)
registry.URL = fmt.Sprintf(registryEndpointTpl, region)
credential := NewAuth(region, registry.Credential.AccessKey, registry.Credential.AccessSecret)
authorizer := auth.NewStandardTokenAuthorizer(&http.Client{
Transport: util.GetHTTPTransport(registry.Insecure),
}, credential)
nativeRegistry, err := native.NewAdapterWithCustomizedAuthorizer(registry, authorizer)
if err != nil {
return nil, err
}
return &adapter{
region: region,
registry: registry,
domain: fmt.Sprintf(endpointTpl, region),
Adapter: nativeRegistry,
}, nil
}
// adapter for to aliyun docker registry
type adapter struct {
*native.Adapter
region string
domain string
registry *model.Registry
}
var _ adp.Adapter = &adapter{}
// Info ...
func (a *adapter) Info() (info *model.RegistryInfo, err error) {
info = &model.RegistryInfo{
Type: model.RegistryTypeAliAcr,
SupportedResourceTypes: []model.ResourceType{
model.ResourceTypeImage,
},
SupportedResourceFilters: []*model.FilterStyle{
{
Type: model.FilterTypeName,
Style: model.FilterStyleTypeText,
},
{
Type: model.FilterTypeTag,
Style: model.FilterStyleTypeText,
},
},
SupportedTriggers: []model.TriggerType{
model.TriggerTypeManual,
model.TriggerTypeScheduled,
},
}
return
}
// FetchImages AliACR not support /v2/_catalog of Registry, we'll list all resources via Aliyun's API
func (a *adapter) FetchImages(filters []*model.Filter) (resources []*model.Resource, err error) {
log.Debugf("FetchImages.filters: %#v\n", filters)
var client *cr.Client
client, err = cr.NewClientWithAccessKey(a.region, a.registry.Credential.AccessKey, a.registry.Credential.AccessSecret)
if err != nil {
return
}
// get filter pattern
var repoPattern string
var tagsPattern string
for _, filter := range filters {
if filter.Type == model.FilterTypeName {
repoPattern = filter.Value.(string)
}
if filter.Type == model.FilterTypeTag {
tagsPattern = filter.Value.(string)
}
}
// list repos
var repositories []aliRepo
for {
var repoListResp *aliRepoResp
repoListResp, err = a.listRepo(a.region, client)
if err != nil {
return
}
if repoPattern != "" {
for _, repo := range repoListResp.Data.Repos {
var ok bool
ok, err = util.Match(repoPattern, filepath.Join(repo.RepoNamespace, repo.RepoName))
if err != nil {
return
}
if ok {
repositories = append(repositories, repo)
}
}
} else {
repositories = append(repositories, repoListResp.Data.Repos...)
}
if repoListResp.Data.Total-(repoListResp.Data.Page*repoListResp.Data.PageSize) <= 0 {
break
}
}
log.Debugf("FetchImages.repositories: %#v\n", repositories)
// list tags
for _, repository := range repositories {
var tags []string
tags, err = a.getTags(repository, client)
if err != nil {
return
}
var filterTags []string
if tagsPattern != "" {
for _, tag := range tags {
var ok bool
ok, err = util.Match(tagsPattern, tag)
if err != nil {
return
}
if ok {
filterTags = append(filterTags, tag)
}
}
} else {
filterTags = tags
}
if len(filterTags) > 0 {
resources = append(resources, &model.Resource{
Type: model.ResourceTypeImage,
Registry: a.registry,
Metadata: &model.ResourceMetadata{
Repository: &model.Repository{
Name: filepath.Join(repository.RepoNamespace, repository.RepoName),
},
Vtags: filterTags,
Labels: []string{},
},
})
}
}
return
}
func (a *adapter) listRepo(region string, c *cr.Client) (resp *aliRepoResp, err error) {
var reposReq = cr.CreateGetRepoListRequest()
var reposResp = cr.CreateGetRepoListResponse()
reposReq.SetDomain(a.domain)
reposResp, err = c.GetRepoList(reposReq)
if err != nil {
return
}
resp = &aliRepoResp{}
json.Unmarshal(reposResp.GetHttpContentBytes(), resp)
return
}
func (a *adapter) getTags(repo aliRepo, c *cr.Client) (tags []string, err error) {
log.Debugf("[ali-acr.getTags]%s: %#v\n", a.domain, repo)
var tagsReq = cr.CreateGetRepoTagsRequest()
var tagsResp = cr.CreateGetRepoTagsResponse()
tagsReq.SetDomain(a.domain)
tagsReq.RepoNamespace = repo.RepoNamespace
tagsReq.RepoName = repo.RepoName
for {
fmt.Printf("[GetRepoTags.req] %#v\n", tagsReq)
tagsResp, err = c.GetRepoTags(tagsReq)
if err != nil {
return
}
var resp = &aliTagResp{}
json.Unmarshal(tagsResp.GetHttpContentBytes(), resp)
for _, tag := range resp.Data.Tags {
tags = append(tags, tag.Tag)
}
if resp.Data.Total-(resp.Data.Page*resp.Data.PageSize) <= 0 {
break
}
}
return
}

View File

@ -0,0 +1,203 @@
package aliacr
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/goharbor/harbor/src/common/utils/test"
adp "github.com/goharbor/harbor/src/replication/adapter"
"github.com/goharbor/harbor/src/replication/adapter/native"
"github.com/goharbor/harbor/src/replication/model"
"github.com/stretchr/testify/assert"
)
func TestAdapter_NewAdapter(t *testing.T) {
factory, err := adp.GetFactory("BadName")
assert.Nil(t, factory)
assert.NotNil(t, err)
factory, err = adp.GetFactory(model.RegistryTypeAliAcr)
assert.Nil(t, err)
assert.NotNil(t, factory)
// test case for URL is registry.
adapter, err := factory(&model.Registry{
Type: model.RegistryTypeAliAcr,
Credential: &model.Credential{
AccessKey: "MockAccessKey",
AccessSecret: "MockAccessSecret",
},
URL: "https://registry.test-region.aliyuncs.com",
})
assert.Nil(t, err)
assert.NotNil(t, adapter)
// test case for URL is cr service.
adapter, err = factory(&model.Registry{
Type: model.RegistryTypeAliAcr,
Credential: &model.Credential{
AccessKey: "MockAccessKey",
AccessSecret: "MockAccessSecret",
},
URL: "https://cr.test-region.aliyuncs.com",
})
assert.Nil(t, err)
assert.NotNil(t, adapter)
}
func getMockAdapter(t *testing.T, hasCred, health bool) (*adapter, *httptest.Server) {
server := test.NewServer(
&test.RequestHandlerMapping{
Method: http.MethodGet,
Pattern: "/v2/",
Handler: func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Method, r.URL)
if health {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusBadRequest)
}
},
},
&test.RequestHandlerMapping{
Method: http.MethodGet,
Pattern: "/",
Handler: func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Method, r.URL)
w.WriteHeader(http.StatusOK)
},
},
&test.RequestHandlerMapping{
Method: http.MethodPost,
Pattern: "/",
Handler: func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Method, r.URL)
if buf, e := ioutil.ReadAll(&io.LimitedReader{R: r.Body, N: 80}); e == nil {
fmt.Println("\t", string(buf))
}
w.WriteHeader(http.StatusOK)
},
},
)
registry := &model.Registry{
Type: model.RegistryTypeAliAcr,
URL: server.URL,
}
if hasCred {
registry.Credential = &model.Credential{
AccessKey: "MockAccessKey",
AccessSecret: "MockAccessSecret",
}
}
nativeRegistry, err := native.NewAdapter(registry)
if err != nil {
panic(err)
}
return &adapter{
Adapter: nativeRegistry,
region: "test-region",
domain: server.URL,
registry: registry,
}, server
}
func TestAdapter_Info(t *testing.T) {
a, s := getMockAdapter(t, true, true)
defer s.Close()
info, err := a.Info()
assert.Nil(t, err)
assert.NotNil(t, info)
assert.EqualValues(t, 1, len(info.SupportedResourceTypes))
assert.EqualValues(t, model.ResourceTypeImage, info.SupportedResourceTypes[0])
}
func Test_getRegion(t *testing.T) {
tests := []struct {
name string
url string
wantRegion string
wantErr bool
}{
{"registry shanghai", "https://registry.cn-shanghai.aliyuncs.com", "cn-shanghai", false},
{"invalid registry shanghai", "http://registry.cn-shanghai.aliyuncs.com", "", true},
{"registry hangzhou", "https://registry.cn-hangzhou.aliyuncs.com", "cn-hangzhou", false},
{"cr shanghai", "https://cr.cn-shanghai.aliyuncs.com", "cn-shanghai", false},
{"cr hangzhou", "https://cr.cn-hangzhou.aliyuncs.com", "cn-hangzhou", false},
{"invalid cr url", "https://acr.cn-hangzhou.aliyuncs.com", "", true},
{"invalid registry url", "https://registry.cn-hangzhou.ali.com", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotRegion, err := getRegion(tt.url)
if tt.wantErr {
assert.NotNil(t, err)
}
assert.Equal(t, tt.wantRegion, gotRegion)
})
}
}
var urlForBenchmark = []string{
"https://cr.cn-hangzhou.aliyuncs.com",
"https://registry.cn-shanghai.aliyuncs.com",
}
func BenchmarkGetRegion(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, url := range urlForBenchmark {
getRegion(url)
}
}
}
func Test_adapter_FetchImages(t *testing.T) {
a, s := getMockAdapter(t, true, true)
defer s.Close()
var filters = []*model.Filter{}
var resources, err = a.FetchImages(filters)
assert.NotNil(t, err)
assert.Nil(t, resources)
}
func Test_aliyunAuthCredential_isCacheTokenValid(t *testing.T) {
type fields struct {
region string
accessKey string
secretKey string
cacheToken *registryTemporaryToken
cacheTokenExpiredAt time.Time
}
var nilTime time.Time
tests := []struct {
name string
fields fields
want bool
}{
{"nil cacheTokenExpiredAt", fields{"test-region", "MockAccessKey", "MockSecretKey", nil, nilTime}, false},
{"nil cacheToken", fields{"test-region", "MockAccessKey", "MockSecretKey", nil, time.Time{}}, false},
{"expired", fields{"test-region", "MockAccessKey", "MockSecretKey", &registryTemporaryToken{}, time.Now().AddDate(0, 0, -1)}, false},
{"ok", fields{"test-region", "MockAccessKey", "MockSecretKey", &registryTemporaryToken{}, time.Now().AddDate(0, 0, 1)}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
a := &aliyunAuthCredential{
region: tt.fields.region,
accessKey: tt.fields.accessKey,
secretKey: tt.fields.secretKey,
cacheToken: tt.fields.cacheToken,
cacheTokenExpiredAt: tt.fields.cacheTokenExpiredAt,
}
if got := a.isCacheTokenValid(); got != tt.want {
assert.Equal(t, got, tt.want)
}
})
}
}

View File

@ -0,0 +1,84 @@
package aliacr
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cr"
"github.com/goharbor/harbor/src/common/http/modifier"
"github.com/goharbor/harbor/src/common/utils/log"
)
// Credential ...
type Credential modifier.Modifier
// Implements interface Credential
type aliyunAuthCredential struct {
region string
accessKey string
secretKey string
cacheToken *registryTemporaryToken
cacheTokenExpiredAt time.Time
}
type registryTemporaryToken struct {
user string
password string
}
var _ Credential = &aliyunAuthCredential{}
// NewAuth will get a temporary docker registry username and password via aliyun cr service API.
func NewAuth(region, accessKey, secretKey string) Credential {
return &aliyunAuthCredential{
region: region,
accessKey: accessKey,
secretKey: secretKey,
cacheToken: &registryTemporaryToken{},
}
}
func (a *aliyunAuthCredential) Modify(r *http.Request) (err error) {
if !a.isCacheTokenValid() {
log.Debugf("[aliyunAuthCredential.Modify.updateToken]Host: %s\n", r.Host)
var client *cr.Client
client, err = cr.NewClientWithAccessKey(a.region, a.accessKey, a.secretKey)
if err != nil {
return
}
var tokenRequest = cr.CreateGetAuthorizationTokenRequest()
var tokenResponse = cr.CreateGetAuthorizationTokenResponse()
tokenRequest.SetDomain(fmt.Sprintf(endpointTpl, a.region))
tokenResponse, err = client.GetAuthorizationToken(tokenRequest)
if err != nil {
return
}
var v authorizationToken
json.Unmarshal(tokenResponse.GetHttpContentBytes(), &v)
a.cacheTokenExpiredAt = v.Data.ExpireDate.ToTime()
a.cacheToken.user = v.Data.TempUserName
a.cacheToken.password = v.Data.AuthorizationToken
} else {
log.Debug("[aliyunAuthCredential] USE CACHE TOKEN!!!")
}
r.SetBasicAuth(a.cacheToken.user, a.cacheToken.password)
return
}
func (a *aliyunAuthCredential) isCacheTokenValid() bool {
if &a.cacheTokenExpiredAt == nil {
return false
}
if a.cacheToken == nil {
return false
}
if time.Now().After(a.cacheTokenExpiredAt) {
return false
}
return true
}

View File

@ -0,0 +1,79 @@
package aliacr
import "time"
const (
defaultTemporaryTokenExpiredTime = time.Hour * 1
registryEndpointTpl = "https://registry.%s.aliyuncs.com"
endpointTpl = "cr.%s.aliyuncs.com"
)
type authorizationToken struct {
Data struct {
ExpireDate timeUnix `json:"expireDate"`
AuthorizationToken string `json:"authorizationToken"`
TempUserName string `json:"tempUserName"`
} `json:"data"`
RequestID string `json:"requestId"`
}
type timeUnix int64
func (t timeUnix) ToTime() time.Time {
return time.Unix(int64(t)/1000, 0)
}
func (t timeUnix) String() string {
return t.ToTime().String()
}
type aliRepoResp struct {
Data struct {
Page int `json:"page"`
Total int `json:"total"`
PageSize int `json:"pageSize"`
Repos []aliRepo `json:"repos"`
} `json:"data"`
RequestID string `json:"requestId"`
}
type aliRepo struct {
Summary string `json:"summary"`
RegionID string `json:"regionId"`
RepoName string `json:"repoName"`
RepoNamespace string `json:"repoNamespace"`
RepoStatus string `json:"repoStatus"`
RepoID int `json:"repoId"`
RepoType string `json:"repoType"`
RepoBuildType string `json:"repoBuildType"`
GmtCreate int64 `json:"gmtCreate"`
RepoOriginType string `json:"repoOriginType"`
GmtModified int64 `json:"gmtModified"`
RepoDomainList struct {
Internal string `json:"internal"`
Public string `json:"public"`
Vpc string `json:"vpc"`
} `json:"repoDomainList"`
Downloads int `json:"downloads"`
RepoAuthorizeType string `json:"repoAuthorizeType"`
Logo string `json:"logo"`
Stars int `json:"stars"`
}
type aliTagResp struct {
Data struct {
Total int `json:"total"`
PageSize int `json:"pageSize"`
Page int `json:"page"`
Tags []struct {
ImageUpdate int64 `json:"imageUpdate"`
ImageID string `json:"imageId"`
Digest string `json:"digest"`
ImageSize int `json:"imageSize"`
Tag string `json:"tag"`
ImageCreate int64 `json:"imageCreate"`
Status string `json:"status"`
} `json:"tags"`
} `json:"data"`
RequestID string `json:"requestId"`
}

View File

@ -29,6 +29,7 @@ const (
RegistryTypeGoogleGcr RegistryType = "google-gcr"
RegistryTypeAwsEcr RegistryType = "aws-ecr"
RegistryTypeAzureAcr RegistryType = "azure-acr"
RegistryTypeAliAcr RegistryType = "ali-acr"
RegistryTypeHelmHub RegistryType = "helm-hub"

View File

@ -41,6 +41,8 @@ import (
_ "github.com/goharbor/harbor/src/replication/adapter/awsecr"
// register the AzureAcr adapter
_ "github.com/goharbor/harbor/src/replication/adapter/azurecr"
// register the AliACR adapter
_ "github.com/goharbor/harbor/src/replication/adapter/aliacr"
)
var (

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 [yyyy] [name of copyright owner]
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 = time.Second * 1
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,158 @@
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 {
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,136 @@
/*
* 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))
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,766 @@
/*
* 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
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
}
// 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.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) {
if client.EndpointType == "regional" {
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
}
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.EndpointType != "" {
if client.EndpointMap != nil && client.Network == "" || client.Network == "public" {
endpoint = client.EndpointMap[regionId]
}
if endpoint == "" {
endpoint = client.GetEndpointRules(regionId, request.GetProduct())
}
}
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 {
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 {
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 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 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,91 @@
/*
* 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:""`
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,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"
)
const keyFormatter = "%s::%s"
var endpointMapping = make(map[string]string)
// AddEndpointMapping Use product id and region id as key to store the endpoint into inner map
func AddEndpointMapping(regionId, productId, endpoint string) (err error) {
key := fmt.Sprintf(keyFormatter, strings.ToLower(regionId), strings.ToLower(productId))
endpointMapping[key] = endpoint
return nil
}
// MappingResolver the mapping resolver type
type MappingResolver struct {
}
// GetName get the resolver name: "mapping resolver"
func (resolver *MappingResolver) GetName() (name string) {
name = "mapping resolver"
return
}
// TryResolve use Product and RegionId as key to find endpoint from inner map
func (resolver *MappingResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) {
key := fmt.Sprintf(keyFormatter, strings.ToLower(param.RegionId), strings.ToLower(param.Product))
endpoint, contains := endpointMapping[key]
return endpoint, contains, nil
}

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 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{
&SimpleHostResolver{},
&MappingResolver{},
&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,33 @@
/*
* 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
// SimpleHostResolver the simple host resolver type
type SimpleHostResolver struct {
}
// GetName get the resolver name: "simple host resolver"
func (resolver *SimpleHostResolver) GetName() (name string) {
name = "simple host resolver"
return
}
// TryResolve if the Domain exist in param, use it as endpoint
func (resolver *SimpleHostResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) {
if support = len(param.Domain) > 0; support {
endpoint = param.Domain
}
return
}

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,378 @@
/*
* 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"
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)
}
err = addParam(request, fieldPosition, key, value)
if err != nil {
return
}
} else if typeTag == "Repeated" {
// repeated param
repeatedFieldValue := dataValue.Field(i)
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
}
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,105 @@
package cr
//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"
)
// CancelRepoBuild invokes the cr.CancelRepoBuild API synchronously
// api document: https://help.aliyun.com/api/cr/cancelrepobuild.html
func (client *Client) CancelRepoBuild(request *CancelRepoBuildRequest) (response *CancelRepoBuildResponse, err error) {
response = CreateCancelRepoBuildResponse()
err = client.DoAction(request, response)
return
}
// CancelRepoBuildWithChan invokes the cr.CancelRepoBuild API asynchronously
// api document: https://help.aliyun.com/api/cr/cancelrepobuild.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CancelRepoBuildWithChan(request *CancelRepoBuildRequest) (<-chan *CancelRepoBuildResponse, <-chan error) {
responseChan := make(chan *CancelRepoBuildResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CancelRepoBuild(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CancelRepoBuildWithCallback invokes the cr.CancelRepoBuild API asynchronously
// api document: https://help.aliyun.com/api/cr/cancelrepobuild.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CancelRepoBuildWithCallback(request *CancelRepoBuildRequest, callback func(response *CancelRepoBuildResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CancelRepoBuildResponse
var err error
defer close(result)
response, err = client.CancelRepoBuild(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CancelRepoBuildRequest is the request struct for api CancelRepoBuild
type CancelRepoBuildRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
BuildId string `position:"Path" name:"BuildId"`
}
// CancelRepoBuildResponse is the response struct for api CancelRepoBuild
type CancelRepoBuildResponse struct {
*responses.BaseResponse
}
// CreateCancelRepoBuildRequest creates a request to invoke CancelRepoBuild API
func CreateCancelRepoBuildRequest() (request *CancelRepoBuildRequest) {
request = &CancelRepoBuildRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CancelRepoBuild", "/repos/[RepoNamespace]/[RepoName]/build/[BuildId]/cancel", "cr", "openAPI")
request.Method = requests.POST
return
}
// CreateCancelRepoBuildResponse creates a response to parse from CancelRepoBuild response
func CreateCancelRepoBuildResponse() (response *CancelRepoBuildResponse) {
response = &CancelRepoBuildResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,81 @@
package cr
//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"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
)
// Client is the sdk client struct, each func corresponds to an OpenAPI
type Client struct {
sdk.Client
}
// NewClient creates a sdk client with environment variables
func NewClient() (client *Client, err error) {
client = &Client{}
err = client.Init()
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)
return
}
// NewClientWithAccessKey is a shortcut to create sdk client with accesskey
// usage: https://help.aliyun.com/document_detail/66217.html
func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
client = &Client{}
err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
return
}
// NewClientWithStsToken is a shortcut to create sdk client with sts token
// usage: https://help.aliyun.com/document_detail/66222.html
func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn
// usage: https://help.aliyun.com/document_detail/66222.html
func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
return
}
// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role
// usage: https://help.aliyun.com/document_detail/66223.html
func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithEcsRamRole(regionId, roleName)
return
}
// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair
// attention: rsa key pair auth is only Japan regions available
func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
client = &Client{}
err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
return
}

View File

@ -0,0 +1,102 @@
package cr
//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"
)
// CreateCollection invokes the cr.CreateCollection API synchronously
// api document: https://help.aliyun.com/api/cr/createcollection.html
func (client *Client) CreateCollection(request *CreateCollectionRequest) (response *CreateCollectionResponse, err error) {
response = CreateCreateCollectionResponse()
err = client.DoAction(request, response)
return
}
// CreateCollectionWithChan invokes the cr.CreateCollection API asynchronously
// api document: https://help.aliyun.com/api/cr/createcollection.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateCollectionWithChan(request *CreateCollectionRequest) (<-chan *CreateCollectionResponse, <-chan error) {
responseChan := make(chan *CreateCollectionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateCollection(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateCollectionWithCallback invokes the cr.CreateCollection API asynchronously
// api document: https://help.aliyun.com/api/cr/createcollection.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateCollectionWithCallback(request *CreateCollectionRequest, callback func(response *CreateCollectionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateCollectionResponse
var err error
defer close(result)
response, err = client.CreateCollection(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateCollectionRequest is the request struct for api CreateCollection
type CreateCollectionRequest struct {
*requests.RoaRequest
}
// CreateCollectionResponse is the response struct for api CreateCollection
type CreateCollectionResponse struct {
*responses.BaseResponse
}
// CreateCreateCollectionRequest creates a request to invoke CreateCollection API
func CreateCreateCollectionRequest() (request *CreateCollectionRequest) {
request = &CreateCollectionRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateCollection", "/collections", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateCollectionResponse creates a response to parse from CreateCollection response
func CreateCreateCollectionResponse() (response *CreateCollectionResponse) {
response = &CreateCollectionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,102 @@
package cr
//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"
)
// CreateNamespace invokes the cr.CreateNamespace API synchronously
// api document: https://help.aliyun.com/api/cr/createnamespace.html
func (client *Client) CreateNamespace(request *CreateNamespaceRequest) (response *CreateNamespaceResponse, err error) {
response = CreateCreateNamespaceResponse()
err = client.DoAction(request, response)
return
}
// CreateNamespaceWithChan invokes the cr.CreateNamespace API asynchronously
// api document: https://help.aliyun.com/api/cr/createnamespace.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateNamespaceWithChan(request *CreateNamespaceRequest) (<-chan *CreateNamespaceResponse, <-chan error) {
responseChan := make(chan *CreateNamespaceResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateNamespace(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateNamespaceWithCallback invokes the cr.CreateNamespace API asynchronously
// api document: https://help.aliyun.com/api/cr/createnamespace.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateNamespaceWithCallback(request *CreateNamespaceRequest, callback func(response *CreateNamespaceResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateNamespaceResponse
var err error
defer close(result)
response, err = client.CreateNamespace(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateNamespaceRequest is the request struct for api CreateNamespace
type CreateNamespaceRequest struct {
*requests.RoaRequest
}
// CreateNamespaceResponse is the response struct for api CreateNamespace
type CreateNamespaceResponse struct {
*responses.BaseResponse
}
// CreateCreateNamespaceRequest creates a request to invoke CreateNamespace API
func CreateCreateNamespaceRequest() (request *CreateNamespaceRequest) {
request = &CreateNamespaceRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateNamespace", "/namespace", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateNamespaceResponse creates a response to parse from CreateNamespace response
func CreateCreateNamespaceResponse() (response *CreateNamespaceResponse) {
response = &CreateNamespaceResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package cr
//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"
)
// CreateNamespaceAuthorization invokes the cr.CreateNamespaceAuthorization API synchronously
// api document: https://help.aliyun.com/api/cr/createnamespaceauthorization.html
func (client *Client) CreateNamespaceAuthorization(request *CreateNamespaceAuthorizationRequest) (response *CreateNamespaceAuthorizationResponse, err error) {
response = CreateCreateNamespaceAuthorizationResponse()
err = client.DoAction(request, response)
return
}
// CreateNamespaceAuthorizationWithChan invokes the cr.CreateNamespaceAuthorization API asynchronously
// api document: https://help.aliyun.com/api/cr/createnamespaceauthorization.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateNamespaceAuthorizationWithChan(request *CreateNamespaceAuthorizationRequest) (<-chan *CreateNamespaceAuthorizationResponse, <-chan error) {
responseChan := make(chan *CreateNamespaceAuthorizationResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateNamespaceAuthorization(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateNamespaceAuthorizationWithCallback invokes the cr.CreateNamespaceAuthorization API asynchronously
// api document: https://help.aliyun.com/api/cr/createnamespaceauthorization.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateNamespaceAuthorizationWithCallback(request *CreateNamespaceAuthorizationRequest, callback func(response *CreateNamespaceAuthorizationResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateNamespaceAuthorizationResponse
var err error
defer close(result)
response, err = client.CreateNamespaceAuthorization(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateNamespaceAuthorizationRequest is the request struct for api CreateNamespaceAuthorization
type CreateNamespaceAuthorizationRequest struct {
*requests.RoaRequest
Namespace string `position:"Path" name:"Namespace"`
}
// CreateNamespaceAuthorizationResponse is the response struct for api CreateNamespaceAuthorization
type CreateNamespaceAuthorizationResponse struct {
*responses.BaseResponse
}
// CreateCreateNamespaceAuthorizationRequest creates a request to invoke CreateNamespaceAuthorization API
func CreateCreateNamespaceAuthorizationRequest() (request *CreateNamespaceAuthorizationRequest) {
request = &CreateNamespaceAuthorizationRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateNamespaceAuthorization", "/namespace/[Namespace]/authorizations", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateNamespaceAuthorizationResponse creates a response to parse from CreateNamespaceAuthorization response
func CreateCreateNamespaceAuthorizationResponse() (response *CreateNamespaceAuthorizationResponse) {
response = &CreateNamespaceAuthorizationResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,102 @@
package cr
//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"
)
// CreateRepo invokes the cr.CreateRepo API synchronously
// api document: https://help.aliyun.com/api/cr/createrepo.html
func (client *Client) CreateRepo(request *CreateRepoRequest) (response *CreateRepoResponse, err error) {
response = CreateCreateRepoResponse()
err = client.DoAction(request, response)
return
}
// CreateRepoWithChan invokes the cr.CreateRepo API asynchronously
// api document: https://help.aliyun.com/api/cr/createrepo.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoWithChan(request *CreateRepoRequest) (<-chan *CreateRepoResponse, <-chan error) {
responseChan := make(chan *CreateRepoResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateRepo(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateRepoWithCallback invokes the cr.CreateRepo API asynchronously
// api document: https://help.aliyun.com/api/cr/createrepo.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoWithCallback(request *CreateRepoRequest, callback func(response *CreateRepoResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateRepoResponse
var err error
defer close(result)
response, err = client.CreateRepo(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateRepoRequest is the request struct for api CreateRepo
type CreateRepoRequest struct {
*requests.RoaRequest
}
// CreateRepoResponse is the response struct for api CreateRepo
type CreateRepoResponse struct {
*responses.BaseResponse
}
// CreateCreateRepoRequest creates a request to invoke CreateRepo API
func CreateCreateRepoRequest() (request *CreateRepoRequest) {
request = &CreateRepoRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateRepo", "/repos", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateRepoResponse creates a response to parse from CreateRepo response
func CreateCreateRepoResponse() (response *CreateRepoResponse) {
response = &CreateRepoResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// CreateRepoAuthorization invokes the cr.CreateRepoAuthorization API synchronously
// api document: https://help.aliyun.com/api/cr/createrepoauthorization.html
func (client *Client) CreateRepoAuthorization(request *CreateRepoAuthorizationRequest) (response *CreateRepoAuthorizationResponse, err error) {
response = CreateCreateRepoAuthorizationResponse()
err = client.DoAction(request, response)
return
}
// CreateRepoAuthorizationWithChan invokes the cr.CreateRepoAuthorization API asynchronously
// api document: https://help.aliyun.com/api/cr/createrepoauthorization.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoAuthorizationWithChan(request *CreateRepoAuthorizationRequest) (<-chan *CreateRepoAuthorizationResponse, <-chan error) {
responseChan := make(chan *CreateRepoAuthorizationResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateRepoAuthorization(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateRepoAuthorizationWithCallback invokes the cr.CreateRepoAuthorization API asynchronously
// api document: https://help.aliyun.com/api/cr/createrepoauthorization.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoAuthorizationWithCallback(request *CreateRepoAuthorizationRequest, callback func(response *CreateRepoAuthorizationResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateRepoAuthorizationResponse
var err error
defer close(result)
response, err = client.CreateRepoAuthorization(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateRepoAuthorizationRequest is the request struct for api CreateRepoAuthorization
type CreateRepoAuthorizationRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
}
// CreateRepoAuthorizationResponse is the response struct for api CreateRepoAuthorization
type CreateRepoAuthorizationResponse struct {
*responses.BaseResponse
}
// CreateCreateRepoAuthorizationRequest creates a request to invoke CreateRepoAuthorization API
func CreateCreateRepoAuthorizationRequest() (request *CreateRepoAuthorizationRequest) {
request = &CreateRepoAuthorizationRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateRepoAuthorization", "/repos/[RepoNamespace]/[RepoName]/authorizations", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateRepoAuthorizationResponse creates a response to parse from CreateRepoAuthorization response
func CreateCreateRepoAuthorizationResponse() (response *CreateRepoAuthorizationResponse) {
response = &CreateRepoAuthorizationResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// CreateRepoBuildRule invokes the cr.CreateRepoBuildRule API synchronously
// api document: https://help.aliyun.com/api/cr/createrepobuildrule.html
func (client *Client) CreateRepoBuildRule(request *CreateRepoBuildRuleRequest) (response *CreateRepoBuildRuleResponse, err error) {
response = CreateCreateRepoBuildRuleResponse()
err = client.DoAction(request, response)
return
}
// CreateRepoBuildRuleWithChan invokes the cr.CreateRepoBuildRule API asynchronously
// api document: https://help.aliyun.com/api/cr/createrepobuildrule.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoBuildRuleWithChan(request *CreateRepoBuildRuleRequest) (<-chan *CreateRepoBuildRuleResponse, <-chan error) {
responseChan := make(chan *CreateRepoBuildRuleResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateRepoBuildRule(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateRepoBuildRuleWithCallback invokes the cr.CreateRepoBuildRule API asynchronously
// api document: https://help.aliyun.com/api/cr/createrepobuildrule.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoBuildRuleWithCallback(request *CreateRepoBuildRuleRequest, callback func(response *CreateRepoBuildRuleResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateRepoBuildRuleResponse
var err error
defer close(result)
response, err = client.CreateRepoBuildRule(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateRepoBuildRuleRequest is the request struct for api CreateRepoBuildRule
type CreateRepoBuildRuleRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
}
// CreateRepoBuildRuleResponse is the response struct for api CreateRepoBuildRule
type CreateRepoBuildRuleResponse struct {
*responses.BaseResponse
}
// CreateCreateRepoBuildRuleRequest creates a request to invoke CreateRepoBuildRule API
func CreateCreateRepoBuildRuleRequest() (request *CreateRepoBuildRuleRequest) {
request = &CreateRepoBuildRuleRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateRepoBuildRule", "/repos/[RepoNamespace]/[RepoName]/rules", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateRepoBuildRuleResponse creates a response to parse from CreateRepoBuildRule response
func CreateCreateRepoBuildRuleResponse() (response *CreateRepoBuildRuleResponse) {
response = &CreateRepoBuildRuleResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// CreateRepoSyncTask invokes the cr.CreateRepoSyncTask API synchronously
// api document: https://help.aliyun.com/api/cr/createreposynctask.html
func (client *Client) CreateRepoSyncTask(request *CreateRepoSyncTaskRequest) (response *CreateRepoSyncTaskResponse, err error) {
response = CreateCreateRepoSyncTaskResponse()
err = client.DoAction(request, response)
return
}
// CreateRepoSyncTaskWithChan invokes the cr.CreateRepoSyncTask API asynchronously
// api document: https://help.aliyun.com/api/cr/createreposynctask.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoSyncTaskWithChan(request *CreateRepoSyncTaskRequest) (<-chan *CreateRepoSyncTaskResponse, <-chan error) {
responseChan := make(chan *CreateRepoSyncTaskResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateRepoSyncTask(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateRepoSyncTaskWithCallback invokes the cr.CreateRepoSyncTask API asynchronously
// api document: https://help.aliyun.com/api/cr/createreposynctask.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoSyncTaskWithCallback(request *CreateRepoSyncTaskRequest, callback func(response *CreateRepoSyncTaskResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateRepoSyncTaskResponse
var err error
defer close(result)
response, err = client.CreateRepoSyncTask(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateRepoSyncTaskRequest is the request struct for api CreateRepoSyncTask
type CreateRepoSyncTaskRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
}
// CreateRepoSyncTaskResponse is the response struct for api CreateRepoSyncTask
type CreateRepoSyncTaskResponse struct {
*responses.BaseResponse
}
// CreateCreateRepoSyncTaskRequest creates a request to invoke CreateRepoSyncTask API
func CreateCreateRepoSyncTaskRequest() (request *CreateRepoSyncTaskRequest) {
request = &CreateRepoSyncTaskRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateRepoSyncTask", "/repos/[RepoNamespace]/[RepoName]/syncTasks", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateRepoSyncTaskResponse creates a response to parse from CreateRepoSyncTask response
func CreateCreateRepoSyncTaskResponse() (response *CreateRepoSyncTaskResponse) {
response = &CreateRepoSyncTaskResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// CreateRepoWebhook invokes the cr.CreateRepoWebhook API synchronously
// api document: https://help.aliyun.com/api/cr/createrepowebhook.html
func (client *Client) CreateRepoWebhook(request *CreateRepoWebhookRequest) (response *CreateRepoWebhookResponse, err error) {
response = CreateCreateRepoWebhookResponse()
err = client.DoAction(request, response)
return
}
// CreateRepoWebhookWithChan invokes the cr.CreateRepoWebhook API asynchronously
// api document: https://help.aliyun.com/api/cr/createrepowebhook.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoWebhookWithChan(request *CreateRepoWebhookRequest) (<-chan *CreateRepoWebhookResponse, <-chan error) {
responseChan := make(chan *CreateRepoWebhookResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateRepoWebhook(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateRepoWebhookWithCallback invokes the cr.CreateRepoWebhook API asynchronously
// api document: https://help.aliyun.com/api/cr/createrepowebhook.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateRepoWebhookWithCallback(request *CreateRepoWebhookRequest, callback func(response *CreateRepoWebhookResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateRepoWebhookResponse
var err error
defer close(result)
response, err = client.CreateRepoWebhook(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateRepoWebhookRequest is the request struct for api CreateRepoWebhook
type CreateRepoWebhookRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
}
// CreateRepoWebhookResponse is the response struct for api CreateRepoWebhook
type CreateRepoWebhookResponse struct {
*responses.BaseResponse
}
// CreateCreateRepoWebhookRequest creates a request to invoke CreateRepoWebhook API
func CreateCreateRepoWebhookRequest() (request *CreateRepoWebhookRequest) {
request = &CreateRepoWebhookRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateRepoWebhook", "/repos/[RepoNamespace]/[RepoName]/webhooks", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateRepoWebhookResponse creates a response to parse from CreateRepoWebhook response
func CreateCreateRepoWebhookResponse() (response *CreateRepoWebhookResponse) {
response = &CreateRepoWebhookResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,102 @@
package cr
//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"
)
// CreateUserInfo invokes the cr.CreateUserInfo API synchronously
// api document: https://help.aliyun.com/api/cr/createuserinfo.html
func (client *Client) CreateUserInfo(request *CreateUserInfoRequest) (response *CreateUserInfoResponse, err error) {
response = CreateCreateUserInfoResponse()
err = client.DoAction(request, response)
return
}
// CreateUserInfoWithChan invokes the cr.CreateUserInfo API asynchronously
// api document: https://help.aliyun.com/api/cr/createuserinfo.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateUserInfoWithChan(request *CreateUserInfoRequest) (<-chan *CreateUserInfoResponse, <-chan error) {
responseChan := make(chan *CreateUserInfoResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateUserInfo(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateUserInfoWithCallback invokes the cr.CreateUserInfo API asynchronously
// api document: https://help.aliyun.com/api/cr/createuserinfo.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateUserInfoWithCallback(request *CreateUserInfoRequest, callback func(response *CreateUserInfoResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateUserInfoResponse
var err error
defer close(result)
response, err = client.CreateUserInfo(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateUserInfoRequest is the request struct for api CreateUserInfo
type CreateUserInfoRequest struct {
*requests.RoaRequest
}
// CreateUserInfoResponse is the response struct for api CreateUserInfo
type CreateUserInfoResponse struct {
*responses.BaseResponse
}
// CreateCreateUserInfoRequest creates a request to invoke CreateUserInfo API
func CreateCreateUserInfoRequest() (request *CreateUserInfoRequest) {
request = &CreateUserInfoRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateUserInfo", "/users", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateUserInfoResponse creates a response to parse from CreateUserInfo response
func CreateCreateUserInfoResponse() (response *CreateUserInfoResponse) {
response = &CreateUserInfoResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,102 @@
package cr
//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"
)
// CreateUserSourceAccount invokes the cr.CreateUserSourceAccount API synchronously
// api document: https://help.aliyun.com/api/cr/createusersourceaccount.html
func (client *Client) CreateUserSourceAccount(request *CreateUserSourceAccountRequest) (response *CreateUserSourceAccountResponse, err error) {
response = CreateCreateUserSourceAccountResponse()
err = client.DoAction(request, response)
return
}
// CreateUserSourceAccountWithChan invokes the cr.CreateUserSourceAccount API asynchronously
// api document: https://help.aliyun.com/api/cr/createusersourceaccount.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateUserSourceAccountWithChan(request *CreateUserSourceAccountRequest) (<-chan *CreateUserSourceAccountResponse, <-chan error) {
responseChan := make(chan *CreateUserSourceAccountResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.CreateUserSourceAccount(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// CreateUserSourceAccountWithCallback invokes the cr.CreateUserSourceAccount API asynchronously
// api document: https://help.aliyun.com/api/cr/createusersourceaccount.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CreateUserSourceAccountWithCallback(request *CreateUserSourceAccountRequest, callback func(response *CreateUserSourceAccountResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *CreateUserSourceAccountResponse
var err error
defer close(result)
response, err = client.CreateUserSourceAccount(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// CreateUserSourceAccountRequest is the request struct for api CreateUserSourceAccount
type CreateUserSourceAccountRequest struct {
*requests.RoaRequest
}
// CreateUserSourceAccountResponse is the response struct for api CreateUserSourceAccount
type CreateUserSourceAccountResponse struct {
*responses.BaseResponse
}
// CreateCreateUserSourceAccountRequest creates a request to invoke CreateUserSourceAccount API
func CreateCreateUserSourceAccountRequest() (request *CreateUserSourceAccountRequest) {
request = &CreateUserSourceAccountRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "CreateUserSourceAccount", "/users/sourceAccount", "cr", "openAPI")
request.Method = requests.PUT
return
}
// CreateCreateUserSourceAccountResponse creates a response to parse from CreateUserSourceAccount response
func CreateCreateUserSourceAccountResponse() (response *CreateUserSourceAccountResponse) {
response = &CreateUserSourceAccountResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package cr
//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"
)
// DeleteCollection invokes the cr.DeleteCollection API synchronously
// api document: https://help.aliyun.com/api/cr/deletecollection.html
func (client *Client) DeleteCollection(request *DeleteCollectionRequest) (response *DeleteCollectionResponse, err error) {
response = CreateDeleteCollectionResponse()
err = client.DoAction(request, response)
return
}
// DeleteCollectionWithChan invokes the cr.DeleteCollection API asynchronously
// api document: https://help.aliyun.com/api/cr/deletecollection.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteCollectionWithChan(request *DeleteCollectionRequest) (<-chan *DeleteCollectionResponse, <-chan error) {
responseChan := make(chan *DeleteCollectionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteCollection(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteCollectionWithCallback invokes the cr.DeleteCollection API asynchronously
// api document: https://help.aliyun.com/api/cr/deletecollection.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteCollectionWithCallback(request *DeleteCollectionRequest, callback func(response *DeleteCollectionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteCollectionResponse
var err error
defer close(result)
response, err = client.DeleteCollection(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteCollectionRequest is the request struct for api DeleteCollection
type DeleteCollectionRequest struct {
*requests.RoaRequest
CollectionId requests.Integer `position:"Path" name:"CollectionId"`
}
// DeleteCollectionResponse is the response struct for api DeleteCollection
type DeleteCollectionResponse struct {
*responses.BaseResponse
}
// CreateDeleteCollectionRequest creates a request to invoke DeleteCollection API
func CreateDeleteCollectionRequest() (request *DeleteCollectionRequest) {
request = &DeleteCollectionRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "DeleteCollection", "/collections/[CollectionId]", "cr", "openAPI")
request.Method = requests.DELETE
return
}
// CreateDeleteCollectionResponse creates a response to parse from DeleteCollection response
func CreateDeleteCollectionResponse() (response *DeleteCollectionResponse) {
response = &DeleteCollectionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// DeleteImage invokes the cr.DeleteImage API synchronously
// api document: https://help.aliyun.com/api/cr/deleteimage.html
func (client *Client) DeleteImage(request *DeleteImageRequest) (response *DeleteImageResponse, err error) {
response = CreateDeleteImageResponse()
err = client.DoAction(request, response)
return
}
// DeleteImageWithChan invokes the cr.DeleteImage API asynchronously
// api document: https://help.aliyun.com/api/cr/deleteimage.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteImageWithChan(request *DeleteImageRequest) (<-chan *DeleteImageResponse, <-chan error) {
responseChan := make(chan *DeleteImageResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteImage(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteImageWithCallback invokes the cr.DeleteImage API asynchronously
// api document: https://help.aliyun.com/api/cr/deleteimage.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteImageWithCallback(request *DeleteImageRequest, callback func(response *DeleteImageResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteImageResponse
var err error
defer close(result)
response, err = client.DeleteImage(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteImageRequest is the request struct for api DeleteImage
type DeleteImageRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
Tag string `position:"Path" name:"Tag"`
}
// DeleteImageResponse is the response struct for api DeleteImage
type DeleteImageResponse struct {
*responses.BaseResponse
}
// CreateDeleteImageRequest creates a request to invoke DeleteImage API
func CreateDeleteImageRequest() (request *DeleteImageRequest) {
request = &DeleteImageRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "DeleteImage", "/repos/[RepoNamespace]/[RepoName]/tags/[Tag]", "cr", "openAPI")
request.Method = requests.DELETE
return
}
// CreateDeleteImageResponse creates a response to parse from DeleteImage response
func CreateDeleteImageResponse() (response *DeleteImageResponse) {
response = &DeleteImageResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package cr
//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"
)
// DeleteNamespace invokes the cr.DeleteNamespace API synchronously
// api document: https://help.aliyun.com/api/cr/deletenamespace.html
func (client *Client) DeleteNamespace(request *DeleteNamespaceRequest) (response *DeleteNamespaceResponse, err error) {
response = CreateDeleteNamespaceResponse()
err = client.DoAction(request, response)
return
}
// DeleteNamespaceWithChan invokes the cr.DeleteNamespace API asynchronously
// api document: https://help.aliyun.com/api/cr/deletenamespace.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteNamespaceWithChan(request *DeleteNamespaceRequest) (<-chan *DeleteNamespaceResponse, <-chan error) {
responseChan := make(chan *DeleteNamespaceResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteNamespace(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteNamespaceWithCallback invokes the cr.DeleteNamespace API asynchronously
// api document: https://help.aliyun.com/api/cr/deletenamespace.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteNamespaceWithCallback(request *DeleteNamespaceRequest, callback func(response *DeleteNamespaceResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteNamespaceResponse
var err error
defer close(result)
response, err = client.DeleteNamespace(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteNamespaceRequest is the request struct for api DeleteNamespace
type DeleteNamespaceRequest struct {
*requests.RoaRequest
Namespace string `position:"Path" name:"Namespace"`
}
// DeleteNamespaceResponse is the response struct for api DeleteNamespace
type DeleteNamespaceResponse struct {
*responses.BaseResponse
}
// CreateDeleteNamespaceRequest creates a request to invoke DeleteNamespace API
func CreateDeleteNamespaceRequest() (request *DeleteNamespaceRequest) {
request = &DeleteNamespaceRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "DeleteNamespace", "/namespace/[Namespace]", "cr", "openAPI")
request.Method = requests.DELETE
return
}
// CreateDeleteNamespaceResponse creates a response to parse from DeleteNamespace response
func CreateDeleteNamespaceResponse() (response *DeleteNamespaceResponse) {
response = &DeleteNamespaceResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// DeleteNamespaceAuthorization invokes the cr.DeleteNamespaceAuthorization API synchronously
// api document: https://help.aliyun.com/api/cr/deletenamespaceauthorization.html
func (client *Client) DeleteNamespaceAuthorization(request *DeleteNamespaceAuthorizationRequest) (response *DeleteNamespaceAuthorizationResponse, err error) {
response = CreateDeleteNamespaceAuthorizationResponse()
err = client.DoAction(request, response)
return
}
// DeleteNamespaceAuthorizationWithChan invokes the cr.DeleteNamespaceAuthorization API asynchronously
// api document: https://help.aliyun.com/api/cr/deletenamespaceauthorization.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteNamespaceAuthorizationWithChan(request *DeleteNamespaceAuthorizationRequest) (<-chan *DeleteNamespaceAuthorizationResponse, <-chan error) {
responseChan := make(chan *DeleteNamespaceAuthorizationResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteNamespaceAuthorization(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteNamespaceAuthorizationWithCallback invokes the cr.DeleteNamespaceAuthorization API asynchronously
// api document: https://help.aliyun.com/api/cr/deletenamespaceauthorization.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteNamespaceAuthorizationWithCallback(request *DeleteNamespaceAuthorizationRequest, callback func(response *DeleteNamespaceAuthorizationResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteNamespaceAuthorizationResponse
var err error
defer close(result)
response, err = client.DeleteNamespaceAuthorization(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteNamespaceAuthorizationRequest is the request struct for api DeleteNamespaceAuthorization
type DeleteNamespaceAuthorizationRequest struct {
*requests.RoaRequest
AuthorizeId requests.Integer `position:"Path" name:"AuthorizeId"`
Namespace string `position:"Path" name:"Namespace"`
}
// DeleteNamespaceAuthorizationResponse is the response struct for api DeleteNamespaceAuthorization
type DeleteNamespaceAuthorizationResponse struct {
*responses.BaseResponse
}
// CreateDeleteNamespaceAuthorizationRequest creates a request to invoke DeleteNamespaceAuthorization API
func CreateDeleteNamespaceAuthorizationRequest() (request *DeleteNamespaceAuthorizationRequest) {
request = &DeleteNamespaceAuthorizationRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "DeleteNamespaceAuthorization", "/namespace/[Namespace]/authorizations/[AuthorizeId]", "cr", "openAPI")
request.Method = requests.DELETE
return
}
// CreateDeleteNamespaceAuthorizationResponse creates a response to parse from DeleteNamespaceAuthorization response
func CreateDeleteNamespaceAuthorizationResponse() (response *DeleteNamespaceAuthorizationResponse) {
response = &DeleteNamespaceAuthorizationResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// DeleteRepo invokes the cr.DeleteRepo API synchronously
// api document: https://help.aliyun.com/api/cr/deleterepo.html
func (client *Client) DeleteRepo(request *DeleteRepoRequest) (response *DeleteRepoResponse, err error) {
response = CreateDeleteRepoResponse()
err = client.DoAction(request, response)
return
}
// DeleteRepoWithChan invokes the cr.DeleteRepo API asynchronously
// api document: https://help.aliyun.com/api/cr/deleterepo.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRepoWithChan(request *DeleteRepoRequest) (<-chan *DeleteRepoResponse, <-chan error) {
responseChan := make(chan *DeleteRepoResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteRepo(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteRepoWithCallback invokes the cr.DeleteRepo API asynchronously
// api document: https://help.aliyun.com/api/cr/deleterepo.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRepoWithCallback(request *DeleteRepoRequest, callback func(response *DeleteRepoResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteRepoResponse
var err error
defer close(result)
response, err = client.DeleteRepo(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteRepoRequest is the request struct for api DeleteRepo
type DeleteRepoRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
}
// DeleteRepoResponse is the response struct for api DeleteRepo
type DeleteRepoResponse struct {
*responses.BaseResponse
}
// CreateDeleteRepoRequest creates a request to invoke DeleteRepo API
func CreateDeleteRepoRequest() (request *DeleteRepoRequest) {
request = &DeleteRepoRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "DeleteRepo", "/repos/[RepoNamespace]/[RepoName]", "cr", "openAPI")
request.Method = requests.DELETE
return
}
// CreateDeleteRepoResponse creates a response to parse from DeleteRepo response
func CreateDeleteRepoResponse() (response *DeleteRepoResponse) {
response = &DeleteRepoResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// DeleteRepoAuthorization invokes the cr.DeleteRepoAuthorization API synchronously
// api document: https://help.aliyun.com/api/cr/deleterepoauthorization.html
func (client *Client) DeleteRepoAuthorization(request *DeleteRepoAuthorizationRequest) (response *DeleteRepoAuthorizationResponse, err error) {
response = CreateDeleteRepoAuthorizationResponse()
err = client.DoAction(request, response)
return
}
// DeleteRepoAuthorizationWithChan invokes the cr.DeleteRepoAuthorization API asynchronously
// api document: https://help.aliyun.com/api/cr/deleterepoauthorization.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRepoAuthorizationWithChan(request *DeleteRepoAuthorizationRequest) (<-chan *DeleteRepoAuthorizationResponse, <-chan error) {
responseChan := make(chan *DeleteRepoAuthorizationResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteRepoAuthorization(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteRepoAuthorizationWithCallback invokes the cr.DeleteRepoAuthorization API asynchronously
// api document: https://help.aliyun.com/api/cr/deleterepoauthorization.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRepoAuthorizationWithCallback(request *DeleteRepoAuthorizationRequest, callback func(response *DeleteRepoAuthorizationResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteRepoAuthorizationResponse
var err error
defer close(result)
response, err = client.DeleteRepoAuthorization(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteRepoAuthorizationRequest is the request struct for api DeleteRepoAuthorization
type DeleteRepoAuthorizationRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
AuthorizeId requests.Integer `position:"Path" name:"AuthorizeId"`
}
// DeleteRepoAuthorizationResponse is the response struct for api DeleteRepoAuthorization
type DeleteRepoAuthorizationResponse struct {
*responses.BaseResponse
}
// CreateDeleteRepoAuthorizationRequest creates a request to invoke DeleteRepoAuthorization API
func CreateDeleteRepoAuthorizationRequest() (request *DeleteRepoAuthorizationRequest) {
request = &DeleteRepoAuthorizationRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "DeleteRepoAuthorization", "/repos/[RepoNamespace]/[RepoName]/authorizations/[AuthorizeId]", "cr", "openAPI")
request.Method = requests.DELETE
return
}
// CreateDeleteRepoAuthorizationResponse creates a response to parse from DeleteRepoAuthorization response
func CreateDeleteRepoAuthorizationResponse() (response *DeleteRepoAuthorizationResponse) {
response = &DeleteRepoAuthorizationResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// DeleteRepoBuildRule invokes the cr.DeleteRepoBuildRule API synchronously
// api document: https://help.aliyun.com/api/cr/deleterepobuildrule.html
func (client *Client) DeleteRepoBuildRule(request *DeleteRepoBuildRuleRequest) (response *DeleteRepoBuildRuleResponse, err error) {
response = CreateDeleteRepoBuildRuleResponse()
err = client.DoAction(request, response)
return
}
// DeleteRepoBuildRuleWithChan invokes the cr.DeleteRepoBuildRule API asynchronously
// api document: https://help.aliyun.com/api/cr/deleterepobuildrule.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRepoBuildRuleWithChan(request *DeleteRepoBuildRuleRequest) (<-chan *DeleteRepoBuildRuleResponse, <-chan error) {
responseChan := make(chan *DeleteRepoBuildRuleResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteRepoBuildRule(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteRepoBuildRuleWithCallback invokes the cr.DeleteRepoBuildRule API asynchronously
// api document: https://help.aliyun.com/api/cr/deleterepobuildrule.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRepoBuildRuleWithCallback(request *DeleteRepoBuildRuleRequest, callback func(response *DeleteRepoBuildRuleResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteRepoBuildRuleResponse
var err error
defer close(result)
response, err = client.DeleteRepoBuildRule(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteRepoBuildRuleRequest is the request struct for api DeleteRepoBuildRule
type DeleteRepoBuildRuleRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
BuildRuleId requests.Integer `position:"Path" name:"BuildRuleId"`
}
// DeleteRepoBuildRuleResponse is the response struct for api DeleteRepoBuildRule
type DeleteRepoBuildRuleResponse struct {
*responses.BaseResponse
}
// CreateDeleteRepoBuildRuleRequest creates a request to invoke DeleteRepoBuildRule API
func CreateDeleteRepoBuildRuleRequest() (request *DeleteRepoBuildRuleRequest) {
request = &DeleteRepoBuildRuleRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "DeleteRepoBuildRule", "/repos/[RepoNamespace]/[RepoName]/rules/[BuildRuleId]", "cr", "openAPI")
request.Method = requests.DELETE
return
}
// CreateDeleteRepoBuildRuleResponse creates a response to parse from DeleteRepoBuildRule response
func CreateDeleteRepoBuildRuleResponse() (response *DeleteRepoBuildRuleResponse) {
response = &DeleteRepoBuildRuleResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// DeleteRepoWebhook invokes the cr.DeleteRepoWebhook API synchronously
// api document: https://help.aliyun.com/api/cr/deleterepowebhook.html
func (client *Client) DeleteRepoWebhook(request *DeleteRepoWebhookRequest) (response *DeleteRepoWebhookResponse, err error) {
response = CreateDeleteRepoWebhookResponse()
err = client.DoAction(request, response)
return
}
// DeleteRepoWebhookWithChan invokes the cr.DeleteRepoWebhook API asynchronously
// api document: https://help.aliyun.com/api/cr/deleterepowebhook.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRepoWebhookWithChan(request *DeleteRepoWebhookRequest) (<-chan *DeleteRepoWebhookResponse, <-chan error) {
responseChan := make(chan *DeleteRepoWebhookResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteRepoWebhook(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteRepoWebhookWithCallback invokes the cr.DeleteRepoWebhook API asynchronously
// api document: https://help.aliyun.com/api/cr/deleterepowebhook.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteRepoWebhookWithCallback(request *DeleteRepoWebhookRequest, callback func(response *DeleteRepoWebhookResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteRepoWebhookResponse
var err error
defer close(result)
response, err = client.DeleteRepoWebhook(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteRepoWebhookRequest is the request struct for api DeleteRepoWebhook
type DeleteRepoWebhookRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
WebhookId requests.Integer `position:"Path" name:"WebhookId"`
RepoName string `position:"Path" name:"RepoName"`
}
// DeleteRepoWebhookResponse is the response struct for api DeleteRepoWebhook
type DeleteRepoWebhookResponse struct {
*responses.BaseResponse
}
// CreateDeleteRepoWebhookRequest creates a request to invoke DeleteRepoWebhook API
func CreateDeleteRepoWebhookRequest() (request *DeleteRepoWebhookRequest) {
request = &DeleteRepoWebhookRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "DeleteRepoWebhook", "/repos/[RepoNamespace]/[RepoName]/webhooks/[WebhookId]", "cr", "openAPI")
request.Method = requests.DELETE
return
}
// CreateDeleteRepoWebhookResponse creates a response to parse from DeleteRepoWebhook response
func CreateDeleteRepoWebhookResponse() (response *DeleteRepoWebhookResponse) {
response = &DeleteRepoWebhookResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package cr
//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"
)
// DeleteUserSourceAccount invokes the cr.DeleteUserSourceAccount API synchronously
// api document: https://help.aliyun.com/api/cr/deleteusersourceaccount.html
func (client *Client) DeleteUserSourceAccount(request *DeleteUserSourceAccountRequest) (response *DeleteUserSourceAccountResponse, err error) {
response = CreateDeleteUserSourceAccountResponse()
err = client.DoAction(request, response)
return
}
// DeleteUserSourceAccountWithChan invokes the cr.DeleteUserSourceAccount API asynchronously
// api document: https://help.aliyun.com/api/cr/deleteusersourceaccount.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteUserSourceAccountWithChan(request *DeleteUserSourceAccountRequest) (<-chan *DeleteUserSourceAccountResponse, <-chan error) {
responseChan := make(chan *DeleteUserSourceAccountResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.DeleteUserSourceAccount(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// DeleteUserSourceAccountWithCallback invokes the cr.DeleteUserSourceAccount API asynchronously
// api document: https://help.aliyun.com/api/cr/deleteusersourceaccount.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DeleteUserSourceAccountWithCallback(request *DeleteUserSourceAccountRequest, callback func(response *DeleteUserSourceAccountResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *DeleteUserSourceAccountResponse
var err error
defer close(result)
response, err = client.DeleteUserSourceAccount(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// DeleteUserSourceAccountRequest is the request struct for api DeleteUserSourceAccount
type DeleteUserSourceAccountRequest struct {
*requests.RoaRequest
SourceAccountId requests.Integer `position:"Path" name:"SourceAccountId"`
}
// DeleteUserSourceAccountResponse is the response struct for api DeleteUserSourceAccount
type DeleteUserSourceAccountResponse struct {
*responses.BaseResponse
}
// CreateDeleteUserSourceAccountRequest creates a request to invoke DeleteUserSourceAccount API
func CreateDeleteUserSourceAccountRequest() (request *DeleteUserSourceAccountRequest) {
request = &DeleteUserSourceAccountRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "DeleteUserSourceAccount", "/users/sourceAccount/[SourceAccountId]", "cr", "openAPI")
request.Method = requests.DELETE
return
}
// CreateDeleteUserSourceAccountResponse creates a response to parse from DeleteUserSourceAccount response
func CreateDeleteUserSourceAccountResponse() (response *DeleteUserSourceAccountResponse) {
response = &DeleteUserSourceAccountResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,102 @@
package cr
//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"
)
// GetAuthorizationToken invokes the cr.GetAuthorizationToken API synchronously
// api document: https://help.aliyun.com/api/cr/getauthorizationtoken.html
func (client *Client) GetAuthorizationToken(request *GetAuthorizationTokenRequest) (response *GetAuthorizationTokenResponse, err error) {
response = CreateGetAuthorizationTokenResponse()
err = client.DoAction(request, response)
return
}
// GetAuthorizationTokenWithChan invokes the cr.GetAuthorizationToken API asynchronously
// api document: https://help.aliyun.com/api/cr/getauthorizationtoken.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetAuthorizationTokenWithChan(request *GetAuthorizationTokenRequest) (<-chan *GetAuthorizationTokenResponse, <-chan error) {
responseChan := make(chan *GetAuthorizationTokenResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetAuthorizationToken(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetAuthorizationTokenWithCallback invokes the cr.GetAuthorizationToken API asynchronously
// api document: https://help.aliyun.com/api/cr/getauthorizationtoken.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetAuthorizationTokenWithCallback(request *GetAuthorizationTokenRequest, callback func(response *GetAuthorizationTokenResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetAuthorizationTokenResponse
var err error
defer close(result)
response, err = client.GetAuthorizationToken(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetAuthorizationTokenRequest is the request struct for api GetAuthorizationToken
type GetAuthorizationTokenRequest struct {
*requests.RoaRequest
}
// GetAuthorizationTokenResponse is the response struct for api GetAuthorizationToken
type GetAuthorizationTokenResponse struct {
*responses.BaseResponse
}
// CreateGetAuthorizationTokenRequest creates a request to invoke GetAuthorizationToken API
func CreateGetAuthorizationTokenRequest() (request *GetAuthorizationTokenRequest) {
request = &GetAuthorizationTokenRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetAuthorizationToken", "/tokens", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetAuthorizationTokenResponse creates a response to parse from GetAuthorizationToken response
func CreateGetAuthorizationTokenResponse() (response *GetAuthorizationTokenResponse) {
response = &GetAuthorizationTokenResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// GetCollection invokes the cr.GetCollection API synchronously
// api document: https://help.aliyun.com/api/cr/getcollection.html
func (client *Client) GetCollection(request *GetCollectionRequest) (response *GetCollectionResponse, err error) {
response = CreateGetCollectionResponse()
err = client.DoAction(request, response)
return
}
// GetCollectionWithChan invokes the cr.GetCollection API asynchronously
// api document: https://help.aliyun.com/api/cr/getcollection.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetCollectionWithChan(request *GetCollectionRequest) (<-chan *GetCollectionResponse, <-chan error) {
responseChan := make(chan *GetCollectionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetCollection(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetCollectionWithCallback invokes the cr.GetCollection API asynchronously
// api document: https://help.aliyun.com/api/cr/getcollection.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetCollectionWithCallback(request *GetCollectionRequest, callback func(response *GetCollectionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetCollectionResponse
var err error
defer close(result)
response, err = client.GetCollection(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetCollectionRequest is the request struct for api GetCollection
type GetCollectionRequest struct {
*requests.RoaRequest
PageSize requests.Integer `position:"Query" name:"PageSize"`
Page requests.Integer `position:"Query" name:"Page"`
}
// GetCollectionResponse is the response struct for api GetCollection
type GetCollectionResponse struct {
*responses.BaseResponse
}
// CreateGetCollectionRequest creates a request to invoke GetCollection API
func CreateGetCollectionRequest() (request *GetCollectionRequest) {
request = &GetCollectionRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetCollection", "/collections", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetCollectionResponse creates a response to parse from GetCollection response
func CreateGetCollectionResponse() (response *GetCollectionResponse) {
response = &GetCollectionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// GetImageLayer invokes the cr.GetImageLayer API synchronously
// api document: https://help.aliyun.com/api/cr/getimagelayer.html
func (client *Client) GetImageLayer(request *GetImageLayerRequest) (response *GetImageLayerResponse, err error) {
response = CreateGetImageLayerResponse()
err = client.DoAction(request, response)
return
}
// GetImageLayerWithChan invokes the cr.GetImageLayer API asynchronously
// api document: https://help.aliyun.com/api/cr/getimagelayer.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetImageLayerWithChan(request *GetImageLayerRequest) (<-chan *GetImageLayerResponse, <-chan error) {
responseChan := make(chan *GetImageLayerResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetImageLayer(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetImageLayerWithCallback invokes the cr.GetImageLayer API asynchronously
// api document: https://help.aliyun.com/api/cr/getimagelayer.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetImageLayerWithCallback(request *GetImageLayerRequest, callback func(response *GetImageLayerResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetImageLayerResponse
var err error
defer close(result)
response, err = client.GetImageLayer(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetImageLayerRequest is the request struct for api GetImageLayer
type GetImageLayerRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
Tag string `position:"Path" name:"Tag"`
}
// GetImageLayerResponse is the response struct for api GetImageLayer
type GetImageLayerResponse struct {
*responses.BaseResponse
}
// CreateGetImageLayerRequest creates a request to invoke GetImageLayer API
func CreateGetImageLayerRequest() (request *GetImageLayerRequest) {
request = &GetImageLayerRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetImageLayer", "/repos/[RepoNamespace]/[RepoName]/tags/[Tag]/layers", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetImageLayerResponse creates a response to parse from GetImageLayer response
func CreateGetImageLayerResponse() (response *GetImageLayerResponse) {
response = &GetImageLayerResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,106 @@
package cr
//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"
)
// GetImageManifest invokes the cr.GetImageManifest API synchronously
// api document: https://help.aliyun.com/api/cr/getimagemanifest.html
func (client *Client) GetImageManifest(request *GetImageManifestRequest) (response *GetImageManifestResponse, err error) {
response = CreateGetImageManifestResponse()
err = client.DoAction(request, response)
return
}
// GetImageManifestWithChan invokes the cr.GetImageManifest API asynchronously
// api document: https://help.aliyun.com/api/cr/getimagemanifest.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetImageManifestWithChan(request *GetImageManifestRequest) (<-chan *GetImageManifestResponse, <-chan error) {
responseChan := make(chan *GetImageManifestResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetImageManifest(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetImageManifestWithCallback invokes the cr.GetImageManifest API asynchronously
// api document: https://help.aliyun.com/api/cr/getimagemanifest.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetImageManifestWithCallback(request *GetImageManifestRequest, callback func(response *GetImageManifestResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetImageManifestResponse
var err error
defer close(result)
response, err = client.GetImageManifest(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetImageManifestRequest is the request struct for api GetImageManifest
type GetImageManifestRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
Tag string `position:"Path" name:"Tag"`
SchemaVersion requests.Integer `position:"Query" name:"SchemaVersion"`
}
// GetImageManifestResponse is the response struct for api GetImageManifest
type GetImageManifestResponse struct {
*responses.BaseResponse
}
// CreateGetImageManifestRequest creates a request to invoke GetImageManifest API
func CreateGetImageManifestRequest() (request *GetImageManifestRequest) {
request = &GetImageManifestRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetImageManifest", "/repos/[RepoNamespace]/[RepoName]/tags/[Tag]/manifest", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetImageManifestResponse creates a response to parse from GetImageManifest response
func CreateGetImageManifestResponse() (response *GetImageManifestResponse) {
response = &GetImageManifestResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// GetImageScan invokes the cr.GetImageScan API synchronously
// api document: https://help.aliyun.com/api/cr/getimagescan.html
func (client *Client) GetImageScan(request *GetImageScanRequest) (response *GetImageScanResponse, err error) {
response = CreateGetImageScanResponse()
err = client.DoAction(request, response)
return
}
// GetImageScanWithChan invokes the cr.GetImageScan API asynchronously
// api document: https://help.aliyun.com/api/cr/getimagescan.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetImageScanWithChan(request *GetImageScanRequest) (<-chan *GetImageScanResponse, <-chan error) {
responseChan := make(chan *GetImageScanResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetImageScan(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetImageScanWithCallback invokes the cr.GetImageScan API asynchronously
// api document: https://help.aliyun.com/api/cr/getimagescan.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetImageScanWithCallback(request *GetImageScanRequest, callback func(response *GetImageScanResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetImageScanResponse
var err error
defer close(result)
response, err = client.GetImageScan(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetImageScanRequest is the request struct for api GetImageScan
type GetImageScanRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
Tag string `position:"Path" name:"Tag"`
}
// GetImageScanResponse is the response struct for api GetImageScan
type GetImageScanResponse struct {
*responses.BaseResponse
}
// CreateGetImageScanRequest creates a request to invoke GetImageScan API
func CreateGetImageScanRequest() (request *GetImageScanRequest) {
request = &GetImageScanRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetImageScan", "/repos/[RepoNamespace]/[RepoName]/tags/[Tag]/scan", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetImageScanResponse creates a response to parse from GetImageScan response
func CreateGetImageScanResponse() (response *GetImageScanResponse) {
response = &GetImageScanResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,102 @@
package cr
//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"
)
// GetMirrorList invokes the cr.GetMirrorList API synchronously
// api document: https://help.aliyun.com/api/cr/getmirrorlist.html
func (client *Client) GetMirrorList(request *GetMirrorListRequest) (response *GetMirrorListResponse, err error) {
response = CreateGetMirrorListResponse()
err = client.DoAction(request, response)
return
}
// GetMirrorListWithChan invokes the cr.GetMirrorList API asynchronously
// api document: https://help.aliyun.com/api/cr/getmirrorlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetMirrorListWithChan(request *GetMirrorListRequest) (<-chan *GetMirrorListResponse, <-chan error) {
responseChan := make(chan *GetMirrorListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetMirrorList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetMirrorListWithCallback invokes the cr.GetMirrorList API asynchronously
// api document: https://help.aliyun.com/api/cr/getmirrorlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetMirrorListWithCallback(request *GetMirrorListRequest, callback func(response *GetMirrorListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetMirrorListResponse
var err error
defer close(result)
response, err = client.GetMirrorList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetMirrorListRequest is the request struct for api GetMirrorList
type GetMirrorListRequest struct {
*requests.RoaRequest
}
// GetMirrorListResponse is the response struct for api GetMirrorList
type GetMirrorListResponse struct {
*responses.BaseResponse
}
// CreateGetMirrorListRequest creates a request to invoke GetMirrorList API
func CreateGetMirrorListRequest() (request *GetMirrorListRequest) {
request = &GetMirrorListRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetMirrorList", "/mirrors", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetMirrorListResponse creates a response to parse from GetMirrorList response
func CreateGetMirrorListResponse() (response *GetMirrorListResponse) {
response = &GetMirrorListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package cr
//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"
)
// GetNamespace invokes the cr.GetNamespace API synchronously
// api document: https://help.aliyun.com/api/cr/getnamespace.html
func (client *Client) GetNamespace(request *GetNamespaceRequest) (response *GetNamespaceResponse, err error) {
response = CreateGetNamespaceResponse()
err = client.DoAction(request, response)
return
}
// GetNamespaceWithChan invokes the cr.GetNamespace API asynchronously
// api document: https://help.aliyun.com/api/cr/getnamespace.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetNamespaceWithChan(request *GetNamespaceRequest) (<-chan *GetNamespaceResponse, <-chan error) {
responseChan := make(chan *GetNamespaceResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetNamespace(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetNamespaceWithCallback invokes the cr.GetNamespace API asynchronously
// api document: https://help.aliyun.com/api/cr/getnamespace.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetNamespaceWithCallback(request *GetNamespaceRequest, callback func(response *GetNamespaceResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetNamespaceResponse
var err error
defer close(result)
response, err = client.GetNamespace(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetNamespaceRequest is the request struct for api GetNamespace
type GetNamespaceRequest struct {
*requests.RoaRequest
Namespace string `position:"Path" name:"Namespace"`
}
// GetNamespaceResponse is the response struct for api GetNamespace
type GetNamespaceResponse struct {
*responses.BaseResponse
}
// CreateGetNamespaceRequest creates a request to invoke GetNamespace API
func CreateGetNamespaceRequest() (request *GetNamespaceRequest) {
request = &GetNamespaceRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetNamespace", "/namespace/[Namespace]", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetNamespaceResponse creates a response to parse from GetNamespace response
func CreateGetNamespaceResponse() (response *GetNamespaceResponse) {
response = &GetNamespaceResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// GetNamespaceAuthorizationList invokes the cr.GetNamespaceAuthorizationList API synchronously
// api document: https://help.aliyun.com/api/cr/getnamespaceauthorizationlist.html
func (client *Client) GetNamespaceAuthorizationList(request *GetNamespaceAuthorizationListRequest) (response *GetNamespaceAuthorizationListResponse, err error) {
response = CreateGetNamespaceAuthorizationListResponse()
err = client.DoAction(request, response)
return
}
// GetNamespaceAuthorizationListWithChan invokes the cr.GetNamespaceAuthorizationList API asynchronously
// api document: https://help.aliyun.com/api/cr/getnamespaceauthorizationlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetNamespaceAuthorizationListWithChan(request *GetNamespaceAuthorizationListRequest) (<-chan *GetNamespaceAuthorizationListResponse, <-chan error) {
responseChan := make(chan *GetNamespaceAuthorizationListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetNamespaceAuthorizationList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetNamespaceAuthorizationListWithCallback invokes the cr.GetNamespaceAuthorizationList API asynchronously
// api document: https://help.aliyun.com/api/cr/getnamespaceauthorizationlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetNamespaceAuthorizationListWithCallback(request *GetNamespaceAuthorizationListRequest, callback func(response *GetNamespaceAuthorizationListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetNamespaceAuthorizationListResponse
var err error
defer close(result)
response, err = client.GetNamespaceAuthorizationList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetNamespaceAuthorizationListRequest is the request struct for api GetNamespaceAuthorizationList
type GetNamespaceAuthorizationListRequest struct {
*requests.RoaRequest
Namespace string `position:"Path" name:"Namespace"`
Authorize string `position:"Query" name:"Authorize"`
}
// GetNamespaceAuthorizationListResponse is the response struct for api GetNamespaceAuthorizationList
type GetNamespaceAuthorizationListResponse struct {
*responses.BaseResponse
}
// CreateGetNamespaceAuthorizationListRequest creates a request to invoke GetNamespaceAuthorizationList API
func CreateGetNamespaceAuthorizationListRequest() (request *GetNamespaceAuthorizationListRequest) {
request = &GetNamespaceAuthorizationListRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetNamespaceAuthorizationList", "/namespace/[Namespace]/authorizations", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetNamespaceAuthorizationListResponse creates a response to parse from GetNamespaceAuthorizationList response
func CreateGetNamespaceAuthorizationListResponse() (response *GetNamespaceAuthorizationListResponse) {
response = &GetNamespaceAuthorizationListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// GetNamespaceList invokes the cr.GetNamespaceList API synchronously
// api document: https://help.aliyun.com/api/cr/getnamespacelist.html
func (client *Client) GetNamespaceList(request *GetNamespaceListRequest) (response *GetNamespaceListResponse, err error) {
response = CreateGetNamespaceListResponse()
err = client.DoAction(request, response)
return
}
// GetNamespaceListWithChan invokes the cr.GetNamespaceList API asynchronously
// api document: https://help.aliyun.com/api/cr/getnamespacelist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetNamespaceListWithChan(request *GetNamespaceListRequest) (<-chan *GetNamespaceListResponse, <-chan error) {
responseChan := make(chan *GetNamespaceListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetNamespaceList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetNamespaceListWithCallback invokes the cr.GetNamespaceList API asynchronously
// api document: https://help.aliyun.com/api/cr/getnamespacelist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetNamespaceListWithCallback(request *GetNamespaceListRequest, callback func(response *GetNamespaceListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetNamespaceListResponse
var err error
defer close(result)
response, err = client.GetNamespaceList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetNamespaceListRequest is the request struct for api GetNamespaceList
type GetNamespaceListRequest struct {
*requests.RoaRequest
Authorize string `position:"Query" name:"Authorize"`
Status string `position:"Query" name:"Status"`
}
// GetNamespaceListResponse is the response struct for api GetNamespaceList
type GetNamespaceListResponse struct {
*responses.BaseResponse
}
// CreateGetNamespaceListRequest creates a request to invoke GetNamespaceList API
func CreateGetNamespaceListRequest() (request *GetNamespaceListRequest) {
request = &GetNamespaceListRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetNamespaceList", "/namespace", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetNamespaceListResponse creates a response to parse from GetNamespaceList response
func CreateGetNamespaceListResponse() (response *GetNamespaceListResponse) {
response = &GetNamespaceListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package cr
//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"
)
// GetRegion invokes the cr.GetRegion API synchronously
// api document: https://help.aliyun.com/api/cr/getregion.html
func (client *Client) GetRegion(request *GetRegionRequest) (response *GetRegionResponse, err error) {
response = CreateGetRegionResponse()
err = client.DoAction(request, response)
return
}
// GetRegionWithChan invokes the cr.GetRegion API asynchronously
// api document: https://help.aliyun.com/api/cr/getregion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRegionWithChan(request *GetRegionRequest) (<-chan *GetRegionResponse, <-chan error) {
responseChan := make(chan *GetRegionResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRegion(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRegionWithCallback invokes the cr.GetRegion API asynchronously
// api document: https://help.aliyun.com/api/cr/getregion.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRegionWithCallback(request *GetRegionRequest, callback func(response *GetRegionResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRegionResponse
var err error
defer close(result)
response, err = client.GetRegion(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRegionRequest is the request struct for api GetRegion
type GetRegionRequest struct {
*requests.RoaRequest
Domain string `position:"Query" name:"Domain"`
}
// GetRegionResponse is the response struct for api GetRegion
type GetRegionResponse struct {
*responses.BaseResponse
}
// CreateGetRegionRequest creates a request to invoke GetRegion API
func CreateGetRegionRequest() (request *GetRegionRequest) {
request = &GetRegionRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRegion", "/regions", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRegionResponse creates a response to parse from GetRegion response
func CreateGetRegionResponse() (response *GetRegionResponse) {
response = &GetRegionResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,102 @@
package cr
//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"
)
// GetRegionList invokes the cr.GetRegionList API synchronously
// api document: https://help.aliyun.com/api/cr/getregionlist.html
func (client *Client) GetRegionList(request *GetRegionListRequest) (response *GetRegionListResponse, err error) {
response = CreateGetRegionListResponse()
err = client.DoAction(request, response)
return
}
// GetRegionListWithChan invokes the cr.GetRegionList API asynchronously
// api document: https://help.aliyun.com/api/cr/getregionlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRegionListWithChan(request *GetRegionListRequest) (<-chan *GetRegionListResponse, <-chan error) {
responseChan := make(chan *GetRegionListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRegionList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRegionListWithCallback invokes the cr.GetRegionList API asynchronously
// api document: https://help.aliyun.com/api/cr/getregionlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRegionListWithCallback(request *GetRegionListRequest, callback func(response *GetRegionListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRegionListResponse
var err error
defer close(result)
response, err = client.GetRegionList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRegionListRequest is the request struct for api GetRegionList
type GetRegionListRequest struct {
*requests.RoaRequest
}
// GetRegionListResponse is the response struct for api GetRegionList
type GetRegionListResponse struct {
*responses.BaseResponse
}
// CreateGetRegionListRequest creates a request to invoke GetRegionList API
func CreateGetRegionListRequest() (request *GetRegionListRequest) {
request = &GetRegionListRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRegionList", "/regions", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRegionListResponse creates a response to parse from GetRegionList response
func CreateGetRegionListResponse() (response *GetRegionListResponse) {
response = &GetRegionListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// GetRepo invokes the cr.GetRepo API synchronously
// api document: https://help.aliyun.com/api/cr/getrepo.html
func (client *Client) GetRepo(request *GetRepoRequest) (response *GetRepoResponse, err error) {
response = CreateGetRepoResponse()
err = client.DoAction(request, response)
return
}
// GetRepoWithChan invokes the cr.GetRepo API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepo.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoWithChan(request *GetRepoRequest) (<-chan *GetRepoResponse, <-chan error) {
responseChan := make(chan *GetRepoResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRepo(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRepoWithCallback invokes the cr.GetRepo API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepo.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoWithCallback(request *GetRepoRequest, callback func(response *GetRepoResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRepoResponse
var err error
defer close(result)
response, err = client.GetRepo(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRepoRequest is the request struct for api GetRepo
type GetRepoRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
}
// GetRepoResponse is the response struct for api GetRepo
type GetRepoResponse struct {
*responses.BaseResponse
}
// CreateGetRepoRequest creates a request to invoke GetRepo API
func CreateGetRepoRequest() (request *GetRepoRequest) {
request = &GetRepoRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRepo", "/repos/[RepoNamespace]/[RepoName]", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRepoResponse creates a response to parse from GetRepo response
func CreateGetRepoResponse() (response *GetRepoResponse) {
response = &GetRepoResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// GetRepoAuthorizationList invokes the cr.GetRepoAuthorizationList API synchronously
// api document: https://help.aliyun.com/api/cr/getrepoauthorizationlist.html
func (client *Client) GetRepoAuthorizationList(request *GetRepoAuthorizationListRequest) (response *GetRepoAuthorizationListResponse, err error) {
response = CreateGetRepoAuthorizationListResponse()
err = client.DoAction(request, response)
return
}
// GetRepoAuthorizationListWithChan invokes the cr.GetRepoAuthorizationList API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepoauthorizationlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoAuthorizationListWithChan(request *GetRepoAuthorizationListRequest) (<-chan *GetRepoAuthorizationListResponse, <-chan error) {
responseChan := make(chan *GetRepoAuthorizationListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRepoAuthorizationList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRepoAuthorizationListWithCallback invokes the cr.GetRepoAuthorizationList API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepoauthorizationlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoAuthorizationListWithCallback(request *GetRepoAuthorizationListRequest, callback func(response *GetRepoAuthorizationListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRepoAuthorizationListResponse
var err error
defer close(result)
response, err = client.GetRepoAuthorizationList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRepoAuthorizationListRequest is the request struct for api GetRepoAuthorizationList
type GetRepoAuthorizationListRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
Authorize string `position:"Query" name:"Authorize"`
}
// GetRepoAuthorizationListResponse is the response struct for api GetRepoAuthorizationList
type GetRepoAuthorizationListResponse struct {
*responses.BaseResponse
}
// CreateGetRepoAuthorizationListRequest creates a request to invoke GetRepoAuthorizationList API
func CreateGetRepoAuthorizationListRequest() (request *GetRepoAuthorizationListRequest) {
request = &GetRepoAuthorizationListRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRepoAuthorizationList", "/repos/[RepoNamespace]/[RepoName]/authorizations", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRepoAuthorizationListResponse creates a response to parse from GetRepoAuthorizationList response
func CreateGetRepoAuthorizationListResponse() (response *GetRepoAuthorizationListResponse) {
response = &GetRepoAuthorizationListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,103 @@
package cr
//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"
)
// GetRepoBatch invokes the cr.GetRepoBatch API synchronously
// api document: https://help.aliyun.com/api/cr/getrepobatch.html
func (client *Client) GetRepoBatch(request *GetRepoBatchRequest) (response *GetRepoBatchResponse, err error) {
response = CreateGetRepoBatchResponse()
err = client.DoAction(request, response)
return
}
// GetRepoBatchWithChan invokes the cr.GetRepoBatch API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobatch.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBatchWithChan(request *GetRepoBatchRequest) (<-chan *GetRepoBatchResponse, <-chan error) {
responseChan := make(chan *GetRepoBatchResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRepoBatch(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRepoBatchWithCallback invokes the cr.GetRepoBatch API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobatch.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBatchWithCallback(request *GetRepoBatchRequest, callback func(response *GetRepoBatchResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRepoBatchResponse
var err error
defer close(result)
response, err = client.GetRepoBatch(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRepoBatchRequest is the request struct for api GetRepoBatch
type GetRepoBatchRequest struct {
*requests.RoaRequest
RepoIds string `position:"Query" name:"RepoIds"`
}
// GetRepoBatchResponse is the response struct for api GetRepoBatch
type GetRepoBatchResponse struct {
*responses.BaseResponse
}
// CreateGetRepoBatchRequest creates a request to invoke GetRepoBatch API
func CreateGetRepoBatchRequest() (request *GetRepoBatchRequest) {
request = &GetRepoBatchRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRepoBatch", "/batchsearch", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRepoBatchResponse creates a response to parse from GetRepoBatch response
func CreateGetRepoBatchResponse() (response *GetRepoBatchResponse) {
response = &GetRepoBatchResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,106 @@
package cr
//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"
)
// GetRepoBuildList invokes the cr.GetRepoBuildList API synchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildlist.html
func (client *Client) GetRepoBuildList(request *GetRepoBuildListRequest) (response *GetRepoBuildListResponse, err error) {
response = CreateGetRepoBuildListResponse()
err = client.DoAction(request, response)
return
}
// GetRepoBuildListWithChan invokes the cr.GetRepoBuildList API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildListWithChan(request *GetRepoBuildListRequest) (<-chan *GetRepoBuildListResponse, <-chan error) {
responseChan := make(chan *GetRepoBuildListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRepoBuildList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRepoBuildListWithCallback invokes the cr.GetRepoBuildList API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildlist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildListWithCallback(request *GetRepoBuildListRequest, callback func(response *GetRepoBuildListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRepoBuildListResponse
var err error
defer close(result)
response, err = client.GetRepoBuildList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRepoBuildListRequest is the request struct for api GetRepoBuildList
type GetRepoBuildListRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
PageSize requests.Integer `position:"Query" name:"PageSize"`
Page requests.Integer `position:"Query" name:"Page"`
}
// GetRepoBuildListResponse is the response struct for api GetRepoBuildList
type GetRepoBuildListResponse struct {
*responses.BaseResponse
}
// CreateGetRepoBuildListRequest creates a request to invoke GetRepoBuildList API
func CreateGetRepoBuildListRequest() (request *GetRepoBuildListRequest) {
request = &GetRepoBuildListRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRepoBuildList", "/repos/[RepoNamespace]/[RepoName]/build", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRepoBuildListResponse creates a response to parse from GetRepoBuildList response
func CreateGetRepoBuildListResponse() (response *GetRepoBuildListResponse) {
response = &GetRepoBuildListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// GetRepoBuildLogs invokes the cr.GetRepoBuildLogs API synchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildlogs.html
func (client *Client) GetRepoBuildLogs(request *GetRepoBuildLogsRequest) (response *GetRepoBuildLogsResponse, err error) {
response = CreateGetRepoBuildLogsResponse()
err = client.DoAction(request, response)
return
}
// GetRepoBuildLogsWithChan invokes the cr.GetRepoBuildLogs API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildlogs.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildLogsWithChan(request *GetRepoBuildLogsRequest) (<-chan *GetRepoBuildLogsResponse, <-chan error) {
responseChan := make(chan *GetRepoBuildLogsResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRepoBuildLogs(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRepoBuildLogsWithCallback invokes the cr.GetRepoBuildLogs API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildlogs.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildLogsWithCallback(request *GetRepoBuildLogsRequest, callback func(response *GetRepoBuildLogsResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRepoBuildLogsResponse
var err error
defer close(result)
response, err = client.GetRepoBuildLogs(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRepoBuildLogsRequest is the request struct for api GetRepoBuildLogs
type GetRepoBuildLogsRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
BuildId string `position:"Path" name:"BuildId"`
}
// GetRepoBuildLogsResponse is the response struct for api GetRepoBuildLogs
type GetRepoBuildLogsResponse struct {
*responses.BaseResponse
}
// CreateGetRepoBuildLogsRequest creates a request to invoke GetRepoBuildLogs API
func CreateGetRepoBuildLogsRequest() (request *GetRepoBuildLogsRequest) {
request = &GetRepoBuildLogsRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRepoBuildLogs", "/repos/[RepoNamespace]/[RepoName]/build/[BuildId]/logs", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRepoBuildLogsResponse creates a response to parse from GetRepoBuildLogs response
func CreateGetRepoBuildLogsResponse() (response *GetRepoBuildLogsResponse) {
response = &GetRepoBuildLogsResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,104 @@
package cr
//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"
)
// GetRepoBuildRuleList invokes the cr.GetRepoBuildRuleList API synchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildrulelist.html
func (client *Client) GetRepoBuildRuleList(request *GetRepoBuildRuleListRequest) (response *GetRepoBuildRuleListResponse, err error) {
response = CreateGetRepoBuildRuleListResponse()
err = client.DoAction(request, response)
return
}
// GetRepoBuildRuleListWithChan invokes the cr.GetRepoBuildRuleList API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildrulelist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildRuleListWithChan(request *GetRepoBuildRuleListRequest) (<-chan *GetRepoBuildRuleListResponse, <-chan error) {
responseChan := make(chan *GetRepoBuildRuleListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRepoBuildRuleList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRepoBuildRuleListWithCallback invokes the cr.GetRepoBuildRuleList API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildrulelist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildRuleListWithCallback(request *GetRepoBuildRuleListRequest, callback func(response *GetRepoBuildRuleListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRepoBuildRuleListResponse
var err error
defer close(result)
response, err = client.GetRepoBuildRuleList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRepoBuildRuleListRequest is the request struct for api GetRepoBuildRuleList
type GetRepoBuildRuleListRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
}
// GetRepoBuildRuleListResponse is the response struct for api GetRepoBuildRuleList
type GetRepoBuildRuleListResponse struct {
*responses.BaseResponse
}
// CreateGetRepoBuildRuleListRequest creates a request to invoke GetRepoBuildRuleList API
func CreateGetRepoBuildRuleListRequest() (request *GetRepoBuildRuleListRequest) {
request = &GetRepoBuildRuleListRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRepoBuildRuleList", "/repos/[RepoNamespace]/[RepoName]/rules", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRepoBuildRuleListResponse creates a response to parse from GetRepoBuildRuleList response
func CreateGetRepoBuildRuleListResponse() (response *GetRepoBuildRuleListResponse) {
response = &GetRepoBuildRuleListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// GetRepoBuildStatus invokes the cr.GetRepoBuildStatus API synchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildstatus.html
func (client *Client) GetRepoBuildStatus(request *GetRepoBuildStatusRequest) (response *GetRepoBuildStatusResponse, err error) {
response = CreateGetRepoBuildStatusResponse()
err = client.DoAction(request, response)
return
}
// GetRepoBuildStatusWithChan invokes the cr.GetRepoBuildStatus API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildstatus.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildStatusWithChan(request *GetRepoBuildStatusRequest) (<-chan *GetRepoBuildStatusResponse, <-chan error) {
responseChan := make(chan *GetRepoBuildStatusResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRepoBuildStatus(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRepoBuildStatusWithCallback invokes the cr.GetRepoBuildStatus API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepobuildstatus.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoBuildStatusWithCallback(request *GetRepoBuildStatusRequest, callback func(response *GetRepoBuildStatusResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRepoBuildStatusResponse
var err error
defer close(result)
response, err = client.GetRepoBuildStatus(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRepoBuildStatusRequest is the request struct for api GetRepoBuildStatus
type GetRepoBuildStatusRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
RepoName string `position:"Path" name:"RepoName"`
BuildId string `position:"Path" name:"BuildId"`
}
// GetRepoBuildStatusResponse is the response struct for api GetRepoBuildStatus
type GetRepoBuildStatusResponse struct {
*responses.BaseResponse
}
// CreateGetRepoBuildStatusRequest creates a request to invoke GetRepoBuildStatus API
func CreateGetRepoBuildStatusRequest() (request *GetRepoBuildStatusRequest) {
request = &GetRepoBuildStatusRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRepoBuildStatus", "/repos/[RepoNamespace]/[RepoName]/build/[BuildId]/status", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRepoBuildStatusResponse creates a response to parse from GetRepoBuildStatus response
func CreateGetRepoBuildStatusResponse() (response *GetRepoBuildStatusResponse) {
response = &GetRepoBuildStatusResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,105 @@
package cr
//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"
)
// GetRepoList invokes the cr.GetRepoList API synchronously
// api document: https://help.aliyun.com/api/cr/getrepolist.html
func (client *Client) GetRepoList(request *GetRepoListRequest) (response *GetRepoListResponse, err error) {
response = CreateGetRepoListResponse()
err = client.DoAction(request, response)
return
}
// GetRepoListWithChan invokes the cr.GetRepoList API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepolist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoListWithChan(request *GetRepoListRequest) (<-chan *GetRepoListResponse, <-chan error) {
responseChan := make(chan *GetRepoListResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRepoList(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRepoListWithCallback invokes the cr.GetRepoList API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepolist.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoListWithCallback(request *GetRepoListRequest, callback func(response *GetRepoListResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRepoListResponse
var err error
defer close(result)
response, err = client.GetRepoList(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRepoListRequest is the request struct for api GetRepoList
type GetRepoListRequest struct {
*requests.RoaRequest
PageSize requests.Integer `position:"Query" name:"PageSize"`
Page requests.Integer `position:"Query" name:"Page"`
Status string `position:"Query" name:"Status"`
}
// GetRepoListResponse is the response struct for api GetRepoList
type GetRepoListResponse struct {
*responses.BaseResponse
}
// CreateGetRepoListRequest creates a request to invoke GetRepoList API
func CreateGetRepoListRequest() (request *GetRepoListRequest) {
request = &GetRepoListRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRepoList", "/repos", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRepoListResponse creates a response to parse from GetRepoList response
func CreateGetRepoListResponse() (response *GetRepoListResponse) {
response = &GetRepoListResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

View File

@ -0,0 +1,106 @@
package cr
//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"
)
// GetRepoListByNamespace invokes the cr.GetRepoListByNamespace API synchronously
// api document: https://help.aliyun.com/api/cr/getrepolistbynamespace.html
func (client *Client) GetRepoListByNamespace(request *GetRepoListByNamespaceRequest) (response *GetRepoListByNamespaceResponse, err error) {
response = CreateGetRepoListByNamespaceResponse()
err = client.DoAction(request, response)
return
}
// GetRepoListByNamespaceWithChan invokes the cr.GetRepoListByNamespace API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepolistbynamespace.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoListByNamespaceWithChan(request *GetRepoListByNamespaceRequest) (<-chan *GetRepoListByNamespaceResponse, <-chan error) {
responseChan := make(chan *GetRepoListByNamespaceResponse, 1)
errChan := make(chan error, 1)
err := client.AddAsyncTask(func() {
defer close(responseChan)
defer close(errChan)
response, err := client.GetRepoListByNamespace(request)
if err != nil {
errChan <- err
} else {
responseChan <- response
}
})
if err != nil {
errChan <- err
close(responseChan)
close(errChan)
}
return responseChan, errChan
}
// GetRepoListByNamespaceWithCallback invokes the cr.GetRepoListByNamespace API asynchronously
// api document: https://help.aliyun.com/api/cr/getrepolistbynamespace.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetRepoListByNamespaceWithCallback(request *GetRepoListByNamespaceRequest, callback func(response *GetRepoListByNamespaceResponse, err error)) <-chan int {
result := make(chan int, 1)
err := client.AddAsyncTask(func() {
var response *GetRepoListByNamespaceResponse
var err error
defer close(result)
response, err = client.GetRepoListByNamespace(request)
callback(response, err)
result <- 1
})
if err != nil {
defer close(result)
callback(nil, err)
result <- 0
}
return result
}
// GetRepoListByNamespaceRequest is the request struct for api GetRepoListByNamespace
type GetRepoListByNamespaceRequest struct {
*requests.RoaRequest
RepoNamespace string `position:"Path" name:"RepoNamespace"`
PageSize requests.Integer `position:"Query" name:"PageSize"`
Page requests.Integer `position:"Query" name:"Page"`
Status string `position:"Query" name:"Status"`
}
// GetRepoListByNamespaceResponse is the response struct for api GetRepoListByNamespace
type GetRepoListByNamespaceResponse struct {
*responses.BaseResponse
}
// CreateGetRepoListByNamespaceRequest creates a request to invoke GetRepoListByNamespace API
func CreateGetRepoListByNamespaceRequest() (request *GetRepoListByNamespaceRequest) {
request = &GetRepoListByNamespaceRequest{
RoaRequest: &requests.RoaRequest{},
}
request.InitWithApiInfo("cr", "2016-06-07", "GetRepoListByNamespace", "/repos/[RepoNamespace]", "cr", "openAPI")
request.Method = requests.GET
return
}
// CreateGetRepoListByNamespaceResponse creates a response to parse from GetRepoListByNamespace response
func CreateGetRepoListByNamespaceResponse() (response *GetRepoListByNamespaceResponse) {
response = &GetRepoListByNamespaceResponse{
BaseResponse: &responses.BaseResponse{},
}
return
}

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