vendor: update all dependencies to latest versions

This commit is contained in:
Nick Craig-Wood 2018-01-16 13:20:59 +00:00
parent 8e83fb6fb9
commit 7d3a17725d
4878 changed files with 1974229 additions and 201215 deletions

View file

@ -5,11 +5,10 @@ services:
language: go
go:
- 1.6
- 1.7
- 1.8
- 1.9
- master
- 1.9
- 1.8
- 1.7
cache:
directories:

View file

@ -1,26 +1,32 @@
# Change Log
All notable changes to QingStor SDK for Go will be documented in this file.
## [v2.2.9] - 2017-11-25
### Changed
- Refactor logger.
## [v2.2.8] - 2017-09-25
### Added
- Support setting custom SDK logger
- Support setting custom SDK logger.
## [v2.2.7] - 2017-09-01
### Added
- Support image process APIs
- Add advanced client for image process
- Support image process APIs.
- Add advanced client for image process.
### Changed
- Force the zone ID to be lowercase
- Force the zone ID to be lowercase.
### Fixed
- Add support for the X-QS-Date header
- Add support for the X-QS-Date header.
## [v2.2.6] - 2017-07-21
@ -52,19 +58,19 @@ All notable changes to QingStor SDK for Go will be documented in this file.
### Added
- Allow user to append additional info to User-Agent
- Allow user to append additional info to User-Agent.
## [v2.2.2] - 2017-03-08
### Fixed
- Resource is not mandatory in bucket policy statement
- Resource is not mandatory in bucket policy statement.
## [v2.2.1] - 2017-03-05
### Changed
- Add "Encrypted" field to "KeyType" struct
- Add "Encrypted" field to "KeyType" struct.
## [v2.2.0] - 2017-02-28
@ -121,6 +127,7 @@ All notable changes to QingStor SDK for Go will be documented in this file.
- QingStor SDK for the Go programming language.
[v2.2.9]: https://github.com/yunify/qingstor-sdk-go/compare/v2.2.8...v2.2.9
[v2.2.8]: https://github.com/yunify/qingstor-sdk-go/compare/v2.2.7...v2.2.8
[v2.2.7]: https://github.com/yunify/qingstor-sdk-go/compare/v2.2.6...v2.2.7
[v2.2.6]: https://github.com/yunify/qingstor-sdk-go/compare/v2.2.5...v2.2.6

View file

@ -32,22 +32,22 @@ check: vet lint
.PHONY: vet
vet:
@echo "go tool vet, skipping vendor packages"
@echo "Go tool vet, skipping vendor packages"
@go tool vet -all ${DIRS_TO_CHECK}
@echo "ok"
@echo "Done"
.PHONY: lint
lint:
@echo "golint, skipping vendor packages"
@echo "Golint, skipping vendor packages"
@lint=$$(for pkg in ${PKGS_TO_CHECK}; do golint $${pkg}; done); \
lint=$$(echo "$${lint}"); \
if [[ -n $${lint} ]]; then echo "$${lint}"; exit 1; fi
@echo "ok"
@echo "Done"
.PHONY: update
update:
git submodule update --remote
@echo "ok"
@echo "Done"
.PHONY: generate
generate:
@ -56,23 +56,23 @@ generate:
fi
snips -f="./specs/qingstor/2016-01-06/swagger/api_v2.0.json" -t="./template" -o="./service"
gofmt -w .
@echo "ok"
@echo "Done"
.PHONY: build
build:
@echo "build the SDK"
@echo "Build the SDK"
go build ${PKGS_TO_RELEASE}
@echo "ok"
@echo "Done"
.PHONY: test
test:
@echo "run test"
@echo "Run test"
go test -v ${PKGS_TO_RELEASE}
@echo "ok"
@echo "Done"
.PHONY: test-coverage
test-coverage:
@echo "run test with coverage"
@echo "Run test with coverage"
for pkg in ${PKGS_TO_RELEASE}; do \
output="coverage$${pkg#github.com/yunify/qingstor-sdk-go}"; \
mkdir -p $${output}; \
@ -81,38 +81,38 @@ test-coverage:
go tool cover -html="$${output}/profile.out" -o "$${output}/profile.html"; \
fi; \
done
@echo "ok"
@echo "Done"
.PHONY: test-race
test-race:
@echo "run test with race"
@echo "Run test with race"
go test -v -race -cpu=1,2,4 ${PKGS_TO_RELEASE}
@echo "ok"
@echo "Done"
.PHONY: integration-test
integration-test:
@echo "run integration test"
@echo "Run integration test"
pushd "./test"; go run *.go; popd
@echo "ok"
@echo "Done"
.PHONY: release
release: release-source release-source-with-vendor
.PHONY: release-source
release-source:
@echo "pack the source code"
@echo "Pack the source code"
mkdir -p "release"
zip -FS "release/${PREFIX}-source-v${VERSION}.zip" ${FILES_TO_RELEASE}
@echo "ok"
@echo "Done"
.PHONY: release-source-with-vendor
release-source-with-vendor:
@echo "pack the source code"
@echo "Pack the source code with vendor"
mkdir -p "release"
zip -FS "release/${PREFIX}-source-with-vendor-v${VERSION}.zip" ${FILES_TO_RELEASE_WITH_VENDOR}
@echo "ok"
@echo "Done"
.PHONY: clean
clean:
rm -rf $${PWD}/coverage
@echo "ok"
@echo "Done"

View file

