示例#1
1
// 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
1
文件: plan.go 项目: secondbit/stripe
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
1
文件: api.go 项目: nattsw/jarvisbot
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
1
文件: exec.go 项目: sulochan/hyper
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
}
示例#5
1
// 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
}
示例#6
0
文件: s3.go 项目: nullren/kebab
func (b *Bucket) List(prefix, delimiter string) (*ListBucketResult, error) {
	vals := url.Values{}
	vals.Set("prefix", prefix)
	if delimiter != "" {
		vals.Set("delimiter", delimiter)
	}
	req, err := http.NewRequest("GET", b.URL("", vals).String(), nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("x-amz-content-sha256", fmt.Sprintf("%x", sha256.Sum256(nil)))
	b.Service.sign(req)

	resp, err := b.Service.do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("unexpected http status code: %d", resp.StatusCode)
	}

	list := new(ListBucketResult)
	err = xml.NewDecoder(resp.Body).Decode(list)
	if err != nil {
		return nil, fmt.Errorf("unable to decode response body: %s", err)
	}

	return list, nil
}
示例#7
0
文件: gui_test.go 项目: bac/juju
func (s *guiArchiveSuite) TestGUIArchivePostCurrent(c *gc.C) {
	// Add an existing GUI archive and set it as the current one.
	storage, err := s.State.GUIStorage()
	c.Assert(err, jc.ErrorIsNil)
	defer storage.Close()
	vers := version.MustParse("2.0.47")
	setupGUIArchive(c, storage, vers.String(), nil)
	err = s.State.GUISetVersion(vers)
	c.Assert(err, jc.ErrorIsNil)

	// Create a GUI archive to be uploaded.
	r, hash, _ := makeGUIArchive(c, vers.String(), map[string]string{"filename": "content"})

	// Prepare and send the request to upload a new GUI archive.
	v := url.Values{}
	v.Set("version", vers.String())
	v.Set("hash", hash)
	resp := s.authRequest(c, httpRequestParams{
		method:      "POST",
		url:         s.guiURL(c) + "?" + v.Encode(),
		contentType: apiserver.BZMimeType,
		body:        r,
	})

	// Check that the response reflects a successful upload.
	body := assertResponse(c, resp, http.StatusOK, params.ContentTypeJSON)
	var jsonResponse params.GUIArchiveVersion
	err = json.Unmarshal(body, &jsonResponse)
	c.Assert(err, jc.ErrorIsNil, gc.Commentf("body: %s", body))
	c.Assert(jsonResponse, jc.DeepEquals, params.GUIArchiveVersion{
		Version: vers,
		SHA256:  hash,
		Current: true,
	})
}
示例#8
0
// Send sends an SMS
func Send(recipient string, message string) error {

	endpoint := fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json", user)
	data := url.Values{}
	data.Set("From", from)
	data.Set("To", recipient)
	data.Set("Body", message)
	body := data.Encode()

	fmt.Printf("SENDING SMS:%s BODY:%s\n", endpoint, body)

	request, err := http.NewRequest("POST", endpoint, strings.NewReader(body))
	if err != nil {
		return err
	}
	request.SetBasicAuth(user, secret)
	request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return err
	}

	if response.StatusCode != http.StatusCreated {
		fmt.Sprintf("Error sending SMS:%v\n", response)
		return fmt.Errorf("SMS send failed with status:%d", response.StatusCode)
	}

	return nil

}
示例#9
0
文件: commands.go 项目: jweede/docker
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
}
示例#10
0
// buildURL builds the URL for the operation.
func (s *IndicesExistsTypeService) buildURL() (string, url.Values, error) {
	// Build URL
	path, err := uritemplates.Expand("/{index}/{type}", map[string]string{
		"index": strings.Join(s.index, ","),
		"type":  strings.Join(s.typ, ","),
	})
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if s.pretty {
		params.Set("pretty", "1")
	}
	if s.ignoreUnavailable != nil {
		params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
	}
	if s.allowNoIndices != nil {
		params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
	}
	if s.expandWildcards != "" {
		params.Set("expand_wildcards", s.expandWildcards)
	}
	if s.local != nil {
		params.Set("local", fmt.Sprintf("%v", *s.local))
	}
	return path, params, nil
}
示例#11
0
func (k *Kraken) SendAuthenticatedHTTPRequest(method string, values url.Values) (interface{}, error) {
	path := fmt.Sprintf("/%s/private/%s", KRAKEN_API_VERSION, method)
	values.Set("nonce", strconv.FormatInt(time.Now().UnixNano(), 10))
	secret, err := Base64Decode(k.APISecret)

	if err != nil {
		return nil, err
	}

	shasum := GetSHA256([]byte(values.Get("nonce") + values.Encode()))
	signature := Base64Encode(GetHMAC(HASH_SHA512, append([]byte(path), shasum...), secret))

	if k.Verbose {
		log.Printf("Sending POST request to %s, path: %s.", KRAKEN_API_URL, path)
	}

	headers := make(map[string]string)
	headers["API-Key"] = k.ClientKey
	headers["API-Sign"] = signature

	resp, err := SendHTTPRequest("POST", KRAKEN_API_URL+path, headers, strings.NewReader(values.Encode()))

	if err != nil {
		return nil, err
	}

	if k.Verbose {
		log.Printf("Recieved raw: \n%s\n", resp)
	}

	return resp, nil
}
示例#12
0
// List calls google.com/cloudprint/list to get all GCP printers assigned
// to this connector.
//
// Returns map of GCPID => printer name. GCPID is unique to GCP; printer name
// should be unique to CUPS. Use Printer to get details about each printer.
func (gcp *GoogleCloudPrint) List() (map[string]string, error) {
	form := url.Values{}
	form.Set("proxy", gcp.proxyName)
	form.Set("extra_fields", "-tags")

	responseBody, _, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"list", form)
	if err != nil {
		return nil, err
	}

	var listData struct {
		Printers []struct {
			ID   string `json:"id"`
			Name string `json:"name"`
		}
	}
	if err = json.Unmarshal(responseBody, &listData); err != nil {
		return nil, err
	}

	printers := make(map[string]string, len(listData.Printers))
	for _, p := range listData.Printers {
		printers[p.ID] = p.Name
	}

	return printers, nil
}
示例#13
0
func (k *Kraken) GetTradesHistory(tradeType string, showRelatedTrades bool, start, end, offset int64) {
	values := url.Values{}

	if len(tradeType) > 0 {
		values.Set("aclass", tradeType)
	}

	if showRelatedTrades {
		values.Set("trades", "true")
	}

	if start != 0 {
		values.Set("start", strconv.FormatInt(start, 10))
	}

	if end != 0 {
		values.Set("end", strconv.FormatInt(end, 10))
	}

	if offset != 0 {
		values.Set("offset", strconv.FormatInt(offset, 10))
	}

	result, err := k.SendAuthenticatedHTTPRequest(KRAKEN_TRADES_HISTORY, values)

	if err != nil {
		log.Println(err)
		return
	}

	log.Println(result)
}
示例#14
0
func (o *OKCoin) SendAuthenticatedHTTPRequest(method string, v url.Values) (err error) {
	v.Set("api_key", o.PartnerID)
	hasher := GetMD5([]byte(v.Encode() + "&secret_key=" + o.SecretKey))
	v.Set("sign", strings.ToUpper(HexEncodeToString(hasher)))

	encoded := v.Encode()
	path := o.APIUrl + method

	if o.Verbose {
		log.Printf("Sending POST request to %s with params %s\n", path, encoded)
	}

	headers := make(map[string]string)
	headers["Content-Type"] = "application/x-www-form-urlencoded"

	resp, err := SendHTTPRequest("POST", path, headers, strings.NewReader(encoded))

	if err != nil {
		return err
	}

	if o.Verbose {
		log.Printf("Recieved raw: \n%s\n", resp)
	}

	return nil
}
func doObjectStoreAddImage(c *cli.Context) error {
	var err error
	v := url.Values{}

	objectstoreUUID, err := getUUID(c, KEY_OBJECTSTORE, true, err)
	imageUUID, err := getUUID(c, KEY_IMAGE, false, err)
	imageName, err := getName(c, "image-name", false, err)
	if err != nil {
		return err
	}
	imageFile := c.String("image-file")
	if imageFile == "" {
		return genRequiredMissingError("image-file")
	}

	imageConfig := api.ObjectStoreImageConfig{
		ImageFile: imageFile,
	}
	if imageUUID != "" {
		v.Set(KEY_IMAGE, imageUUID)
	}
	if imageName != "" {
		v.Set("image-name", imageName)
	}

	request := "/objectstores/" + objectstoreUUID + "/images/add?" + v.Encode()
	return sendRequestAndPrint("POST", request, imageConfig)
}
示例#16
0
文件: oauth.go 项目: taviti/goauth2
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
}
示例#17
0
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
}
示例#18
0
func postMessage(path, room, message string) ([]byte, error) {
	data := url.Values{}
	data.Set("room_id", room)
	data.Add("message", message)
	data.Add("from", "hcl")
	data.Add("notify", "1")
	data.Add("color", "green")

	req, err := http.NewRequest("POST", path, bytes.NewBufferString(data.Encode()))
	if err != nil {
		fmt.Println("postMessage ERROR: ", err)
	}

	// for v2 only
	//authHeader := fmt.Sprintf("Bearer %s", token)
	//req.Header.Add("Authentication", authHeader)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("client do ERROR: ", err)
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Read body ERROR: ", err)
	}
	return body, nil
}
示例#19
0
func (client *DockerClient) PushImage(name string, tag string, auth *AuthConfig) error {
	v := url.Values{}
	if tag != "" {
		v.Set("tag", tag)
	}
	uri := fmt.Sprintf("/%s/images/%s/push?%s", APIVersion, url.QueryEscape(name), v.Encode())
	req, err := http.NewRequest("POST", client.URL.String()+uri, nil)
	if auth != nil {
		if encodedAuth, err := auth.encode(); err != nil {
			return err
		} else {
			req.Header.Add("X-Registry-Auth", encodedAuth)
		}
	}
	resp, err := client.HTTPClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	var finalObj map[string]interface{}
	for decoder := json.NewDecoder(resp.Body); err == nil; err = decoder.Decode(&finalObj) {
	}
	if err != io.EOF {
		return err
	}
	if err, ok := finalObj["error"]; ok {
		return fmt.Errorf("%v", err)
	}
	return nil
}
示例#20
0
// CmdRestart restarts one or more running containers.
//
// Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...]
func (cli *DockerCli) CmdRestart(args ...string) error {
	cmd := cli.Subcmd("restart", "CONTAINER [CONTAINER...]", "Restart a running container", true)
	nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Seconds to wait for stop before killing the container")
	cmd.Require(flag.Min, 1)

	cmd.ParseFlags(args, true)

	v := url.Values{}
	v.Set("t", strconv.Itoa(*nSeconds))

	var errNames []string
	for _, name := range cmd.Args() {
		_, _, err := readBody(cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil, nil))
		if err != nil {
			fmt.Fprintf(cli.err, "%s\n", err)
			errNames = append(errNames, name)
		} else {
			fmt.Fprintf(cli.out, "%s\n", name)
		}
	}
	if len(errNames) > 0 {
		return fmt.Errorf("Error: failed to restart containers: %v", errNames)
	}
	return nil
}
示例#21
0
func init() {
	storeBaseURI, err := url.Parse(cpiURL())
	if err != nil {
		panic(err)
	}

	storeSearchURI, err = storeBaseURI.Parse("search")
	if err != nil {
		panic(err)
	}

	v := url.Values{}
	v.Set("fields", strings.Join(getStructFields(remote.Snap{}), ","))
	storeSearchURI.RawQuery = v.Encode()

	storeDetailsURI, err = storeBaseURI.Parse("package/")

	if err != nil {
		panic(err)
	}

	storeBulkURI, err = storeBaseURI.Parse("click-metadata")
	if err != nil {
		panic(err)
	}
	storeBulkURI.RawQuery = v.Encode()
}
示例#22
0
文件: oauth2.go 项目: 40a/bootkube
func (c *Client) newAuthenticatedRequest(urlToken string, values url.Values) (*http.Request, error) {
	var req *http.Request
	var err error
	switch c.authMethod {
	case AuthMethodClientSecretPost:
		values.Set("client_secret", c.creds.Secret)
		req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
		if err != nil {
			return nil, err
		}
	case AuthMethodClientSecretBasic:
		req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
		if err != nil {
			return nil, err
		}
		encodedID := url.QueryEscape(c.creds.ID)
		encodedSecret := url.QueryEscape(c.creds.Secret)
		req.SetBasicAuth(encodedID, encodedSecret)
	default:
		panic("misconfigured client: auth method not supported")
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	return req, nil

}
示例#23
0
// initRobotAccount creates a GCP robot account for this connector.
func initRobotAccount(userClient *http.Client) (string, string) {
	params := url.Values{}
	params.Set("oauth_client_id", flagToString(gcpOAuthClientIDFlag, lib.DefaultConfig.GCPOAuthClientID))

	url := fmt.Sprintf("%s%s?%s", flagToString(gcpBaseURLFlag, lib.DefaultConfig.GCPBaseURL), "createrobot", params.Encode())
	response, err := userClient.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	if response.StatusCode != 200 {
		log.Fatal("failed to initialize robot account: " + response.Status)
	}

	var robotInit struct {
		Success  bool   `json:"success"`
		Message  string `json:"message"`
		XMPPJID  string `json:"xmpp_jid"`
		AuthCode string `json:"authorization_code"`
	}

	if err = json.NewDecoder(response.Body).Decode(&robotInit); err != nil {
		log.Fatal(err)
	}
	if !robotInit.Success {
		log.Fatal("failed to initialize robot account: " + robotInit.Message)
	}

	fmt.Println("Requested OAuth credentials for robot account")

	return robotInit.XMPPJID, robotInit.AuthCode
}
示例#24
0
文件: album.go 项目: brandur/spotify
// GetAlbumTracksOpt behaves like GetAlbumTracks, with the exception that it
// allows you to specify extra parameters that limit the number of results returned.
// The maximum number of results to return is specified by limit.
// The offset argument can be used to specify the index of the first track to return.
// It can be used along with limit to reqeust the next set of results.
func (c *Client) GetAlbumTracksOpt(id ID, limit, offset int) (*SimpleTrackPage, error) {
	spotifyURL := fmt.Sprintf("%salbums/%s/tracks", baseAddress, id)
	v := url.Values{}
	if limit != -1 {
		v.Set("limit", strconv.Itoa(limit))
	}
	if offset != -1 {
		v.Set("offset", strconv.Itoa(offset))
	}
	optional := v.Encode()
	if optional != "" {
		spotifyURL = spotifyURL + "?" + optional
	}
	resp, err := c.http.Get(spotifyURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result SimpleTrackPage
	err = json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}
示例#25
0
func (c *Cryptsy) SendAuthenticatedHTTPRequest(method, path string, params url.Values) (err error) {
	nonce := strconv.FormatInt(time.Now().Unix(), 10)
	params.Set("nonce", nonce)
	encoded := params.Encode()
	hmac := GetHMAC(HASH_SHA512, []byte(encoded), []byte(c.APISecret))
	readStr := ""

	if method == "GET" || method == "DELETE" {
		path += "?" + encoded
	} else if method == "POST" {
		readStr = encoded
	}

	if c.Verbose {
		log.Printf("Sending %s request to %s with params %s\n", method, path, encoded)
	}

	headers := make(map[string]string)
	headers["Key"] = c.APIKey
	headers["Sign"] = HexEncodeToString(hmac)
	headers["Content-Type"] = "application/x-www-form-urlencoded"

	resp, err := SendHTTPRequest(method, path, headers, strings.NewReader(readStr))

	if err != nil {
		return err
	}

	if c.Verbose {
		log.Printf("Recieved raw: \n%s\n", resp)
	}

	return nil
}
示例#26
0
文件: commands.go 项目: jweede/docker
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
}
示例#27
0
func (p *ListBaremetalDhcpParams) toURLValues() url.Values {
	u := url.Values{}
	if p.p == nil {
		return u
	}
	if v, found := p.p["dhcpservertype"]; found {
		u.Set("dhcpservertype", v.(string))
	}
	if v, found := p.p["id"]; found {
		vv := strconv.FormatInt(v.(int64), 10)
		u.Set("id", vv)
	}
	if v, found := p.p["keyword"]; found {
		u.Set("keyword", v.(string))
	}
	if v, found := p.p["page"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("page", vv)
	}
	if v, found := p.p["pagesize"]; found {
		vv := strconv.Itoa(v.(int))
		u.Set("pagesize", vv)
	}
	return u
}
示例#28
0
func searchTrack(context *echo.Context, song *SpotifySong) (*SpotifySong, error) {
	v := url.Values{}
	v.Set("type", "track")
	v.Set("q", song.Name+" artist:"+song.Artist)
	reqUrl := searchUrl + "?" + v.Encode()
	resp, err := getWithAuthToken(context, reqUrl)
	if err != nil {
		return song, err
	}
	defer resp.Body.Close()
	var result map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return song, err
	}
	if resp.StatusCode != http.StatusOK {
		return song, errors.New("Non-OK http status " + resp.Status)
	}
	tracks := result["tracks"].(map[string]interface{})
	items := tracks["items"].([]interface{})
	if len(items) > 0 {
		itemObj := items[0].(map[string]interface{})
		id := itemObj["id"].(string)
		song.SpotifyTrackId = id
	}
	return song, nil
}
示例#29
0
func searchAlbum(context *echo.Context, p *PipelineState, song *SpotifySong) (*SpotifySong, error) {
	if cachedId, ok := p.GetCachedAlbumId(song.Album, song.Artist); ok {
		song.SpotifyAlbumId = cachedId
		return song, nil
	}
	v := url.Values{}
	v.Set("type", "album")
	v.Set("q", song.Album+" artist:"+song.Artist)
	reqUrl := searchUrl + "?" + v.Encode()
	resp, err := getWithAuthToken(context, reqUrl)
	if err != nil {
		return song, err
	}
	defer resp.Body.Close()
	var result map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return song, err
	}
	if resp.StatusCode != http.StatusOK {
		return song, errors.New("Non-OK http status " + resp.Status)
	}
	albums := result["albums"].(map[string]interface{})
	items := albums["items"].([]interface{})
	if len(items) > 0 {
		itemObj := items[0].(map[string]interface{})
		id := itemObj["id"].(string)
		song.SpotifyAlbumId = id
		p.CacheAlbumId(song.Album, song.Artist, id)
	}
	return song, nil
}
示例#30
0
func (c *Client) Login(user, password string) bool {
	args := url.Values{}
	args.Set("user", user)

	resp, err := c.action("challenge", args)

	if err != nil {
		return false
	}

	if resp["status"].(float64) != 0 {
		return false
	}

	challenge := resp["response"].(map[string]interface{})["challenge"]
	args.Set("token", fmt.Sprintf("%x",
		md5.Sum([]byte(challenge.(string)+password))))
	respLogin, err := c.action("login", args)
	if err != nil {
		return false
	}
	if respLogin["status"].(float64) != 0 {
		return false
	}
	return true
}