...

Source file src/github.com/alibabacloud-go/tea-utils/service/service.go

Documentation: github.com/alibabacloud-go/tea-utils/service

     1  package service
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io"
     8  	"io/ioutil"
     9  	"net/http"
    10  	"net/url"
    11  	"reflect"
    12  	"runtime"
    13  	"strconv"
    14  	"strings"
    15  	"time"
    16  
    17  	"github.com/alibabacloud-go/tea/tea"
    18  )
    19  
    20  var defaultUserAgent = fmt.Sprintf("AlibabaCloud (%s; %s) Golang/%s Core/%s TeaDSL/1", runtime.GOOS, runtime.GOARCH, strings.Trim(runtime.Version(), "go"), "0.01")
    21  
    22  type RuntimeOptions struct {
    23  	Autoretry      *bool   `json:"autoretry" xml:"autoretry"`
    24  	IgnoreSSL      *bool   `json:"ignoreSSL" xml:"ignoreSSL"`
    25  	MaxAttempts    *int    `json:"maxAttempts" xml:"maxAttempts"`
    26  	BackoffPolicy  *string `json:"backoffPolicy" xml:"backoffPolicy"`
    27  	BackoffPeriod  *int    `json:"backoffPeriod" xml:"backoffPeriod"`
    28  	ReadTimeout    *int    `json:"readTimeout" xml:"readTimeout"`
    29  	ConnectTimeout *int    `json:"connectTimeout" xml:"connectTimeout"`
    30  	LocalAddr      *string `json:"localAddr" xml:"localAddr"`
    31  	HttpProxy      *string `json:"httpProxy" xml:"httpProxy"`
    32  	HttpsProxy     *string `json:"httpsProxy" xml:"httpsProxy"`
    33  	NoProxy        *string `json:"noProxy" xml:"noProxy"`
    34  	MaxIdleConns   *int    `json:"maxIdleConns" xml:"maxIdleConns"`
    35  	Socks5Proxy    *string `json:"socks5Proxy" xml:"socks5Proxy"`
    36  	Socks5NetWork  *string `json:"socks5NetWork" xml:"socks5NetWork"`
    37  	KeepAlive      *bool   `json:"keepAlive" xml:"keepAlive"`
    38  }
    39  
    40  func (s RuntimeOptions) String() string {
    41  	return tea.Prettify(s)
    42  }
    43  
    44  func (s RuntimeOptions) GoString() string {
    45  	return s.String()
    46  }
    47  
    48  func (s *RuntimeOptions) SetAutoretry(v bool) *RuntimeOptions {
    49  	s.Autoretry = &v
    50  	return s
    51  }
    52  
    53  func (s *RuntimeOptions) SetIgnoreSSL(v bool) *RuntimeOptions {
    54  	s.IgnoreSSL = &v
    55  	return s
    56  }
    57  
    58  func (s *RuntimeOptions) SetMaxAttempts(v int) *RuntimeOptions {
    59  	s.MaxAttempts = &v
    60  	return s
    61  }
    62  
    63  func (s *RuntimeOptions) SetBackoffPolicy(v string) *RuntimeOptions {
    64  	s.BackoffPolicy = &v
    65  	return s
    66  }
    67  
    68  func (s *RuntimeOptions) SetBackoffPeriod(v int) *RuntimeOptions {
    69  	s.BackoffPeriod = &v
    70  	return s
    71  }
    72  
    73  func (s *RuntimeOptions) SetReadTimeout(v int) *RuntimeOptions {
    74  	s.ReadTimeout = &v
    75  	return s
    76  }
    77  
    78  func (s *RuntimeOptions) SetConnectTimeout(v int) *RuntimeOptions {
    79  	s.ConnectTimeout = &v
    80  	return s
    81  }
    82  
    83  func (s *RuntimeOptions) SetHttpProxy(v string) *RuntimeOptions {
    84  	s.HttpProxy = &v
    85  	return s
    86  }
    87  
    88  func (s *RuntimeOptions) SetHttpsProxy(v string) *RuntimeOptions {
    89  	s.HttpsProxy = &v
    90  	return s
    91  }
    92  
    93  func (s *RuntimeOptions) SetNoProxy(v string) *RuntimeOptions {
    94  	s.NoProxy = &v
    95  	return s
    96  }
    97  
    98  func (s *RuntimeOptions) SetMaxIdleConns(v int) *RuntimeOptions {
    99  	s.MaxIdleConns = &v
   100  	return s
   101  }
   102  
   103  func (s *RuntimeOptions) SetLocalAddr(v string) *RuntimeOptions {
   104  	s.LocalAddr = &v
   105  	return s
   106  }
   107  
   108  func (s *RuntimeOptions) SetSocks5Proxy(v string) *RuntimeOptions {
   109  	s.Socks5Proxy = &v
   110  	return s
   111  }
   112  
   113  func (s *RuntimeOptions) SetSocks5NetWork(v string) *RuntimeOptions {
   114  	s.Socks5NetWork = &v
   115  	return s
   116  }
   117  
   118  func (s *RuntimeOptions) SetKeepAlive(v bool) *RuntimeOptions {
   119  	s.KeepAlive = &v
   120  	return s
   121  }
   122  
   123  func ReadAsString(body io.Reader) (*string, error) {
   124  	byt, err := ioutil.ReadAll(body)
   125  	if err != nil {
   126  		return tea.String(""), err
   127  	}
   128  	r, ok := body.(io.ReadCloser)
   129  	if ok {
   130  		r.Close()
   131  	}
   132  	return tea.String(string(byt)), nil
   133  }
   134  
   135  func StringifyMapValue(a map[string]interface{}) map[string]*string {
   136  	res := make(map[string]*string)
   137  	for key, value := range a {
   138  		if value != nil {
   139  			switch value.(type) {
   140  			case string:
   141  				res[key] = tea.String(value.(string))
   142  			default:
   143  				byt, _ := json.Marshal(value)
   144  				res[key] = tea.String(string(byt))
   145  			}
   146  		}
   147  	}
   148  	return res
   149  }
   150  
   151  func AnyifyMapValue(a map[string]*string) map[string]interface{} {
   152  	res := make(map[string]interface{})
   153  	for key, value := range a {
   154  		res[key] = tea.StringValue(value)
   155  	}
   156  	return res
   157  }
   158  
   159  func ReadAsBytes(body io.Reader) ([]byte, error) {
   160  	byt, err := ioutil.ReadAll(body)
   161  	if err != nil {
   162  		return nil, err
   163  	}
   164  	r, ok := body.(io.ReadCloser)
   165  	if ok {
   166  		r.Close()
   167  	}
   168  	return byt, nil
   169  }
   170  
   171  func DefaultString(reaStr, defaultStr *string) *string {
   172  	if reaStr == nil {
   173  		return defaultStr
   174  	}
   175  	return reaStr
   176  }
   177  
   178  func ToJSONString(a interface{}) *string {
   179  	switch v := a.(type) {
   180  	case *string:
   181  		return v
   182  	case string:
   183  		return tea.String(v)
   184  	case []byte:
   185  		return tea.String(string(v))
   186  	case io.Reader:
   187  		byt, err := ioutil.ReadAll(v)
   188  		if err != nil {
   189  			return nil
   190  		}
   191  		return tea.String(string(byt))
   192  	}
   193  	byt, err := json.Marshal(a)
   194  	if err != nil {
   195  		return nil
   196  	}
   197  	return tea.String(string(byt))
   198  }
   199  
   200  func DefaultNumber(reaNum, defaultNum *int) *int {
   201  	if reaNum == nil {
   202  		return defaultNum
   203  	}
   204  	return reaNum
   205  }
   206  
   207  func ReadAsJSON(body io.Reader) (result interface{}, err error) {
   208  	byt, err := ioutil.ReadAll(body)
   209  	if err != nil {
   210  		return
   211  	}
   212  	if string(byt) == "" {
   213  		return
   214  	}
   215  	r, ok := body.(io.ReadCloser)
   216  	if ok {
   217  		r.Close()
   218  	}
   219  	d := json.NewDecoder(bytes.NewReader(byt))
   220  	d.UseNumber()
   221  	err = d.Decode(&result)
   222  	return
   223  }
   224  
   225  func GetNonce() *string {
   226  	return tea.String(getUUID())
   227  }
   228  
   229  func Empty(val *string) *bool {
   230  	return tea.Bool(val == nil || tea.StringValue(val) == "")
   231  }
   232  
   233  func ValidateModel(a interface{}) error {
   234  	if a == nil {
   235  		return nil
   236  	}
   237  	err := tea.Validate(a)
   238  	return err
   239  }
   240  
   241  func EqualString(val1, val2 *string) *bool {
   242  	return tea.Bool(tea.StringValue(val1) == tea.StringValue(val2))
   243  }
   244  
   245  func EqualNumber(val1, val2 *int) *bool {
   246  	return tea.Bool(tea.IntValue(val1) == tea.IntValue(val2))
   247  }
   248  
   249  func IsUnset(val interface{}) *bool {
   250  	if val == nil {
   251  		return tea.Bool(true)
   252  	}
   253  
   254  	v := reflect.ValueOf(val)
   255  	if v.Kind() == reflect.Ptr || v.Kind() == reflect.Slice || v.Kind() == reflect.Map {
   256  		return tea.Bool(v.IsNil())
   257  	}
   258  
   259  	valType := reflect.TypeOf(val)
   260  	valZero := reflect.Zero(valType)
   261  	return tea.Bool(valZero == v)
   262  }
   263  
   264  func ToBytes(a *string) []byte {
   265  	return []byte(tea.StringValue(a))
   266  }
   267  
   268  func AssertAsMap(a interface{}) map[string]interface{} {
   269  	r := reflect.ValueOf(a)
   270  	if r.Kind().String() != "map" {
   271  		panic(fmt.Sprintf("%v is not a map[string]interface{}", a))
   272  	}
   273  
   274  	res := make(map[string]interface{})
   275  	tmp := r.MapKeys()
   276  	for _, key := range tmp {
   277  		res[key.String()] = r.MapIndex(key).Interface()
   278  	}
   279  
   280  	return res
   281  }
   282  
   283  func AssertAsNumber(a interface{}) *int {
   284  	res := 0
   285  	switch a.(type) {
   286  	case int:
   287  		tmp := a.(int)
   288  		res = tmp
   289  	case *int:
   290  		tmp := a.(*int)
   291  		res = tea.IntValue(tmp)
   292  	default:
   293  		panic(fmt.Sprintf("%v is not a int", a))
   294  	}
   295  
   296  	return tea.Int(res)
   297  }
   298  
   299  func AssertAsBoolean(a interface{}) *bool {
   300  	res := false
   301  	switch a.(type) {
   302  	case bool:
   303  		tmp := a.(bool)
   304  		res = tmp
   305  	case *bool:
   306  		tmp := a.(*bool)
   307  		res = tea.BoolValue(tmp)
   308  	default:
   309  		panic(fmt.Sprintf("%v is not a bool", a))
   310  	}
   311  
   312  	return tea.Bool(res)
   313  }
   314  
   315  func AssertAsString(a interface{}) *string {
   316  	res := ""
   317  	switch a.(type) {
   318  	case string:
   319  		tmp := a.(string)
   320  		res = tmp
   321  	case *string:
   322  		tmp := a.(*string)
   323  		res = tea.StringValue(tmp)
   324  	default:
   325  		panic(fmt.Sprintf("%v is not a string", a))
   326  	}
   327  
   328  	return tea.String(res)
   329  }
   330  
   331  func AssertAsBytes(a interface{}) []byte {
   332  	res, ok := a.([]byte)
   333  	if !ok {
   334  		panic(fmt.Sprintf("%v is not []byte", a))
   335  	}
   336  	return res
   337  }
   338  
   339  func AssertAsReadable(a interface{}) io.Reader {
   340  	res, ok := a.(io.Reader)
   341  	if !ok {
   342  		panic(fmt.Sprintf("%v is not reader", a))
   343  	}
   344  	return res
   345  }
   346  
   347  func AssertAsArray(a interface{}) []interface{} {
   348  	r := reflect.ValueOf(a)
   349  	if r.Kind().String() != "array" && r.Kind().String() != "slice" {
   350  		panic(fmt.Sprintf("%v is not a [x]interface{}", a))
   351  	}
   352  	aLen := r.Len()
   353  	res := make([]interface{}, 0)
   354  	for i := 0; i < aLen; i++ {
   355  		res = append(res, r.Index(i).Interface())
   356  	}
   357  	return res
   358  }
   359  
   360  func ParseJSON(a *string) interface{} {
   361  	mapTmp := make(map[string]interface{})
   362  	d := json.NewDecoder(bytes.NewReader([]byte(tea.StringValue(a))))
   363  	d.UseNumber()
   364  	err := d.Decode(&mapTmp)
   365  	if err == nil {
   366  		return mapTmp
   367  	}
   368  
   369  	sliceTmp := make([]interface{}, 0)
   370  	d = json.NewDecoder(bytes.NewReader([]byte(tea.StringValue(a))))
   371  	d.UseNumber()
   372  	err = d.Decode(&sliceTmp)
   373  	if err == nil {
   374  		return sliceTmp
   375  	}
   376  
   377  	if num, err := strconv.Atoi(tea.StringValue(a)); err == nil {
   378  		return num
   379  	}
   380  
   381  	if ok, err := strconv.ParseBool(tea.StringValue(a)); err == nil {
   382  		return ok
   383  	}
   384  
   385  	if floa64tVal, err := strconv.ParseFloat(tea.StringValue(a), 64); err == nil {
   386  		return floa64tVal
   387  	}
   388  	return nil
   389  }
   390  
   391  func ToString(a []byte) *string {
   392  	return tea.String(string(a))
   393  }
   394  
   395  func ToMap(in interface{}) map[string]interface{} {
   396  	if in == nil {
   397  		return nil
   398  	}
   399  	res := tea.ToMap(in)
   400  	return res
   401  }
   402  
   403  func ToFormString(a map[string]interface{}) *string {
   404  	if a == nil {
   405  		return tea.String("")
   406  	}
   407  	res := ""
   408  	urlEncoder := url.Values{}
   409  	for key, value := range a {
   410  		v := fmt.Sprintf("%v", value)
   411  		urlEncoder.Add(key, v)
   412  	}
   413  	res = urlEncoder.Encode()
   414  	return tea.String(res)
   415  }
   416  
   417  func GetDateUTCString() *string {
   418  	return tea.String(time.Now().UTC().Format(http.TimeFormat))
   419  }
   420  
   421  func GetUserAgent(userAgent *string) *string {
   422  	if userAgent != nil && tea.StringValue(userAgent) != "" {
   423  		return tea.String(defaultUserAgent + " " + tea.StringValue(userAgent))
   424  	}
   425  	return tea.String(defaultUserAgent)
   426  }
   427  
   428  func Is2xx(code *int) *bool {
   429  	tmp := tea.IntValue(code)
   430  	return tea.Bool(tmp >= 200 && tmp < 300)
   431  }
   432  
   433  func Is3xx(code *int) *bool {
   434  	tmp := tea.IntValue(code)
   435  	return tea.Bool(tmp >= 300 && tmp < 400)
   436  }
   437  
   438  func Is4xx(code *int) *bool {
   439  	tmp := tea.IntValue(code)
   440  	return tea.Bool(tmp >= 400 && tmp < 500)
   441  }
   442  
   443  func Is5xx(code *int) *bool {
   444  	tmp := tea.IntValue(code)
   445  	return tea.Bool(tmp >= 500 && tmp < 600)
   446  }
   447  
   448  func Sleep(millisecond *int) error {
   449  	ms := tea.IntValue(millisecond)
   450  	time.Sleep(time.Duration(ms) * time.Millisecond)
   451  	return nil
   452  }
   453  
   454  func ToArray(in interface{}) []map[string]interface{} {
   455  	if tea.BoolValue(IsUnset(in)) {
   456  		return nil
   457  	}
   458  
   459  	tmp := make([]map[string]interface{}, 0)
   460  	byt, _ := json.Marshal(in)
   461  	d := json.NewDecoder(bytes.NewReader(byt))
   462  	d.UseNumber()
   463  	err := d.Decode(&tmp)
   464  	if err != nil {
   465  		return nil
   466  	}
   467  	return tmp
   468  }
   469  

View as plain text