@ -2,8 +2,8 @@ package upload
import (
"bytes"
"io"
"errors"
"io"
)
const (

View file

@ -26,25 +26,25 @@ func Init(bucket *service.Bucket, partSize int) *Uploader {
// Upload uploads multi parts of large object
func (u *Uploader) Upload(fd io.Reader, objectKey string) error {
if u.partSize < smallestPartSize {
logger.Errorf("Part size error")
logger.Errorf(nil, "Part size error")
return errors.New("the part size is too small")
}
uploadID, err := u.init(objectKey)
if err != nil {
logger.Errorf("Init multipart upload error" + err.Error())
logger.Errorf(nil, "Init multipart upload error, %v.", err)
return err
}
partNumbers, err := u.upload(fd, uploadID, objectKey)
if err != nil {
logger.Errorf("Upload multipart error" + err.Error())
logger.Errorf(nil, "Upload multipart error, %v.", err)
return err
}
err = u.complete(objectKey, uploadID, partNumbers)
if err != nil {
logger.Errorf("Complete upload error" + err.Error())
logger.Errorf(nil, "Complete upload error, %v.", err)
return err
}
@ -72,7 +72,7 @@ func (u *Uploader) upload(fd io.Reader, uploadID *string, objectKey string) ([]*
break
}
if err != nil {
logger.Errorf("Get next part failed for %v", err)
logger.Errorf(nil, "Get next part failed, %v", err)
return nil, err
}
_, err = u.bucket.UploadMultipart(
@ -84,7 +84,7 @@ func (u *Uploader) upload(fd io.Reader, uploadID *string, objectKey string) ([]*
},
)
if err != nil {
logger.Errorf("Upload multipart failed for %v", err)
logger.Errorf(nil, "Upload multipart failed, %v", err)
return nil, err
}
partNumbers = append(partNumbers, &service.ObjectPartType{

View file

@ -22,8 +22,9 @@ import (
"net/http"
"os"
"strings"
"time"
"github.com/pengsrc/go-shared/yaml"
"gopkg.in/yaml.v2"
"github.com/yunify/qingstor-sdk-go/logger"
)
@ -46,88 +47,99 @@ type Config struct {
}
// New create a Config with given AccessKeyID and SecretAccessKey.
func New(accessKeyID, secretAccessKey string) (*Config, error) {
config, err := NewDefault()
func New(accessKeyID, secretAccessKey string) (c *Config, err error) {
c, err = NewDefault()
if err != nil {
return nil, err
c = nil
return
}
config.AccessKeyID = accessKeyID
config.SecretAccessKey = secretAccessKey
c.AccessKeyID = accessKeyID
c.SecretAccessKey = secretAccessKey
config.Connection = &http.Client{}
c.Connection = &http.Client{
Timeout: time.Minute,
}
return config, nil
return
}
// NewDefault create a Config with default configuration.
func NewDefault() (*Config, error) {
config := &Config{}
err := config.LoadDefaultConfig()
func NewDefault() (c *Config, err error) {
c = &Config{}
err = c.LoadDefaultConfig()
if err != nil {
return nil, err
c = nil
return
}
config.Connection = &http.Client{}
return config, nil
c.Connection = &http.Client{
Timeout: time.Minute,
}
return
}
// Check checks the configuration.
func (c *Config) Check() error {
func (c *Config) Check() (err error) {
if c.AccessKeyID == "" {
return errors.New("access key ID not specified")
err = errors.New("access key ID not specified")
return
}
if c.SecretAccessKey == "" {
return errors.New("secret access key not specified")
err = errors.New("secret access key not specified")
return
}
if c.Host == "" {
return errors.New("server host not specified")
err = errors.New("server host not specified")
return
}
if c.Port <= 0 {
return errors.New("server port not specified")
err = errors.New("server port not specified")
return
}
if c.Protocol == "" {
return errors.New("server protocol not specified")
err = errors.New("server protocol not specified")
return
}
if c.AdditionalUserAgent != "" {
for _, x := range c.AdditionalUserAgent {
// Allow space(32) to ~(126) in ASCII Table, exclude "(34).
if int(x) < 32 || int(x) > 126 || int(x) == 32 || int(x) == 34 {
return errors.New("additional User-Agent contains characters that not allowed")
err = errors.New("additional User-Agent contains characters that not allowed")
return
}
}
}
err := logger.CheckLevel(c.LogLevel)
err = logger.CheckLevel(c.LogLevel)
if err != nil {
return err
return
}
return nil
return
}
// LoadDefaultConfig loads the default configuration for Config.
// It returns error if yaml decode failed.
func (c *Config) LoadDefaultConfig() error {
_, err := yaml.Decode([]byte(DefaultConfigFileContent), c)
func (c *Config) LoadDefaultConfig() (err error) {
err = yaml.Unmarshal([]byte(DefaultConfigFileContent), c)
if err != nil {
logger.Errorf("Config parse error: " + err.Error())
return err
logger.Errorf(nil, "Config parse error, %v.", err)
return
}
logger.SetLevel(c.LogLevel)
return nil
return
}
// LoadUserConfig loads user configuration in ~/.qingstor/config.yaml for Config.
// It returns error if file not found.
func (c *Config) LoadUserConfig() error {
_, err := os.Stat(GetUserConfigFilePath())
func (c *Config) LoadUserConfig() (err error) {
_, err = os.Stat(GetUserConfigFilePath())
if err != nil {
logger.Warnf("Installing default config file to \"" + GetUserConfigFilePath() + "\"")
logger.Warnf(nil, "Installing default config file to %s.", GetUserConfigFilePath())
InstallDefaultUserConfig()
}
@ -136,14 +148,14 @@ func (c *Config) LoadUserConfig() error {
// LoadConfigFromFilePath loads configuration from a specified local path.
// It returns error if file not found or yaml decode failed.
func (c *Config) LoadConfigFromFilePath(filepath string) error {
if strings.Index(filepath, "~/") == 0 {
filepath = strings.Replace(filepath, "~/", getHome()+"/", 1)
func (c *Config) LoadConfigFromFilePath(filePath string) (err error) {
if strings.Index(filePath, "~/") == 0 {
filePath = strings.Replace(filePath, "~/", getHome()+"/", 1)
}
yamlString, err := ioutil.ReadFile(filepath)
yamlString, err := ioutil.ReadFile(filePath)
if err != nil {
logger.Errorf("File not found: " + filepath)
logger.Errorf(nil, "File not found: %s.", filePath)
return err
}
@ -152,21 +164,20 @@ func (c *Config) LoadConfigFromFilePath(filepath string) error {
// LoadConfigFromContent loads configuration from a given byte slice.
// It returns error if yaml decode failed.
func (c *Config) LoadConfigFromContent(content []byte) error {
func (c *Config) LoadConfigFromContent(content []byte) (err error) {
c.LoadDefaultConfig()
_, err := yaml.Decode(content, c)
err = yaml.Unmarshal(content, c)
if err != nil {
logger.Errorf("Config parse error: " + err.Error())
return err
logger.Errorf(nil, "Config parse error, %v.", err)
return
}
err = c.Check()
if err != nil {
return err
return
}
logger.SetLevel(c.LogLevel)
return nil
return
}

View file

@ -56,7 +56,7 @@ func TestLoadDefaultConfig(t *testing.T) {
assert.Equal(t, "https", config.Protocol)
assert.Equal(t, "qingstor.com", config.Host)
assert.Equal(t, "", config.AdditionalUserAgent)
assert.Equal(t, "warning", logger.GetLevel())
assert.Equal(t, "WARN", logger.GetLevel())
}
func TestLoadUserConfig(t *testing.T) {
@ -83,7 +83,7 @@ log_level: 'debug'
assert.Equal(t, "secret_access_key", config.SecretAccessKey)
assert.Equal(t, "https", config.Protocol)
assert.Equal(t, "qingstor.com", config.Host)
assert.Equal(t, "debug", logger.GetLevel())
assert.Equal(t, "DEBUG", logger.GetLevel())
}
func TestNewDefault(t *testing.T) {

View file

@ -1,35 +1,29 @@
hash: 2e6b1ed4a2ee0638abc2e819ac3c247eaf80fa0f2053cfc41eecf883054c6032
updated: 2017-07-20T20:14:05.143145325+08:00
hash: 08f9d9c9c14c4e5927e38688e6bab5bc44b5cb920d05b2523de680a115f5a6b7
updated: 2017-11-25T11:24:10.452444+08:00
imports:
- name: github.com/DATA-DOG/godog
version: 70f777599da0f5de682b8848d356611c1738b695
version: 272624afcc2fc5f818ce069e2e417e7b4fa8bb6c
subpackages:
- colors
- gherkin
- name: github.com/pengsrc/go-shared
version: 454950d6a0782c34427d4f29b46c6bf447256f20
version: b98065a377794d577e2a0e32869378b9ce4b8952
subpackages:
- buffer
- check
- convert
- json
- yaml
- name: github.com/sirupsen/logrus
version: 00386b3fbd637582f90cb17482dc3087646c0ac2
- name: golang.org/x/sys
version: f3918c30c5c2cb527c0b071a27c35120a6c0719a
repo: https://github.com/golang/sys.git
subpackages:
- unix
- log
- reopen
- name: gopkg.in/yaml.v2
version: a5b47d31c556af34a302ce5d659e6fea44d90de0
version: 287cf08546ab5e7e37d55a84f7ed3fd1db036de5
repo: https://github.com/go-yaml/yaml.git
testImports:
- name: github.com/davecgh/go-spew
version: 346938d642f2ec3594ed81d874461961cd0faa76
version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9
subpackages:
- spew
- name: github.com/pmezard/go-difflib
version: 792786c7400a136282c1664665ae0a8db921c6c2
version: d8ed2627bdf02c080bf22230dbb337003b7aba2d
subpackages:
- difflib
- name: github.com/stretchr/testify

View file

@ -1,4 +1,11 @@
package: github.com/yunify/qingstor-sdk-go
import:
# YAML
- package: gopkg.in/yaml.v2
version: 287cf08546ab5e7e37d55a84f7ed3fd1db036de5
repo: https://github.com/go-yaml/yaml.git
# Shared packages
- package: github.com/pengsrc/go-shared
version: v0.0.8
version: v0.1.1

View file

@ -15,53 +15,28 @@
// +-------------------------------------------------------------------------
// Package logger provides support for logging to stdout and stderr.
// Log entries will be logged with format: $timestamp $hostname [$pid]: $severity $message.
package logger
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/pengsrc/go-shared/log"
)
// Logger is the interface of SDK logger.
type Logger interface {
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
Panicf(format string, args ...interface{})
}
// LogFormatter is used to format log entry.
type LogFormatter struct{}
// Format formats a given log entry, returns byte slice and error.
func (c *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
level := strings.ToUpper(entry.Level.String())
if level == "WARNING" {
level = "WARN"
}
if len(level) < 5 {
level = strings.Repeat(" ", 5-len(level)) + level
}
return []byte(fmt.Sprintf(
"[%s #%d] %s -- : %s\n",
time.Now().Format("2006-01-02T15:04:05.000Z"),
os.Getpid(),
level,
entry.Message),
), nil
Debugf(ctx context.Context, format string, v ...interface{})
Infof(ctx context.Context, format string, v ...interface{})
Warnf(ctx context.Context, format string, v ...interface{})
Errorf(ctx context.Context, format string, v ...interface{})
Fatalf(ctx context.Context, format string, v ...interface{})
Panicf(ctx context.Context, format string, v ...interface{})
}
// CheckLevel checks whether the log level is valid.
func CheckLevel(level string) error {
if _, err := logrus.ParseLevel(level); err != nil {
if _, err := log.ParseLevel(level); err != nil {
return fmt.Errorf(`log level not valid: "%s"`, level)
}
return nil
@ -69,20 +44,20 @@ func CheckLevel(level string) error {
// GetLevel get the log level string.
func GetLevel() string {
if l, ok := instance.(*logrus.Logger); ok {
return l.Level.String()
if l, ok := instance.(*log.Logger); ok {
return l.GetLevel()
}
return "unknown"
return "UNKNOWN"
}
// SetLevel sets the log level. Valid levels are "debug", "info", "warn", "error", and "fatal".
// SetLevel sets the log level.
// Valid levels are "debug", "info", "warn", "error", and "fatal".
func SetLevel(level string) {
if l, ok := instance.(*logrus.Logger); ok {
lvl, err := logrus.ParseLevel(level)
if l, ok := instance.(*log.Logger); ok {
err := l.SetLevel(level)
if err != nil {
Fatalf(fmt.Sprintf(`log level not valid: "%s"`, level))
Fatalf(nil, fmt.Sprintf(`log level not valid: "%s"`, level))
}
l.Level = lvl
}
}
@ -92,37 +67,36 @@ func SetLogger(l Logger) {
}
// Debugf logs a message with severity DEBUG.
func Debugf(format string, v ...interface{}) {
instance.Debugf(format, v...)
func Debugf(ctx context.Context, format string, v ...interface{}) {
instance.Debugf(ctx, format, v...)
}
// Infof logs a message with severity INFO.
func Infof(format string, v ...interface{}) {
instance.Infof(format, v...)
func Infof(ctx context.Context, format string, v ...interface{}) {
instance.Infof(ctx, format, v...)
}
// Warnf logs a message with severity WARN.
func Warnf(format string, v ...interface{}) {
instance.Warnf(format, v...)
func Warnf(ctx context.Context, format string, v ...interface{}) {
instance.Warnf(ctx, format, v...)
}
// Errorf logs a message with severity ERROR.
func Errorf(format string, v ...interface{}) {
instance.Errorf(format, v...)
func Errorf(ctx context.Context, format string, v ...interface{}) {
instance.Errorf(ctx, format, v...)
}
// Fatalf logs a message with severity ERROR followed by a call to os.Exit().
func Fatalf(format string, v ...interface{}) {
instance.Fatalf(format, v...)
func Fatalf(ctx context.Context, format string, v ...interface{}) {
instance.Fatalf(ctx, format, v...)
}
var instance Logger
func init() {
l := logrus.New()
l.Formatter = &LogFormatter{}
l.Out = os.Stderr
l.Level = logrus.WarnLevel
l, err := log.NewTerminalLogger(log.WarnLevel.String())
if err != nil {
panic(fmt.Sprintf("failed to initialize QingStor SDK logger: %v", err))
}
instance = l
}

View file

@ -17,6 +17,7 @@
package builder
import (
"encoding/json"
"errors"
"fmt"
"io"
@ -29,7 +30,6 @@ import (
"unicode"
"github.com/pengsrc/go-shared/convert"
"github.com/pengsrc/go-shared/json"
"github.com/yunify/qingstor-sdk-go/request/data"
"github.com/yunify/qingstor-sdk-go/utils"
@ -100,7 +100,7 @@ func (b *BaseBuilder) parseRequestQueryAndHeaders() error {
requestQuery := map[string]string{}
requestHeaders := map[string]string{}
maps := map[string](map[string]string){
"query": requestQuery,
"query": requestQuery,
"headers": requestHeaders,
}
@ -177,7 +177,7 @@ func (b *BaseBuilder) parseRequestBody() error {
}
if len(requestData) != 0 {
dataValue, err := json.Encode(requestData, true)
dataValue, err := json.Marshal(requestData)
if err != nil {
return err
}

View file

@ -75,24 +75,24 @@ func (qb *QingStorBuilder) BuildHTTPRequest(o *data.Operation, i *reflect.Value)
return nil, err
}
logger.Infof(fmt.Sprintf(
logger.Infof(nil, fmt.Sprintf(
"Built QingStor request: [%d] %s",
convert.StringToUnixTimestamp(httpRequest.Header.Get("Date"), convert.RFC822),
httpRequest.URL.String()),
)
httpRequest.URL.String(),
))
logger.Infof(fmt.Sprintf(
logger.Infof(nil, fmt.Sprintf(
"QingStor request headers: [%d] %s",
convert.StringToUnixTimestamp(httpRequest.Header.Get("Date"), convert.RFC822),
fmt.Sprint(httpRequest.Header)),
)
fmt.Sprint(httpRequest.Header),
))
if qb.baseBuilder.parsedBodyString != "" {
logger.Infof(fmt.Sprintf(
logger.Infof(nil, fmt.Sprintf(
"QingStor request body string: [%d] %s",
convert.StringToUnixTimestamp(httpRequest.Header.Get("Date"), convert.RFC822),
qb.baseBuilder.parsedBodyString),
)
qb.baseBuilder.parsedBodyString,
))
}
return httpRequest, nil

View file

@ -216,7 +216,7 @@ func (r *Request) send() error {
retries := r.Operation.Config.ConnectionRetries + 1
for {
if retries > 0 {
logger.Infof(fmt.Sprintf(
logger.Infof(nil, fmt.Sprintf(
"Sending request: [%d] %s %s",
convert.StringToUnixTimestamp(r.HTTPRequest.Header.Get("Date"), convert.RFC822),
r.Operation.RequestMethod,

View file

@ -85,7 +85,7 @@ func (qss *QingStorSigner) BuildSignature(request *http.Request) (string, error)
signature := strings.TrimSpace(base64.StdEncoding.EncodeToString(h.Sum(nil)))
authorization := "QS " + qss.AccessKeyID + ":" + signature
logger.Debugf(fmt.Sprintf(
logger.Debugf(nil, fmt.Sprintf(
"QingStor authorization: [%d] %s",
convert.StringToUnixTimestamp(request.Header.Get("Date"), convert.RFC822),
authorization,
@ -111,7 +111,7 @@ func (qss *QingStorSigner) BuildQuerySignature(request *http.Request, expires in
qss.AccessKeyID, expires, signature,
)
logger.Debugf(fmt.Sprintf(
logger.Debugf(nil, fmt.Sprintf(
"QingStor query signature: [%d] %s",
convert.StringToUnixTimestamp(request.Header.Get("Date"), convert.RFC822),
query,
@ -141,7 +141,7 @@ func (qss *QingStorSigner) BuildStringToSign(request *http.Request) (string, err
}
stringToSign += canonicalizedResource
logger.Debugf(fmt.Sprintf(
logger.Debugf(nil, fmt.Sprintf(
"QingStor string to sign: [%d] %s",
convert.StringToUnixTimestamp(request.Header.Get("Date"), convert.RFC822),
stringToSign,
@ -167,7 +167,7 @@ func (qss *QingStorSigner) BuildQueryStringToSign(request *http.Request, expires
}
stringToSign += canonicalizedResource
logger.Debugf(fmt.Sprintf(
logger.Debugf(nil, fmt.Sprintf(
"QingStor query string to sign: [%d] %s",
convert.StringToUnixTimestamp(request.Header.Get("Date"), convert.RFC822),
stringToSign,
@ -231,7 +231,7 @@ func (qss *QingStorSigner) buildCanonicalizedResource(request *http.Request) (st
path = path + "?" + joinedParts
}
logger.Debugf(fmt.Sprintf(
logger.Debugf(nil, fmt.Sprintf(
"QingStor canonicalized resource: [%d] %s",
convert.StringToUnixTimestamp(request.Header.Get("Date"), convert.RFC822),
path,

View file

@ -18,6 +18,7 @@ package unpacker
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"reflect"
@ -25,7 +26,6 @@ import (
"time"
"github.com/pengsrc/go-shared/convert"
"github.com/pengsrc/go-shared/json"
"github.com/yunify/qingstor-sdk-go/logger"
"github.com/yunify/qingstor-sdk-go/request/data"
@ -69,7 +69,7 @@ func (b *BaseUnpacker) exposeStatusCode() error {
if value.IsValid() {
switch value.Interface().(type) {
case *int:
logger.Infof(fmt.Sprintf(
logger.Infof(nil, fmt.Sprintf(
"QingStor response status code: [%d] %d",
convert.StringToUnixTimestamp(b.httpResponse.Header.Get("Date"), convert.RFC822),
b.httpResponse.StatusCode,
@ -82,7 +82,7 @@ func (b *BaseUnpacker) exposeStatusCode() error {
}
func (b *BaseUnpacker) parseResponseHeaders() error {
logger.Infof(fmt.Sprintf(
logger.Infof(nil, fmt.Sprintf(
"QingStor response headers: [%d] %s",
convert.StringToUnixTimestamp(b.httpResponse.Header.Get("Date"), convert.RFC822),
fmt.Sprint(b.httpResponse.Header),
@ -145,7 +145,7 @@ func (b *BaseUnpacker) parseResponseBody() error {
buffer.ReadFrom(b.httpResponse.Body)
b.httpResponse.Body.Close()
logger.Infof(fmt.Sprintf(
logger.Infof(nil, fmt.Sprintf(
"QingStor response body string: [%d] %s",
convert.StringToUnixTimestamp(b.httpResponse.Header.Get("Date"), convert.RFC822),
string(buffer.Bytes()),
@ -168,13 +168,13 @@ func (b *BaseUnpacker) parseResponseElements() error {
buffer.ReadFrom(b.httpResponse.Body)
b.httpResponse.Body.Close()
logger.Infof(fmt.Sprintf(
logger.Infof(nil, fmt.Sprintf(
"QingStor response body string: [%d] %s",
convert.StringToUnixTimestamp(b.httpResponse.Header.Get("Date"), convert.RFC822),
string(buffer.Bytes()),
))
_, err := json.Decode(buffer.Bytes(), b.output.Interface())
err := json.Unmarshal(buffer.Bytes(), b.output.Interface())
if err != nil {
return err
}

View file

@ -18,11 +18,10 @@ package unpacker
import (
"bytes"
"encoding/json"
"net/http"
"reflect"
"github.com/pengsrc/go-shared/json"
"github.com/yunify/qingstor-sdk-go/request/data"
"github.com/yunify/qingstor-sdk-go/request/errors"
)
@ -57,7 +56,7 @@ func (qu *QingStorUnpacker) parseError() error {
qsError := &errors.QingStorError{}
if buffer.Len() > 0 {
_, err := json.Decode(buffer.Bytes(), qsError)
err := json.Unmarshal(buffer.Bytes(), qsError)
if err != nil {
return err
}

View file

@ -20,25 +20,25 @@
package service
import (
"net/http"
"net/http"
"github.com/yunify/qingstor-sdk-go/config"
"github.com/yunify/qingstor-sdk-go/request"
"github.com/yunify/qingstor-sdk-go/request/data"
"github.com/yunify/qingstor-sdk-go/config"
"github.com/yunify/qingstor-sdk-go/request"
"github.com/yunify/qingstor-sdk-go/request/data"
)
var _ http.Header
{{if $service.Description}}// Service {{$service.Description}}{{end}}
type Service struct {
Config *config.Config
Config *config.Config
}
// Init initializes a new service.
func Init(c *config.Config) (*Service, error) {
return &Service{Config: c}, nil
return &Service{Config: c}, nil
}
{{range $_, $operation := $service.Operations}}
{{template "RenderOperation" passThrough $service $operation}}
{{template "RenderOperation" passThrough $service $operation}}
{{end}}

View file

@ -1,391 +1,391 @@
{{define "Type"}}
{{- $typeName := index . 0 -}}
{{- $disablePointer := index . 1 -}}
{{- $typeName := index . 0 -}}
{{- $disablePointer := index . 1 -}}
{{- if eq $typeName "string" -}}
{{- if not $disablePointer -}}*{{- end -}}string
{{- else if eq $typeName "boolean" -}}
{{- if not $disablePointer -}}*{{- end -}}bool
{{- else if eq $typeName "integer" -}}
{{- if not $disablePointer -}}*{{- end -}}int
{{- else if eq $typeName "long" -}}
{{- if not $disablePointer -}}*{{- end -}}int64
{{- else if eq $typeName "timestamp" -}}
{{- if not $disablePointer -}}*{{- end -}}time.Time
{{- else if eq $typeName "binary" -}}
io.Reader
{{- else if eq $typeName "array" -}}
interface{}
{{- else if eq $typeName "object" -}}
interface{}
{{- else if eq $typeName "map" -}}
interface{}
{{- else if eq $typeName "any" -}}
interface{}
{{- else -}}
*{{$typeName | camelCase}}Type
{{- end -}}
{{- if eq $typeName "string" -}}
{{- if not $disablePointer -}}*{{- end -}}string
{{- else if eq $typeName "boolean" -}}
{{- if not $disablePointer -}}*{{- end -}}bool
{{- else if eq $typeName "integer" -}}
{{- if not $disablePointer -}}*{{- end -}}int
{{- else if eq $typeName "long" -}}
{{- if not $disablePointer -}}*{{- end -}}int64
{{- else if eq $typeName "timestamp" -}}
{{- if not $disablePointer -}}*{{- end -}}time.Time
{{- else if eq $typeName "binary" -}}
io.Reader
{{- else if eq $typeName "array" -}}
interface{}
{{- else if eq $typeName "object" -}}
interface{}
{{- else if eq $typeName "map" -}}
interface{}
{{- else if eq $typeName "any" -}}
interface{}
{{- else -}}
*{{$typeName | camelCase}}Type
{{- end -}}
{{end}}
{{define "PropertyType"}}
{{- $property := index . 0 -}}
{{- $disablePointer := index . 1 -}}
{{- $property := index . 0 -}}
{{- $disablePointer := index . 1 -}}
{{- if eq $property.Type "object" -}}
{{template "Type" passThrough $property.ExtraType $disablePointer}}
{{- else if eq $property.Type "array" -}}
[]{{template "Type" passThrough $property.ExtraType $disablePointer}}
{{- else if eq $property.Type "map" -}}
map[string]{{template "Type" passThrough $property.ExtraType $disablePointer}}
{{- else if eq $property.Type "any" -}}
{{template "Type" passThrough $property.Type $disablePointer}}
{{- else -}}
{{template "Type" passThrough $property.Type $disablePointer}}
{{- end -}}
{{- if eq $property.Type "object" -}}
{{template "Type" passThrough $property.ExtraType $disablePointer}}
{{- else if eq $property.Type "array" -}}
[]{{template "Type" passThrough $property.ExtraType $disablePointer}}
{{- else if eq $property.Type "map" -}}
map[string]{{template "Type" passThrough $property.ExtraType $disablePointer}}
{{- else if eq $property.Type "any" -}}
{{template "Type" passThrough $property.Type $disablePointer}}
{{- else -}}
{{template "Type" passThrough $property.Type $disablePointer}}
{{- end -}}
{{end}}
{{define "PropertyTags"}}
{{- $property := . -}}
{{- if $property.IsRequired -}}
{{- printf `json:"%s"` ($property.Name | normalized) -}}
{{- else -}}
{{- printf `json:"%s,omitempty"` ($property.Name | normalized) -}}
{{- end -}}
{{- printf ` name:"%s"` ($property.Name | normalized) -}}
{{- if $property.Format}}
{{- printf ` format:"%s"` $property.Format -}}
{{- end -}}
{{- if $property.Default -}}
{{- printf ` default:"%s"` $property.Default -}}
{{- end -}}
{{- $property := . -}}
{{- if $property.IsRequired -}}
{{- printf `json:"%s"` ($property.Name | normalized) -}}
{{- else -}}
{{- printf `json:"%s,omitempty"` ($property.Name | normalized) -}}
{{- end -}}
{{- printf ` name:"%s"` ($property.Name | normalized) -}}
{{- if $property.Format}}
{{- printf ` format:"%s"` $property.Format -}}
{{- end -}}
{{- if $property.Default -}}
{{- printf ` default:"%s"` $property.Default -}}
{{- end -}}
{{end}}
{{define "PropertyTagsDashConnected"}}
{{- $property := . -}}
{{- printf `json:"%s"` ($property.Name | dashConnected) -}}
{{- printf ` name:"%s"` ($property.Name | dashConnected) -}}
{{- $property := . -}}
{{- printf `json:"%s"` ($property.Name | dashConnected) -}}
{{- printf ` name:"%s"` ($property.Name | dashConnected) -}}
{{end}}
{{define "PropertyExtraTags"}}
{{- $propertyExtraTags := . -}}
{{- if $propertyExtraTags -}}
{{- printf " %s" $propertyExtraTags -}}
{{- end -}}
{{- $propertyExtraTags := . -}}
{{- if $propertyExtraTags -}}
{{- printf " %s" $propertyExtraTags -}}
{{- end -}}
{{end}}
{{define "RenderProperties"}}
{{- $customizedType := index . 0 -}}
{{- $propertyExtraTags := index . 1 -}}
{{- $operationName := index . 2 -}}
{{- $customizedType := index . 0 -}}
{{- $propertyExtraTags := index . 1 -}}
{{- $operationName := index . 2 -}}
{{range $_, $property := $customizedType.Properties -}}
{{if or (ne $operationName "Delete Multiple Objects") (ne $property.ID "Content-MD5") -}}
{{if $property.Description -}}
// {{$property.Description}}
{{end -}}
{{if $property.Enum -}}
// {{$property.ID | camelCase}}'s available values: {{$property.Enum | commaConnected}}
{{end -}}
{{$property.ID | camelCase | upperFirst}}{{" " -}}
{{template "PropertyType" passThrough $property false}}{{" " -}}
`{{template "PropertyTags" $property}}{{template "PropertyExtraTags" $propertyExtraTags}}`{{" " -}}
{{if $property.IsRequired -}}
// Required
{{- end}}
{{- end}}
{{end}}
{{range $_, $property := $customizedType.Properties -}}
{{if or (ne $operationName "Delete Multiple Objects") (ne $property.ID "Content-MD5") -}}
{{if $property.Description -}}
// {{$property.Description}}
{{end -}}
{{if $property.Enum -}}
// {{$property.ID | camelCase}}'s available values: {{$property.Enum | commaConnected}}
{{end -}}
{{$property.ID | camelCase | upperFirst}}{{" " -}}
{{template "PropertyType" passThrough $property false}}{{" " -}}
`{{template "PropertyTags" $property}}{{template "PropertyExtraTags" $propertyExtraTags}}`{{" " -}}
{{if $property.IsRequired -}}
// Required
{{- end}}
{{- end}}
{{end}}
{{end}}
{{define "RenderOperation"}}
{{$service := index . 0}}
{{$operation := index . 1}}
{{$service := index . 0}}
{{$operation := index . 1}}
{{$belongs := replace $service.Name "QingStor" "Service" -1}}
{{$belongs := replace $belongs "Object" "Bucket" -1}}
{{$opID := $operation.ID | camelCase}}
{{$belongs := replace $service.Name "QingStor" "Service" -1}}
{{$belongs := replace $belongs "Object" "Bucket" -1}}
{{$opID := $operation.ID | camelCase}}
{{$isBucket := eq $service.Name "Bucket"}}
{{$isObject := eq $service.Name "Object"}}
{{$isBucket := eq $service.Name "Bucket"}}
{{$isObject := eq $service.Name "Object"}}
{{$hasQuery := gt (len $operation.Request.Query.Properties) 0}}
{{$hasHeaders := gt (len $operation.Request.Headers.Properties) 0}}
{{$hasElements := gt (len $operation.Request.Elements.Properties) 0}}
{{$hasStringBody := eq $operation.Request.Body.Type "string"}}
{{$hasBinaryBody := eq $operation.Request.Body.Type "binary"}}
{{$hasInput := or $hasQuery $hasHeaders $hasElements $hasStringBody $hasBinaryBody}}
{{$hasQuery := gt (len $operation.Request.Query.Properties) 0}}
{{$hasHeaders := gt (len $operation.Request.Headers.Properties) 0}}
{{$hasElements := gt (len $operation.Request.Elements.Properties) 0}}
{{$hasStringBody := eq $operation.Request.Body.Type "string"}}
{{$hasBinaryBody := eq $operation.Request.Body.Type "binary"}}
{{$hasInput := or $hasQuery $hasHeaders $hasElements $hasStringBody $hasBinaryBody}}
{{if $operation.Description -}}
{{if eq $belongs "Bucket" -}}
// {{replace $opID "Bucket" "" -1}} does {{$operation.Description}}
{{else -}}
// {{$opID}} does {{$operation.Description}}
{{end -}}
{{end -}}
{{if $operation.DocumentationURL -}}
// Documentation URL: {{$operation.DocumentationURL}}
{{- end}}
{{if eq $belongs "Bucket" -}}
func (s *{{$belongs}}) {{replace $opID "Bucket" "" -1 -}}(
{{- if $isObject}}objectKey string,{{end -}}
{{- if $hasInput}}input *{{$opID}}Input{{end -}}
) (*{{$opID}}Output, error) {
{{else -}}
func (s *{{$belongs}}) {{$opID}}(
{{- if $hasInput}}input *{{$opID}}Input{{end -}}
) (*{{$opID}}Output, error) {
{{end -}}
{{if eq $belongs "Bucket" -}}
r, x, err := s.{{replace $opID "Bucket" "" -1}}Request(
{{- if $isObject}}objectKey,{{end -}}
{{- if $hasInput}}input{{end -}}
)
{{else -}}
r, x, err := s.{{$opID}}Request(
{{- if $hasInput}}input{{end -}}
)
{{end}}
if err != nil {
return x, err
}
{{if $operation.Description -}}
{{if eq $belongs "Bucket" -}}
// {{replace $opID "Bucket" "" -1}} does {{$operation.Description}}
{{else -}}
// {{$opID}} does {{$operation.Description}}
{{end -}}
{{end -}}
{{if $operation.DocumentationURL -}}
// Documentation URL: {{$operation.DocumentationURL}}
{{- end}}
{{if eq $belongs "Bucket" -}}
func (s *{{$belongs}}) {{replace $opID "Bucket" "" -1 -}}(
{{- if $isObject}}objectKey string,{{end -}}
{{- if $hasInput}}input *{{$opID}}Input{{end -}}
) (*{{$opID}}Output, error) {
{{else -}}
func (s *{{$belongs}}) {{$opID}}(
{{- if $hasInput}}input *{{$opID}}Input{{end -}}
) (*{{$opID}}Output, error) {
{{end -}}
{{if eq $belongs "Bucket" -}}
r, x, err := s.{{replace $opID "Bucket" "" -1}}Request(
{{- if $isObject}}objectKey,{{end -}}
{{- if $hasInput}}input{{end -}}
)
{{else -}}
r, x, err := s.{{$opID}}Request(
{{- if $hasInput}}input{{end -}}
)
{{end}}
if err != nil {
return x, err
}
err = r.Send()
if err != nil {
return nil, err
}
err = r.Send()
if err != nil {
return nil, err
}
requestID := r.HTTPResponse.Header.Get(http.CanonicalHeaderKey("X-QS-Request-ID"))
x.RequestID = &requestID
requestID := r.HTTPResponse.Header.Get(http.CanonicalHeaderKey("X-QS-Request-ID"))
x.RequestID = &requestID
return x, err
}
return x, err
}
{{if $operation.Description -}}
{{if eq $belongs "Bucket" -}}
// {{replace $opID "Bucket" "" -1}}Request creates request and output object of {{$opID}}.
{{else -}}
// {{$opID}}Request creates request and output object of {{$opID}}.
{{end -}}
{{end -}}
{{if eq $belongs "Bucket" -}}
func (s *{{$belongs}}) {{replace $opID "Bucket" "" -1 -}}Request(
{{- if $isObject}}objectKey string,{{end -}}
{{- if $hasInput}}input *{{$opID}}Input{{end -}}
) (*request.Request, *{{$opID}}Output, error) {
{{else -}}
func (s *{{$belongs}}) {{$opID}}Request(
{{- if $hasInput}}input *{{$opID}}Input{{end -}}
) (*request.Request, *{{$opID}}Output, error) {
{{end -}}
{{if $hasInput}}
if input == nil {
input = &{{$opID}}Input{}
}
{{end}}
{{$path := $operation.Request.Path}}
{{$path := replace $path "{" "<" -1}}
{{$path := replace $path "}" ">" -1}}
{{$path := dashConnected $path}}
{{if $operation.Description -}}
{{if eq $belongs "Bucket" -}}
// {{replace $opID "Bucket" "" -1}}Request creates request and output object of {{$opID}}.
{{else -}}
// {{$opID}}Request creates request and output object of {{$opID}}.
{{end -}}
{{end -}}
{{if eq $belongs "Bucket" -}}
func (s *{{$belongs}}) {{replace $opID "Bucket" "" -1 -}}Request(
{{- if $isObject}}objectKey string,{{end -}}
{{- if $hasInput}}input *{{$opID}}Input{{end -}}
) (*request.Request, *{{$opID}}Output, error) {
{{else -}}
func (s *{{$belongs}}) {{$opID}}Request(
{{- if $hasInput}}input *{{$opID}}Input{{end -}}
) (*request.Request, *{{$opID}}Output, error) {
{{end -}}
{{if $hasInput}}
if input == nil {
input = &{{$opID}}Input{}
}
{{end}}
{{$path := $operation.Request.Path}}
{{$path := replace $path "{" "<" -1}}
{{$path := replace $path "}" ">" -1}}
{{$path := dashConnected $path}}
{{- if ne $belongs "Service"}}
properties := *s.Properties
{{- end}}
{{if eq $service.Name "Object"}}
properties.ObjectKey = &objectKey
{{end}}
{{- if ne $belongs "Service"}}
properties := *s.Properties
{{- end}}
{{if eq $service.Name "Object"}}
properties.ObjectKey = &objectKey
{{end}}
o := &data.Operation{
Config: s.Config,
{{- if ne $belongs "Service"}}
Properties: &properties,
{{- end}}
APIName: "{{$operation.Name}}",
RequestMethod: "{{$operation.Request.Method}}",
RequestURI: "{{$path}}",
StatusCodes: []int{
{{range $keyStatus, $valueStatus := $operation.Responses -}}
{{- if $valueStatus.StatusCode -}}
{{$valueStatus.StatusCode.Code}}, // {{$valueStatus.StatusCode.Description}}
{{else}}
200, // OK
{{end -}}
{{else}}
200, // OK
{{end -}}
},
}
o := &data.Operation{
Config: s.Config,
{{- if ne $belongs "Service"}}
Properties: &properties,
{{- end}}
APIName: "{{$operation.Name}}",
RequestMethod: "{{$operation.Request.Method}}",
RequestURI: "{{$path}}",
StatusCodes: []int{
{{range $keyStatus, $valueStatus := $operation.Responses -}}
{{- if $valueStatus.StatusCode -}}
{{$valueStatus.StatusCode.Code}}, // {{$valueStatus.StatusCode.Description}}
{{else}}
200, // OK
{{end -}}
{{else}}
200, // OK
{{end -}}
},
}
x := &{{$opID}}Output{}
r, err := request.New(o, {{if $hasInput}}input{{else}}nil{{end}}, x)
if err != nil {
return nil, nil, err
}
x := &{{$opID}}Output{}
r, err := request.New(o, {{if $hasInput}}input{{else}}nil{{end}}, x)
if err != nil {
return nil, nil, err
}
return r, x, nil
}
return r, x, nil
}
{{if $hasInput}}
// {{$opID}}Input presents input for {{$opID}}.
type {{$opID}}Input struct {
{{- if $operation.Request.Query.Properties | len}}
{{$data := $operation.Request.Query -}}
{{template "RenderProperties" passThrough $data `location:"query"` $operation.Name}}
{{end}}
{{if $hasInput}}
// {{$opID}}Input presents input for {{$opID}}.
type {{$opID}}Input struct {
{{- if $operation.Request.Query.Properties | len}}
{{$data := $operation.Request.Query -}}
{{template "RenderProperties" passThrough $data `location:"query"` $operation.Name}}
{{end}}
{{- if $operation.Request.Headers.Properties | len}}
{{$data := $operation.Request.Headers -}}
{{template "RenderProperties" passThrough $data `location:"headers"` $operation.Name}}
{{end}}
{{- if $operation.Request.Headers.Properties | len}}
{{$data := $operation.Request.Headers -}}
{{template "RenderProperties" passThrough $data `location:"headers"` $operation.Name}}
{{end}}
{{- if $operation.Request.Elements.Properties | len}}
{{$data := $operation.Request.Elements -}}
{{template "RenderProperties" passThrough $data `location:"elements"` $operation.Name}}
{{end}}
{{- if $operation.Request.Elements.Properties | len}}
{{$data := $operation.Request.Elements -}}
{{template "RenderProperties" passThrough $data `location:"elements"` $operation.Name}}
{{end}}
{{- if eq $operation.Request.Body.Type "string"}}
{{if $operation.Request.Body.Description -}}
// {{$operation.Request.Body.Description}}
{{- end}}
Body string `location:"body"`
{{else if eq $operation.Request.Body.Type "binary"}}
{{if $operation.Request.Body.Description -}}
// {{$operation.Request.Body.Description}}
{{- end}}
Body io.Reader `location:"body"`
{{end}}
}
{{- if eq $operation.Request.Body.Type "string"}}
{{if $operation.Request.Body.Description -}}
// {{$operation.Request.Body.Description}}
{{- end}}
Body string `location:"body"`
{{else if eq $operation.Request.Body.Type "binary"}}
{{if $operation.Request.Body.Description -}}
// {{$operation.Request.Body.Description}}
{{- end}}
Body io.Reader `location:"body"`
{{end}}
}
// Validate validates the input for {{$opID}}.
func (v *{{$opID}}Input) Validate() error {
{{template "ValidateCustomizedType" passThrough $operation.Request.Query $operation.Name}}
{{template "ValidateCustomizedType" passThrough $operation.Request.Headers $operation.Name}}
{{template "ValidateCustomizedType" passThrough $operation.Request.Elements $operation.Name}}
// Validate validates the input for {{$opID}}.
func (v *{{$opID}}Input) Validate() error {
{{template "ValidateCustomizedType" passThrough $operation.Request.Query $operation.Name}}
{{template "ValidateCustomizedType" passThrough $operation.Request.Headers $operation.Name}}
{{template "ValidateCustomizedType" passThrough $operation.Request.Elements $operation.Name}}
return nil
}
{{end}}
return nil
}
{{end}}
// {{$opID}}Output presents output for {{$opID}}.
type {{$opID}}Output struct {
StatusCode *int `location:"statusCode"`
// {{$opID}}Output presents output for {{$opID}}.
type {{$opID}}Output struct {
StatusCode *int `location:"statusCode"`
RequestID *string `location:"requestID"`
{{range $keyStatus, $valueStatus := $operation.Responses -}}
{{if eq $valueStatus.Body.Type "string"}}
{{if $valueStatus.Body.Description -}}
// {{$valueStatus.Body.Description}}
{{- end}}
Body string `location:"body"`
{{else if eq $valueStatus.Body.Type "binary"}}
{{if $valueStatus.Body.Description -}}
// {{$valueStatus.Body.Description}}
{{- end}}
Body io.ReadCloser `location:"body"`
{{end}}
RequestID *string `location:"requestID"`
{{range $keyStatus, $valueStatus := $operation.Responses -}}
{{if eq $valueStatus.Body.Type "string"}}
{{if $valueStatus.Body.Description -}}
// {{$valueStatus.Body.Description}}
{{- end}}
Body string `location:"body"`
{{else if eq $valueStatus.Body.Type "binary"}}
{{if $valueStatus.Body.Description -}}
// {{$valueStatus.Body.Description}}
{{- end}}
Body io.ReadCloser `location:"body"`
{{end}}
{{if $valueStatus.Elements.Properties | len}}
{{$data := $valueStatus.Elements}}
{{template "RenderProperties" passThrough $data `location:"elements"` $operation.Name}}
{{end}}
{{if $valueStatus.Elements.Properties | len}}
{{$data := $valueStatus.Elements}}
{{template "RenderProperties" passThrough $data `location:"elements"` $operation.Name}}
{{end}}
{{if $valueStatus.Headers.Properties | len}}
{{$data := $valueStatus.Headers}}
{{template "RenderProperties" passThrough $data `location:"headers"` $operation.Name}}
{{end}}
{{end}}
}
{{if $valueStatus.Headers.Properties | len}}
{{$data := $valueStatus.Headers}}
{{template "RenderProperties" passThrough $data `location:"headers"` $operation.Name}}
{{end}}
{{end}}
}
{{end}}
{{define "SubServiceInitParams"}}
{{- $customizedType := index . 0 -}}
{{- $disablePointer := index . 1 -}}
{{- $customizedType := index . 0 -}}
{{- $disablePointer := index . 1 -}}
{{- range $_, $property := $customizedType.Properties -}}
{{$property.ID | camelCase | lowerFirstWord}}{{" " -}}
{{template "PropertyType" passThrough $property $disablePointer}},
{{- end -}}
{{- range $_, $property := $customizedType.Properties -}}
{{$property.ID | camelCase | lowerFirstWord}}{{" " -}}
{{template "PropertyType" passThrough $property $disablePointer}},
{{- end -}}
{{end}}
{{define "ValidateCustomizedType"}}
{{$customizedType := index . 0}}
{{$operationName := index . 1}}
{{$customizedType := index . 0}}
{{$operationName := index . 1}}
{{range $_, $property := $customizedType.Properties}}
{{if or (ne $operationName "Delete Multiple Objects") (ne $property.ID "Content-MD5") -}}
{{$isNormalType := or (eq $property.Type "string") (eq $property.Type "integer")}}
{{$isContentLength := eq $property.ID "Content-Length"}}
{{if and $isNormalType (not $isContentLength) }}
{{if $property.IsRequired }}
if v.{{$property.ID | camelCase}} == nil {
return errors.ParameterRequiredError{
ParameterName: "{{$property.ID | camelCase}}",
ParentName: "{{$customizedType.ID | camelCase}}",
}
}
{{end}}
{{$parameterName := $property.ID | camelCase | lowerFirstWord}}
{{if gt ($property.Enum | len) 0}}
if v.{{$property.ID | camelCase}} != nil {
{{$parameterName}}ValidValues := []string{
{{- $property.Enum | commaConnectedWithQuote -}}
}
{{$parameterName}}ParameterValue := fmt.Sprint(*v.{{$property.ID | camelCase}})
{{range $_, $property := $customizedType.Properties}}
{{if or (ne $operationName "Delete Multiple Objects") (ne $property.ID "Content-MD5") -}}
{{$isNormalType := or (eq $property.Type "string") (eq $property.Type "integer")}}
{{$isContentLength := eq $property.ID "Content-Length"}}
{{if and $isNormalType (not $isContentLength) }}
{{if $property.IsRequired }}
if v.{{$property.ID | camelCase}} == nil {
return errors.ParameterRequiredError{
ParameterName: "{{$property.ID | camelCase}}",
ParentName: "{{$customizedType.ID | camelCase}}",
}
}
{{end}}
{{$parameterName := $property.ID | camelCase | lowerFirstWord}}
{{if gt ($property.Enum | len) 0}}
if v.{{$property.ID | camelCase}} != nil {
{{$parameterName}}ValidValues := []string{
{{- $property.Enum | commaConnectedWithQuote -}}
}
{{$parameterName}}ParameterValue := fmt.Sprint(*v.{{$property.ID | camelCase}})
{{$parameterName}}IsValid := false
for _, value := range {{$parameterName}}ValidValues {
if value == {{$parameterName}}ParameterValue {
{{$parameterName}}IsValid = true
}
}
{{$parameterName}}IsValid := false
for _, value := range {{$parameterName}}ValidValues {
if value == {{$parameterName}}ParameterValue {
{{$parameterName}}IsValid = true
}
}
if !{{$parameterName}}IsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "{{$property.ID | camelCase}}",
ParameterValue: {{$parameterName}}ParameterValue,
AllowedValues: {{$parameterName}}ValidValues,
}
}
}
{{end}}
{{end}}
if !{{$parameterName}}IsValid {
return errors.ParameterValueNotAllowedError{
ParameterName: "{{$property.ID | camelCase}}",
ParameterValue: {{$parameterName}}ParameterValue,
AllowedValues: {{$parameterName}}ValidValues,
}
}
}
{{end}}
{{end}}
{{if eq $property.Type "object"}}
if v.{{$property.ID | camelCase}} != nil {
if err := v.{{$property.ID | camelCase}}.Validate(); err != nil {
return err
}
}
{{if $property.IsRequired }}
if v.{{$property.ID | camelCase}} == nil {
return errors.ParameterRequiredError{
ParameterName: "{{$property.ID | camelCase}}",
ParentName: "{{$customizedType.ID | camelCase}}",
}
}
{{end}}
{{end}}
{{if eq $property.Type "object"}}
if v.{{$property.ID | camelCase}} != nil {
if err := v.{{$property.ID | camelCase}}.Validate(); err != nil {
return err
}
}
{{if $property.IsRequired }}
if v.{{$property.ID | camelCase}} == nil {
return errors.ParameterRequiredError{
ParameterName: "{{$property.ID | camelCase}}",
ParentName: "{{$customizedType.ID | camelCase}}",
}
}
{{end}}
{{end}}
{{if eq $property.Type "array"}}
{{if $property.IsRequired}}
if len(v.{{$property.ID | camelCase}}) == 0 {
return errors.ParameterRequiredError{
ParameterName: "{{$property.ID | camelCase}}",
ParentName: "{{$customizedType.ID | camelCase}}",
}
}
{{end}}
{{$isNotString := ne $property.ExtraType "string"}}
{{$isNotInteger := ne $property.ExtraType "integer"}}
{{$isNotTimestamp := ne $property.ExtraType "timestamp"}}
{{if and $isNotString $isNotInteger $isNotTimestamp}}
if len(v.{{$property.ID | camelCase}}) > 0 {
for _, property := range v.{{$property.ID | camelCase}} {
if err := property.Validate(); err != nil {
return err
}
}
}
{{end}}
{{end}}
{{end}}
{{end}}
{{if eq $property.Type "array"}}
{{if $property.IsRequired}}
if len(v.{{$property.ID | camelCase}}) == 0 {
return errors.ParameterRequiredError{
ParameterName: "{{$property.ID | camelCase}}",
ParentName: "{{$customizedType.ID | camelCase}}",
}
}
{{end}}
{{$isNotString := ne $property.ExtraType "string"}}
{{$isNotInteger := ne $property.ExtraType "integer"}}
{{$isNotTimestamp := ne $property.ExtraType "timestamp"}}
{{if and $isNotString $isNotInteger $isNotTimestamp}}
if len(v.{{$property.ID | camelCase}}) > 0 {
for _, property := range v.{{$property.ID | camelCase}} {
if err := property.Validate(); err != nil {
return err
}
}
}
{{end}}
{{end}}
{{end}}
{{end}}
{{end}}

View file

@ -20,16 +20,16 @@
package service
import (
"fmt"
"io"
"net/http"
"strings"
"time"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/yunify/qingstor-sdk-go/config"
"github.com/yunify/qingstor-sdk-go/request"
"github.com/yunify/qingstor-sdk-go/request/data"
"github.com/yunify/qingstor-sdk-go/request/errors"
"github.com/yunify/qingstor-sdk-go/config"
"github.com/yunify/qingstor-sdk-go/request"
"github.com/yunify/qingstor-sdk-go/request/data"
"github.com/yunify/qingstor-sdk-go/request/errors"
)
var _ fmt.State
@ -40,31 +40,31 @@ var _ time.Time
var _ config.Config
{{if ne $subService.Name "Object"}}
// {{$subService.ID | camelCase}} presents {{$subService.ID | snakeCase}}.
type {{$subService.ID | camelCase}} struct {
Config *config.Config
Properties *Properties
}
// {{$subService.ID | camelCase}} presents {{$subService.ID | snakeCase}}.
type {{$subService.ID | camelCase}} struct {
Config *config.Config
Properties *Properties
}
// {{$subService.ID | camelCase}} initializes a new {{$subService.ID | snakeCase}}.
func (s *Service) {{$subService.ID | camelCase}}(
{{- template "SubServiceInitParams" passThrough $subService.Properties true -}}
) (*{{$subService.ID | camelCase}}, error) {
{{- range $_, $property := $subService.Properties.Properties -}}
{{if eq $property.ID "zone"}}
{{$property.ID}} = strings.ToLower({{$property.ID}})
{{end}}
{{- end -}}
properties := &Properties{
{{range $_, $property := $subService.Properties.Properties -}}
{{$property.ID | upperFirst}}: &{{$property.ID}},
{{end -}}
}
// {{$subService.ID | camelCase}} initializes a new {{$subService.ID | snakeCase}}.
func (s *Service) {{$subService.ID | camelCase}}(
{{- template "SubServiceInitParams" passThrough $subService.Properties true -}}
) (*{{$subService.ID | camelCase}}, error) {
{{- range $_, $property := $subService.Properties.Properties -}}
{{if eq $property.ID "zone"}}
{{$property.ID}} = strings.ToLower({{$property.ID}})
{{end}}
{{- end -}}
properties := &Properties{
{{range $_, $property := $subService.Properties.Properties -}}
{{$property.ID | upperFirst}}: &{{$property.ID}},
{{end -}}
}
return &{{$subService.ID | camelCase}}{Config: s.Config, Properties: properties}, nil
}
return &{{$subService.ID | camelCase}}{Config: s.Config, Properties: properties}, nil
}
{{end}}
{{range $_, $operation := $subService.Operations}}
{{template "RenderOperation" passThrough $subService $operation}}
{{template "RenderOperation" passThrough $subService $operation}}
{{end}}

View file

@ -21,43 +21,43 @@
package service
import (
"fmt"
"time"
"fmt"
"time"
"github.com/yunify/qingstor-sdk-go/request/errors"
"github.com/yunify/qingstor-sdk-go/request/errors"
)
// Properties presents the service properties.
type Properties struct {
{{- template "RenderProperties" passThrough $service.Properties "" "" -}}
{{if $objectSubService -}}
{{range $_, $p := $objectSubService.Properties.Properties -}}
{{- if $p.Description -}}
// {{$p.Description}}
{{end -}}
{{if $p.Enum -}}
// {{camelCase $p.ID}}'s available values: {{commaConnected $p.Enum}}
{{end -}}
{{$p.ID | camelCase | upperFirst}}{{" " -}}
{{template "PropertyType" passThrough $p false}}{{" " -}}
`{{template "PropertyTagsDashConnected" $p}}`{{" " -}}
{{if $p.IsRequired -}}
// Required
{{- end}}
{{end}}
{{end}}
{{- template "RenderProperties" passThrough $service.Properties "" "" -}}
{{if $objectSubService -}}
{{range $_, $p := $objectSubService.Properties.Properties -}}
{{- if $p.Description -}}
// {{$p.Description}}
{{end -}}
{{if $p.Enum -}}
// {{camelCase $p.ID}}'s available values: {{commaConnected $p.Enum}}
{{end -}}
{{$p.ID | camelCase | upperFirst}}{{" " -}}
{{template "PropertyType" passThrough $p false}}{{" " -}}
`{{template "PropertyTagsDashConnected" $p}}`{{" " -}}
{{if $p.IsRequired -}}
// Required
{{- end}}
{{end}}
{{end}}
}
{{range $_, $customizedType := $customizedTypes}}
// {{$customizedType.ID | camelCase}}Type presents {{$customizedType.ID | camelCase}}.
type {{$customizedType.ID | camelCase}}Type struct {
{{template "RenderProperties" passThrough $customizedType "" ""}}
}
// {{$customizedType.ID | camelCase}}Type presents {{$customizedType.ID | camelCase}}.
type {{$customizedType.ID | camelCase}}Type struct {
{{template "RenderProperties" passThrough $customizedType "" ""}}
}
// Validate validates the {{$customizedType.ID | camelCase}}.
func (v *{{$customizedType.ID | camelCase}}Type) Validate() error {
{{template "ValidateCustomizedType" passThrough $customizedType ""}}
// Validate validates the {{$customizedType.ID | camelCase}}.
func (v *{{$customizedType.ID | camelCase}}Type) Validate() error {
{{template "ValidateCustomizedType" passThrough $customizedType ""}}
return nil
}
return nil
}
{{end}}

View file

@ -1,9 +1,9 @@
package main
import (
"errors"
"os"
"os/exec"
"errors"
"github.com/DATA-DOG/godog"
"github.com/yunify/qingstor-sdk-go/client/upload"

View file

@ -20,4 +20,4 @@
package sdk
// Version number.
const Version = "2.2.8"
const Version = "2.2.9"