本文整理汇总了Golang中net/url.Values类的典型用法代码示例。如果您正苦于以下问题:Golang Values类的具体用法?Golang Values怎么用?Golang Values使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Values类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: GetFollowersListAll
// Like GetFollowersList, but returns a channel instead of a cursor and pre-fetches the remaining results
// This channel is closed once all values have been fetched
func (a TwitterApi) GetFollowersListAll(v url.Values) (result chan FollowersPage) {
result = make(chan FollowersPage)
if v == nil {
v = url.Values{}
}
go func(a TwitterApi, v url.Values, result chan FollowersPage) {
// Cursor defaults to the first page ("-1")
next_cursor := "-1"
for {
v.Set("cursor", next_cursor)
c, err := a.GetFollowersList(v)
// throttledQuery() handles all rate-limiting errors
// if GetFollowersList() returns an error, it must be a different kind of error
result <- FollowersPage{c.Users, err}
next_cursor = c.Next_cursor_str
if next_cursor == "0" {
close(result)
break
}
}
}(a, v, result)
return result
}
示例2: Values
func (plan *Plan) Values(values *url.Values) error {
if plan == nil {
// TODO: Throw error
}
if plan.ID == "" {
// TODO: Throw error
}
if plan.Name == "" {
// TODO: Throw error
}
if plan.Amount <= 0 {
// TODO: Throw error
}
if plan.Currency != "USD" {
// TODO: Throw error
}
if plan.Interval != "month" && plan.Interval != "year" {
// TODO: Throw error
}
if plan.TrialDays > 0 {
values.Set("trial_period_days", strconv.Itoa(plan.TrialDays))
}
values.Set("id", plan.ID)
values.Set("amount", strconv.Itoa(plan.Amount))
values.Set("currency", plan.Currency)
values.Set("interval", plan.Interval)
values.Set("name", plan.Name)
return nil
}
示例3: getUpdates
func getUpdates(token string, offset int, timeout int) (updates []Update, err error) {
params := url.Values{}
params.Set("offset", strconv.Itoa(offset))
params.Set("timeout", strconv.Itoa(timeout))
updatesJSON, err := sendCommand("getUpdates", token, params)
if err != nil {
return
}
var updatesRecieved struct {
Ok bool
Result []Update
Description string
}
err = json.Unmarshal(updatesJSON, &updatesRecieved)
if err != nil {
return
}
if !updatesRecieved.Ok {
err = FetchError{updatesRecieved.Description}
return
}
updates = updatesRecieved.Result
return
}
示例4: GetAccessToken
// Issue a request to exchange the current request token for an access token.
func (c *UserConfig) GetAccessToken(token string, verifier string, service *Service, client *http.Client) error {
// This code used to error out if RequestTokenKey were empty, but
// in the interest of being able to operate in a stateless manner this
// has been removed. If you want to make sure that the request token
// is validated against what is being returned, populate the UserConfig
// with a request token stored server-side somewhere, accessed by the
// user's session.
if c.RequestTokenKey != "" && c.RequestTokenKey != token {
return fmt.Errorf("Returned token did not match request token")
}
c.Verifier = verifier
data := url.Values{}
if service.ClientConfig.CallbackURL != "" {
data.Set("oauth_verifier", verifier)
}
body := strings.NewReader(data.Encode())
request, err := http.NewRequest("POST", service.AccessURL, body)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, err := c.send(request, service, client)
if err != nil {
return err
}
err = c.parseAccessToken(response)
return err
}
示例5: GetPodInfo
func (cli *HyperClient) GetPodInfo(podName string) (string, error) {
// get the pod or container info before we start the exec
v := url.Values{}
v.Set("podName", podName)
body, _, err := readBody(cli.call("GET", "/pod/info?"+v.Encode(), nil, nil))
if err != nil {
fmt.Printf("Error: %s\n", err)
return "", err
}
out := engine.NewOutput()
remoteInfo, err := out.AddEnv()
if err != nil {
return "", err
}
if _, err := out.Write(body); err != nil {
fmt.Printf("Error reading remote info: %s", err)
return "", err
}
out.Close()
if remoteInfo.Exists("hostname") {
hostname := remoteInfo.Get("hostname")
if hostname == "" {
return "", nil
} else {
return hostname, nil
}
}
return "", nil
}
示例6: copyValues
func copyValues(dst, src url.Values) {
for k, vs := range src {
for _, value := range vs {
dst.Add(k, value)
}
}
}
示例7: CreateContainer
func (client *DockerClient) CreateContainer(config *ContainerConfig, name string, auth *AuthConfig) (string, error) {
data, err := json.Marshal(config)
if err != nil {
return "", err
}
uri := fmt.Sprintf("/%s/containers/create", APIVersion)
if name != "" {
v := url.Values{}
v.Set("name", name)
uri = fmt.Sprintf("%s?%s", uri, v.Encode())
}
headers := map[string]string{}
if auth != nil {
encoded_auth, err := auth.encode()
if err != nil {
return "", err
}
headers["X-Registry-Auth"] = encoded_auth
}
data, err = client.doRequest("POST", uri, data, headers)
if err != nil {
return "", err
}
result := &RespContainersCreate{}
err = json.Unmarshal(data, result)
if err != nil {
return "", fmt.Errorf(string(data))
}
return result.Id, nil
}
示例8: List
func (c Client) List(params *stripe.RecipientListParams) *Iter {
type recipientList struct {
stripe.ListMeta
Values []*stripe.Recipient `json:"data"`
}
var body *url.Values
var lp *stripe.ListParams
var p *stripe.Params
if params != nil {
body = &url.Values{}
if params.Verified {
body.Add("verified", strconv.FormatBool(true))
}
params.AppendTo(body)
lp = ¶ms.ListParams
p = params.ToParams()
}
return &Iter{stripe.GetIter(lp, body, func(b url.Values) ([]interface{}, stripe.ListMeta, error) {
list := &recipientList{}
err := c.B.Call("GET", "/recipients", c.Key, &b, p, list)
ret := make([]interface{}, len(list.Values))
for i, v := range list.Values {
ret[i] = v
}
return ret, list.ListMeta, err
})}
}
示例9: Login
func (h *ZJUJudger) Login(_ UserInterface) error {
h.client.Get("http://acm.zju.edu.cn/onlinejudge/login.do")
uv := url.Values{}
uv.Add("handle", h.username)
uv.Add("password", h.userpass)
req, err := http.NewRequest("POST", "http://acm.zju.edu.cn/onlinejudge/login.do", strings.NewReader(uv.Encode()))
if err != nil {
return BadInternet
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := h.client.Do(req)
if err != nil {
log.Println("err", err)
return BadInternet
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
html := string(b)
if strings.Index(html, "Handle or password is invalid.") >= 0 ||
strings.Index(html, "Handle is required.") >= 0 ||
strings.Index(html, "Password is required.") >= 0 {
return LoginFailed
}
return nil
}
示例10: List
// List the repositories for a user. Passing the empty string will list
// repositories for the authenticated user.
//
// GitHub API docs: http://developer.github.com/v3/repos/#list-user-repositories
func (s *RepositoriesService) List(user string, opt *RepositoryListOptions) ([]Repository, *Response, error) {
var u string
if user != "" {
u = fmt.Sprintf("users/%v/repos", user)
} else {
u = "user/repos"
}
if opt != nil {
params := url.Values{
"type": []string{opt.Type},
"sort": []string{opt.Sort},
"direction": []string{opt.Direction},
"page": []string{strconv.Itoa(opt.Page)},
}
u += "?" + params.Encode()
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
repos := new([]Repository)
resp, err := s.client.Do(req, repos)
return *repos, resp, err
}
示例11: GetBookmarkCounts
// GetBookmarkCounts call hatena bookmark count api.
func GetBookmarkCounts(urls []string) (map[string]int, error) {
query := neturl.Values{}
for _, url := range urls {
u, err := neturl.Parse(url)
if err != nil {
return map[string]int{}, err
}
query.Add("url", u.String())
}
req, _ := neturl.Parse(EntryCountsAPIURL)
req.RawQuery = query.Encode()
res, err := http.Get(req.String())
if err != nil {
return map[string]int{}, err
}
body, _ := ioutil.ReadAll(res.Body)
defer res.Body.Close()
counts := map[string]int{}
json.Unmarshal(body, &counts)
return counts, nil
}
示例12: updateToken
func (t *Transport) updateToken(tok *Token, v url.Values) error {
v.Set("client_id", t.ClientId)
v.Set("client_secret", t.ClientSecret)
r, err := (&http.Client{Transport: t.transport()}).PostForm(t.TokenURL, v)
if err != nil {
return err
}
defer r.Body.Close()
if r.StatusCode != 200 {
return OAuthError{"updateToken", r.Status}
}
var b struct {
Access string `json:"access_token"`
Refresh string `json:"refresh_token"`
ExpiresIn time.Duration `json:"expires_in"`
Id string `json:"id_token"`
}
content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
switch content {
case "application/x-www-form-urlencoded", "text/plain":
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
vals, err := url.ParseQuery(string(body))
if err != nil {
return err
}
b.Access = vals.Get("access_token")
b.Refresh = vals.Get("refresh_token")
b.ExpiresIn, _ = time.ParseDuration(vals.Get("expires_in") + "s")
b.Id = vals.Get("id_token")
default:
if err = json.NewDecoder(r.Body).Decode(&b); err != nil {
return err
}
// The JSON parser treats the unitless ExpiresIn like 'ns' instead of 's' as above,
// so compensate here.
b.ExpiresIn *= time.Second
}
tok.AccessToken = b.Access
// Don't overwrite `RefreshToken` with an empty value
if len(b.Refresh) > 0 {
tok.RefreshToken = b.Refresh
}
if b.ExpiresIn == 0 {
tok.Expiry = time.Time{}
} else {
tok.Expiry = time.Now().Add(b.ExpiresIn)
}
if b.Id != "" {
if tok.Extra == nil {
tok.Extra = make(map[string]string)
}
tok.Extra["id_token"] = b.Id
}
return nil
}
示例13: CmdPush
func (cli *DockerCli) CmdPush(args ...string) error {
cmd := Subcmd("push", "[OPTION] NAME", "Push an image or a repository to the registry")
registry := cmd.String("registry", "", "Registry host to push the image to")
if err := cmd.Parse(args); err != nil {
return nil
}
name := cmd.Arg(0)
if name == "" {
cmd.Usage()
return nil
}
username, err := cli.checkIfLogged(*registry == "", "push")
if err != nil {
return err
}
if len(strings.SplitN(name, "/", 2)) == 1 {
return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
}
v := url.Values{}
v.Set("registry", *registry)
if err := cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, os.Stdout); err != nil {
return err
}
return nil
}
示例14: CmdSearch
func (cli *DockerCli) CmdSearch(args ...string) error {
cmd := Subcmd("search", "NAME", "Search the docker index for images")
if err := cmd.Parse(args); err != nil {
return nil
}
if cmd.NArg() != 1 {
cmd.Usage()
return nil
}
v := url.Values{}
v.Set("term", cmd.Arg(0))
body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
if err != nil {
return err
}
outs := []ApiSearch{}
err = json.Unmarshal(body, &outs)
if err != nil {
return err
}
fmt.Printf("Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
for _, out := range outs {
fmt.Fprintf(w, "%s\t%s\n", out.Name, out.Description)
}
w.Flush()
return nil
}
示例15: streamLocation
func streamLocation(getter ResourceGetter, connInfo client.ConnectionInfoGetter, ctx api.Context, name string, opts runtime.Object, container, path string) (*url.URL, http.RoundTripper, error) {
pod, err := getPod(getter, ctx, name)
if err != nil {
return nil, nil, err
}
// Try to figure out a container
if container == "" {
if len(pod.Spec.Containers) == 1 {
container = pod.Spec.Containers[0].Name
} else {
return nil, nil, errors.NewBadRequest(fmt.Sprintf("a container name must be specified for pod %s", name))
}
}
nodeHost := pod.Spec.NodeName
if len(nodeHost) == 0 {
// If pod has not been assigned a host, return an empty location
return nil, nil, errors.NewBadRequest(fmt.Sprintf("pod %s does not have a host assigned", name))
}
nodeScheme, nodePort, nodeTransport, err := connInfo.GetConnectionInfo(nodeHost)
if err != nil {
return nil, nil, err
}
params := url.Values{}
if err := streamParams(params, opts); err != nil {
return nil, nil, err
}
loc := &url.URL{
Scheme: nodeScheme,
Host: fmt.Sprintf("%s:%d", nodeHost, nodePort),
Path: fmt.Sprintf("/%s/%s/%s/%s", path, pod.Namespace, name, container),
RawQuery: params.Encode(),
}
return loc, nodeTransport, nil
}