3 // Copyright 2017 Microsoft Corporation
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
29 "github.com/Azure/go-autorest/autorest/adal"
32 // EncodedAs is a series of constants specifying various data encodings
36 // EncodedAsJSON states that data is encoded as JSON
37 EncodedAsJSON EncodedAs = "JSON"
39 // EncodedAsXML states that data is encoded as Xml
40 EncodedAsXML EncodedAs = "XML"
43 // Decoder defines the decoding method json.Decoder and xml.Decoder share
44 type Decoder interface {
45 Decode(v interface{}) error
48 // NewDecoder creates a new decoder appropriate to the passed encoding.
49 // encodedAs specifies the type of encoding and r supplies the io.Reader containing the
51 func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder {
52 if encodedAs == EncodedAsJSON {
53 return json.NewDecoder(r)
54 } else if encodedAs == EncodedAsXML {
55 return xml.NewDecoder(r)
60 // CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy
61 // is especially useful if there is a chance the data will fail to decode.
62 // encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v
63 // is the decoding destination.
64 func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) {
66 return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v)
69 // TeeReadCloser returns a ReadCloser that writes to w what it reads from rc.
70 // It utilizes io.TeeReader to copy the data read and has the same behavior when reading.
71 // Further, when it is closed, it ensures that rc is closed as well.
72 func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser {
73 return &teeReadCloser{rc, io.TeeReader(rc, w)}
76 type teeReadCloser struct {
81 func (t *teeReadCloser) Read(p []byte) (int, error) {
85 func (t *teeReadCloser) Close() error {
89 func containsInt(ints []int, n int) bool {
90 for _, i := range ints {
98 func escapeValueStrings(m map[string]string) map[string]string {
99 for key, value := range m {
100 m[key] = url.QueryEscape(value)
105 func ensureValueStrings(mapOfInterface map[string]interface{}) map[string]string {
106 mapOfStrings := make(map[string]string)
107 for key, value := range mapOfInterface {
108 mapOfStrings[key] = ensureValueString(value)
113 func ensureValueString(value interface{}) string {
117 switch v := value.(type) {
123 return fmt.Sprintf("%v", v)
127 // MapToValues method converts map[string]interface{} to url.Values.
128 func MapToValues(m map[string]interface{}) url.Values {
130 for key, value := range m {
131 x := reflect.ValueOf(value)
132 if x.Kind() == reflect.Array || x.Kind() == reflect.Slice {
133 for i := 0; i < x.Len(); i++ {
134 v.Add(key, ensureValueString(x.Index(i)))
137 v.Add(key, ensureValueString(value))
143 // AsStringSlice method converts interface{} to []string. This expects a
144 //that the parameter passed to be a slice or array of a type that has the underlying
146 func AsStringSlice(s interface{}) ([]string, error) {
147 v := reflect.ValueOf(s)
148 if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
149 return nil, NewError("autorest", "AsStringSlice", "the value's type is not an array.")
151 stringSlice := make([]string, 0, v.Len())
153 for i := 0; i < v.Len(); i++ {
154 stringSlice = append(stringSlice, v.Index(i).String())
156 return stringSlice, nil
159 // String method converts interface v to string. If interface is a list, it
160 // joins list elements using the separator. Note that only sep[0] will be used for
161 // joining if any separator is specified.
162 func String(v interface{}, sep ...string) string {
164 return ensureValueString(v)
166 stringSlice, ok := v.([]string)
169 stringSlice, err = AsStringSlice(v)
171 panic(fmt.Sprintf("autorest: Couldn't convert value to a string %s.", err))
174 return ensureValueString(strings.Join(stringSlice, sep[0]))
177 // Encode method encodes url path and query parameters.
178 func Encode(location string, v interface{}, sep ...string) string {
179 s := String(v, sep...)
180 switch strings.ToLower(location) {
184 return queryEscape(s)
190 func pathEscape(s string) string {
191 return strings.Replace(url.QueryEscape(s), "+", "%20", -1)
194 func queryEscape(s string) string {
195 return url.QueryEscape(s)
198 // ChangeToGet turns the specified http.Request into a GET (it assumes it wasn't).
199 // This is mainly useful for long-running operations that use the Azure-AsyncOperation
200 // header, so we change the initial PUT into a GET to retrieve the final result.
201 func ChangeToGet(req *http.Request) *http.Request {
204 req.ContentLength = 0
205 req.Header.Del("Content-Length")
209 // IsTokenRefreshError returns true if the specified error implements the TokenRefreshError
210 // interface. If err is a DetailedError it will walk the chain of Original errors.
211 func IsTokenRefreshError(err error) bool {
212 if _, ok := err.(adal.TokenRefreshError); ok {
215 if de, ok := err.(DetailedError); ok {
216 return IsTokenRefreshError(de.Original)
221 // IsTemporaryNetworkError returns true if the specified error is a temporary network error or false
222 // if it's not. If the error doesn't implement the net.Error interface the return value is true.
223 func IsTemporaryNetworkError(err error) bool {
224 if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) {