utility.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package autorest
  2. // Copyright 2017 Microsoft Corporation
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "encoding/xml"
  19. "fmt"
  20. "io"
  21. "net"
  22. "net/http"
  23. "net/url"
  24. "reflect"
  25. "strings"
  26. "github.com/Azure/go-autorest/autorest/adal"
  27. )
  28. // EncodedAs is a series of constants specifying various data encodings
  29. type EncodedAs string
  30. const (
  31. // EncodedAsJSON states that data is encoded as JSON
  32. EncodedAsJSON EncodedAs = "JSON"
  33. // EncodedAsXML states that data is encoded as Xml
  34. EncodedAsXML EncodedAs = "XML"
  35. )
  36. // Decoder defines the decoding method json.Decoder and xml.Decoder share
  37. type Decoder interface {
  38. Decode(v interface{}) error
  39. }
  40. // NewDecoder creates a new decoder appropriate to the passed encoding.
  41. // encodedAs specifies the type of encoding and r supplies the io.Reader containing the
  42. // encoded data.
  43. func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder {
  44. if encodedAs == EncodedAsJSON {
  45. return json.NewDecoder(r)
  46. } else if encodedAs == EncodedAsXML {
  47. return xml.NewDecoder(r)
  48. }
  49. return nil
  50. }
  51. // CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy
  52. // is especially useful if there is a chance the data will fail to decode.
  53. // encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v
  54. // is the decoding destination.
  55. func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) {
  56. b := bytes.Buffer{}
  57. return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v)
  58. }
  59. // TeeReadCloser returns a ReadCloser that writes to w what it reads from rc.
  60. // It utilizes io.TeeReader to copy the data read and has the same behavior when reading.
  61. // Further, when it is closed, it ensures that rc is closed as well.
  62. func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser {
  63. return &teeReadCloser{rc, io.TeeReader(rc, w)}
  64. }
  65. type teeReadCloser struct {
  66. rc io.ReadCloser
  67. r io.Reader
  68. }
  69. func (t *teeReadCloser) Read(p []byte) (int, error) {
  70. return t.r.Read(p)
  71. }
  72. func (t *teeReadCloser) Close() error {
  73. return t.rc.Close()
  74. }
  75. func containsInt(ints []int, n int) bool {
  76. for _, i := range ints {
  77. if i == n {
  78. return true
  79. }
  80. }
  81. return false
  82. }
  83. func escapeValueStrings(m map[string]string) map[string]string {
  84. for key, value := range m {
  85. m[key] = url.QueryEscape(value)
  86. }
  87. return m
  88. }
  89. func ensureValueStrings(mapOfInterface map[string]interface{}) map[string]string {
  90. mapOfStrings := make(map[string]string)
  91. for key, value := range mapOfInterface {
  92. mapOfStrings[key] = ensureValueString(value)
  93. }
  94. return mapOfStrings
  95. }
  96. func ensureValueString(value interface{}) string {
  97. if value == nil {
  98. return ""
  99. }
  100. switch v := value.(type) {
  101. case string:
  102. return v
  103. case []byte:
  104. return string(v)
  105. default:
  106. return fmt.Sprintf("%v", v)
  107. }
  108. }
  109. // MapToValues method converts map[string]interface{} to url.Values.
  110. func MapToValues(m map[string]interface{}) url.Values {
  111. v := url.Values{}
  112. for key, value := range m {
  113. x := reflect.ValueOf(value)
  114. if x.Kind() == reflect.Array || x.Kind() == reflect.Slice {
  115. for i := 0; i < x.Len(); i++ {
  116. v.Add(key, ensureValueString(x.Index(i)))
  117. }
  118. } else {
  119. v.Add(key, ensureValueString(value))
  120. }
  121. }
  122. return v
  123. }
  124. // AsStringSlice method converts interface{} to []string. This expects a
  125. //that the parameter passed to be a slice or array of a type that has the underlying
  126. //type a string.
  127. func AsStringSlice(s interface{}) ([]string, error) {
  128. v := reflect.ValueOf(s)
  129. if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
  130. return nil, NewError("autorest", "AsStringSlice", "the value's type is not an array.")
  131. }
  132. stringSlice := make([]string, 0, v.Len())
  133. for i := 0; i < v.Len(); i++ {
  134. stringSlice = append(stringSlice, v.Index(i).String())
  135. }
  136. return stringSlice, nil
  137. }
  138. // String method converts interface v to string. If interface is a list, it
  139. // joins list elements using the seperator. Note that only sep[0] will be used for
  140. // joining if any separator is specified.
  141. func String(v interface{}, sep ...string) string {
  142. if len(sep) == 0 {
  143. return ensureValueString(v)
  144. }
  145. stringSlice, ok := v.([]string)
  146. if ok == false {
  147. var err error
  148. stringSlice, err = AsStringSlice(v)
  149. if err != nil {
  150. panic(fmt.Sprintf("autorest: Couldn't convert value to a string %s.", err))
  151. }
  152. }
  153. return ensureValueString(strings.Join(stringSlice, sep[0]))
  154. }
  155. // Encode method encodes url path and query parameters.
  156. func Encode(location string, v interface{}, sep ...string) string {
  157. s := String(v, sep...)
  158. switch strings.ToLower(location) {
  159. case "path":
  160. return pathEscape(s)
  161. case "query":
  162. return queryEscape(s)
  163. default:
  164. return s
  165. }
  166. }
  167. func pathEscape(s string) string {
  168. return strings.Replace(url.QueryEscape(s), "+", "%20", -1)
  169. }
  170. func queryEscape(s string) string {
  171. return url.QueryEscape(s)
  172. }
  173. // ChangeToGet turns the specified http.Request into a GET (it assumes it wasn't).
  174. // This is mainly useful for long-running operations that use the Azure-AsyncOperation
  175. // header, so we change the initial PUT into a GET to retrieve the final result.
  176. func ChangeToGet(req *http.Request) *http.Request {
  177. req.Method = "GET"
  178. req.Body = nil
  179. req.ContentLength = 0
  180. req.Header.Del("Content-Length")
  181. return req
  182. }
  183. // IsTokenRefreshError returns true if the specified error implements the TokenRefreshError
  184. // interface. If err is a DetailedError it will walk the chain of Original errors.
  185. func IsTokenRefreshError(err error) bool {
  186. if _, ok := err.(adal.TokenRefreshError); ok {
  187. return true
  188. }
  189. if de, ok := err.(DetailedError); ok {
  190. return IsTokenRefreshError(de.Original)
  191. }
  192. return false
  193. }
  194. // IsTemporaryNetworkError returns true if the specified error is a temporary network error or false
  195. // if it's not. If the error doesn't implement the net.Error interface the return value is true.
  196. func IsTemporaryNetworkError(err error) bool {
  197. if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) {
  198. return true
  199. }
  200. return false
  201. }