1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4 5 package gensupport
6 7 import (
8 "net/http"
9 "net/url"
10 11 "google.golang.org/api/googleapi"
12 "google.golang.org/api/internal"
13 )
14 15 // URLParams is a simplified replacement for url.Values
16 // that safely builds up URL parameters for encoding.
17 type URLParams map[string][]string
18 19 // Get returns the first value for the given key, or "".
20 func (u URLParams) Get(key string) string {
21 vs := u[key]
22 if len(vs) == 0 {
23 return ""
24 }
25 return vs[0]
26 }
27 28 // Set sets the key to value.
29 // It replaces any existing values.
30 func (u URLParams) Set(key, value string) {
31 u[key] = []string{value}
32 }
33 34 // SetMulti sets the key to an array of values.
35 // It replaces any existing values.
36 // Note that values must not be modified after calling SetMulti
37 // so the caller is responsible for making a copy if necessary.
38 func (u URLParams) SetMulti(key string, values []string) {
39 u[key] = values
40 }
41 42 // Encode encodes the values into “URL encoded” form
43 // ("bar=baz&foo=quux") sorted by key.
44 func (u URLParams) Encode() string {
45 return url.Values(u).Encode()
46 }
47 48 // SetOptions sets the URL params and any additional `CallOption` or
49 // `MultiCallOption` passed in.
50 func SetOptions(u URLParams, opts ...googleapi.CallOption) {
51 for _, o := range opts {
52 m, ok := o.(googleapi.MultiCallOption)
53 if ok {
54 u.SetMulti(m.GetMulti())
55 continue
56 }
57 u.Set(o.Get())
58 }
59 }
60 61 // SetHeaders sets common headers for all requests. The keyvals header pairs
62 // should have a corresponding value for every key provided. If there is an odd
63 // number of keyvals this method will panic.
64 func SetHeaders(userAgent, contentType string, userHeaders http.Header, keyvals ...string) http.Header {
65 reqHeaders := make(http.Header)
66 reqHeaders.Set("x-goog-api-client", "gl-go/"+GoVersion()+" gdcl/"+internal.Version)
67 for i := 0; i < len(keyvals); i = i + 2 {
68 reqHeaders.Set(keyvals[i], keyvals[i+1])
69 }
70 reqHeaders.Set("User-Agent", userAgent)
71 if contentType != "" {
72 reqHeaders.Set("Content-Type", contentType)
73 }
74 for k, v := range userHeaders {
75 reqHeaders[k] = v
76 }
77 return reqHeaders
78 }
79