示例#1
2
文件: request.go 项目: arnold8/go
func copyValues(dst, src url.Values) {
	for k, vs := range src {
		for _, value := range vs {
			dst.Add(k, value)
		}
	}
}
示例#2
2
/*
Build URL for an API method call. Note that when using GET, we will also append query parameter to URL
*/
func (api *Api) buildUrl(method string, option map[string]string) string {
	q := url.Values{}
	for k, v := range option {
		q.Add(k, v)
	}
	return api.config.Endpoint(method) + "?" + q.Encode()
}
示例#3
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
}
示例#4
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
}
示例#5
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
}
示例#6
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
}
示例#7
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
}
示例#8
1
文件: zoj.go 项目: B88000005/vjudger
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
}
示例#9
1
文件: hbapi.go 项目: yukihir0/hbapi
// 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
}
示例#10
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
}
示例#11
0
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 = &params.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
	})}
}
示例#12
0
// 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
}
示例#13
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
}
示例#14
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
}
示例#15
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
}
示例#16
0
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
}
示例#17
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
}
示例#18
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
}
示例#19
0
文件: blob.go 项目: RaulKite/machine
// GetBlobSASURI creates an URL to the specified blob which contains the Shared
// Access Signature with specified permissions and expiration time.
//
// See https://msdn.microsoft.com/en-us/library/azure/ee395415.aspx
func (b BlobStorageClient) GetBlobSASURI(container, name string, expiry time.Time, permissions string) (string, error) {
	var (
		signedPermissions = permissions
		blobURL           = b.GetBlobURL(container, name)
	)
	canonicalizedResource, err := b.client.buildCanonicalizedResource(blobURL)
	if err != nil {
		return "", err
	}
	signedExpiry := expiry.UTC().Format(time.RFC3339)
	signedResource := "b"

	stringToSign, err := blobSASStringToSign(b.client.apiVersion, canonicalizedResource, signedExpiry, signedPermissions)
	if err != nil {
		return "", err
	}

	sig := b.client.computeHmac256(stringToSign)
	sasParams := url.Values{
		"sv":  {b.client.apiVersion},
		"se":  {signedExpiry},
		"sr":  {signedResource},
		"sp":  {signedPermissions},
		"sig": {sig},
	}

	sasURL, err := url.Parse(blobURL)
	if err != nil {
		return "", err
	}
	sasURL.RawQuery = sasParams.Encode()
	return sasURL.String(), nil
}
示例#20
0
func createRequest(v url.Values) *http.Request {
	body := strings.NewReader(v.Encode())
	req, _ := http.NewRequest("POST",
		"http://localhost:8080/-/auth/password", body)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded;")
	return req
}
示例#21
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
}
示例#22
0
func challengeFromForm(form url.Values) (Challenge, error) {
	var err error
	c := Challenge{}
	fmt.Println(form)
	c.Title = form.Get("title")
	if c.Title == "" {
		return c, errors.New("No Title")
	}
	c.Description = template.HTML(form.Get("description"))
	if c.Title == "" {
		return c, errors.New("No Description")
	}
	c.Alias = form.Get("path")
	if c.Alias == "" {
		return c, errors.New("No path")
	}
	c.MaxScore, err = strconv.Atoi(form.Get("points"))
	if err != nil || c.MaxScore <= 0 || c.MaxScore > MaxChallengeScore {
		return c, errors.New("Wrong Points Format or Missing")
	}
	c.Category = form.Get("category")
	if c.Category == "" {
		return c, errors.New("No Category")
	}
	return c, nil
}
示例#23
0
文件: client.go 项目: yanlixin/GoQQ
func HttpPost(u string, data url.Values) (re *http.Response, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = e.(error)
		}
	}()
	//lg.Trace("\nPOST: URL: %v\nDATA: %v", u, data.Encode())
	req, err := http.NewRequest("POST", u, strings.NewReader(data.Encode()))
	if nil != err {
		return nil, err
	}
	//ErrHandle(err, `p`)

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

	if client.Jar != nil {
		for _, cookie := range client.Jar.Cookies(req.URL) {
			req.AddCookie(cookie)
		}
	}

	req.Header.Add(`referer`, `http://d.web2.qq.com/proxy.html?v=20110331002&callback=2&id=3`)

	re, err = client.Do(req)
	if nil != err {
		return nil, err
	}

	//ErrHandle(err, `p`)

	client.Jar.SetCookies(req.URL, re.Cookies())
	return re, nil
}
示例#24
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
}
示例#25
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
}
示例#26
0
func (self *ReportClient) Request(path string, params map[string]string) (ret interface{}, err error) {
	args := make(map[string]string, len(params)+3)
	for k, v := range params {
		args[k] = v
	}

	args["api_key"] = self.apiKey
	args["expire"] = fmt.Sprintf("%d", time.Now().Unix()+600)
	args["sig"] = hashArgs(self.apiSecret, args)

	query := url.Values{}
	for k, v := range args {
		query.Add(k, v)
	}
	url := fmt.Sprintf("%s/%s/%s/?%s", ENDPOINT, VERSION, path, query.Encode())
	resp, urlerr := http.Get(url)
	if urlerr != nil {
		err = urlerr
		return
	}

	defer resp.Body.Close()
	body, httperr := ioutil.ReadAll(resp.Body)
	if httperr != nil {
		err = httperr
		return
	}
	jsonerr := json.Unmarshal(body, &ret)
	if jsonerr != nil {
		err = jsonerr
		return
	}
	return ret, nil
}
示例#27
0
文件: oauth2.go 项目: 40a/bootkube
func ParseAuthCodeRequest(q url.Values) (AuthCodeRequest, error) {
	acr := AuthCodeRequest{
		ResponseType: q.Get("response_type"),
		ClientID:     q.Get("client_id"),
		State:        q.Get("state"),
		Scope:        make([]string, 0),
	}

	qs := strings.TrimSpace(q.Get("scope"))
	if qs != "" {
		acr.Scope = strings.Split(qs, " ")
	}

	err := func() error {
		if acr.ClientID == "" {
			return NewError(ErrorInvalidRequest)
		}

		redirectURL := q.Get("redirect_uri")
		if redirectURL != "" {
			ru, err := url.Parse(redirectURL)
			if err != nil {
				return NewError(ErrorInvalidRequest)
			}
			acr.RedirectURL = ru
		}

		return nil
	}()

	return acr, err
}
示例#28
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
}
// validateToken returns true if token is valid
func validateToken(p Provider, access_token string, header http.Header) bool {
	if access_token == "" || p.Data().ValidateUrl == nil {
		return false
	}
	endpoint := p.Data().ValidateUrl.String()
	if len(header) == 0 {
		params := url.Values{"access_token": {access_token}}
		endpoint = endpoint + "?" + params.Encode()
	}
	resp, err := api.RequestUnparsedResponse(endpoint, header)
	if err != nil {
		log.Printf("GET %s", endpoint)
		log.Printf("token validation request failed: %s", err)
		return false
	}

	body, _ := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	log.Printf("%d GET %s %s", resp.StatusCode, endpoint, body)

	if resp.StatusCode == 200 {
		return true
	}
	log.Printf("token validation request failed: status %d - %s", resp.StatusCode, body)
	return false
}
示例#30
0
文件: start.go 项目: gnawux/hyper
func (cli *Client) startPodWithoutTty(v *url.Values) (string, error) {

	body, _, err := readBody(cli.call("POST", "/pod/start?"+v.Encode(), nil, nil))
	if err != nil {
		return "", err
	}
	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return "", err
	}

	if _, err := out.Write(body); err != nil {
		return "", fmt.Errorf("Error reading remote info: %s", err)
	}
	out.Close()
	errCode := remoteInfo.GetInt("Code")
	if errCode != types.E_OK {
		if errCode != types.E_BAD_REQUEST &&
			errCode != types.E_FAILED {
			return "", fmt.Errorf("Error code is %d", errCode)
		} else {
			return "", fmt.Errorf("Cause is %s", remoteInfo.Get("Cause"))
		}
	}
	return remoteInfo.Get("ID"), nil
}