Skip to content

Commit

Permalink
feat(googleapi): support setting arbitrary query parameters (#1123)
Browse files Browse the repository at this point in the history
Fixes: #550
  • Loading branch information
codyoss committed Aug 9, 2021
1 parent dee7175 commit 8085c66
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
28 changes: 28 additions & 0 deletions googleapi/googleapi.go
Expand Up @@ -391,6 +391,14 @@ type CallOption interface {
Get() (key, value string)
}

// A MultiCallOption is an option argument to an API call and can be passed
// anywhere a CallOption is accepted. It additionally supports returning a slice
// of values for a given key.
type MultiCallOption interface {
CallOption
GetMulti() (key string, value []string)
}

// QuotaUser returns a CallOption that will set the quota user for a call.
// The quota user can be used by server-side applications to control accounting.
// It can be an arbitrary string up to 40 characters, and will override UserIP
Expand All @@ -417,4 +425,24 @@ type traceTok string

func (t traceTok) Get() (string, string) { return "trace", "token:" + string(t) }

type queryParameter struct {
key string
values []string
}

// QueryParameter allows setting the value(s) of an arbitrary key.
func QueryParameter(key string, values ...string) CallOption {
return queryParameter{key: key, values: append([]string{}, values...)}
}

// Get will never actually be called -- GetMulti will.
func (q queryParameter) Get() (string, string) {
return "", ""
}

// GetMulti returns the key and values values associated to that key.
func (q queryParameter) GetMulti() (string, []string) {
return q.key, q.values
}

// TODO: Fields too
8 changes: 7 additions & 1 deletion internal/gensupport/params.go
Expand Up @@ -43,9 +43,15 @@ func (u URLParams) Encode() string {
return url.Values(u).Encode()
}

// SetOptions sets the URL params and any additional call options.
// SetOptions sets the URL params and any additional `CallOption` or
// `MultiCallOption` passed in.
func SetOptions(u URLParams, opts ...googleapi.CallOption) {
for _, o := range opts {
m, ok := o.(googleapi.MultiCallOption)
if ok {
u.SetMulti(m.GetMulti())
continue
}
u.Set(o.Get())
}
}
20 changes: 20 additions & 0 deletions internal/gensupport/params_test.go
@@ -0,0 +1,20 @@
// Copyright 2021 Google LLC. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gensupport

import (
"testing"

"google.golang.org/api/googleapi"
)

func TestSetOptionsGetMulti(t *testing.T) {
co := googleapi.QueryParameter("key", "foo", "bar")
urlParams := make(URLParams)
SetOptions(urlParams, co)
if got, want := urlParams.Encode(), "key=foo&key=bar"; got != want {
t.Fatalf("URLParams.Encode() = %q, want %q", got, want)
}
}

0 comments on commit 8085c66

Please sign in to comment.