コード例 #1
0
ファイル: push.go プロジェクト: uniqush/uniqush-conn
func (self *uniqushPush) postReadLines(path string, data url.Values, nrLines int) (value string, err error) {
	if len(path) == 0 {
		return
	}

	url := fmt.Sprintf("http://%v/%v", self.addr, path)

	c := http.Client{
		Transport: &http.Transport{
			Dial: timeoutDialler(self.timeout),
		},
	}
	resp, err := c.PostForm(url, data)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	if nrLines > 0 {
		respBuf := bufio.NewReader(resp.Body)
		line := make([]byte, 0, nrLines*512)
		for i := 0; i < nrLines; i++ {
			l, _, e := respBuf.ReadLine()
			if e != nil {
				err = e
				return
			}
			line = append(line, l...)
		}
		value = string(line)
	}
	return
}
コード例 #2
0
ファイル: main.go プロジェクト: mccoyst/topad
func main() {
	text, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		os.Stderr.WriteString("Failed to read anything: " + err.Error() + "\n")
		os.Exit(1)
	}

	vals := make(url.Values)
	vals.Set("body", string(text))

	skipRedirect := errors.New("I want the Location")

	c := http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return skipRedirect
		},
	}

	resp, err := c.PostForm("http://itsapad.appspot.com", vals)
	if err != nil && err.(*url.Error).Err != skipRedirect {
		os.Stderr.WriteString("Request failed: " + err.Error() + "\n")
		os.Exit(1)
	}
	defer resp.Body.Close()

	loc, err := resp.Location()
	if err != nil {
		os.Stderr.WriteString("Response failed: " + err.Error() + "\n")
		os.Exit(1)
	}
	os.Stderr.WriteString(loc.String() + "\n")
}
コード例 #3
0
ファイル: api.go プロジェクト: mantyr/vk_api
func auth_user(email string, password string, client_id string, scope string, client *http.Client) (*http.Response, error) {
	var auth_url = "http://oauth.vk.com/oauth/authorize?" +
		"redirect_uri=http://oauth.vk.com/blank.html&response_type=token&" +
		"client_id=" + client_id + "&v=5.0&scope=" + scope + "&display=wap"

	res, e := client.Get(auth_url)
	if e != nil {
		return nil, e
	}

	doc, err := goquery.NewDocumentFromResponse(res)
	if err != nil {
		return nil, err
	}

	formData, url, err := parse_form(doc)
	if err != nil {
		return nil, err
	}
	formData.Add("email", email)
	formData.Add("pass", password)

	res, e = client.PostForm(url, formData)
	if e != nil {
		return nil, e
	}
	return res, nil
}
コード例 #4
0
ファイル: register.go プロジェクト: jsimonetti/tlstun
func post(pass string) (string, error) {
	mynil := ""
	certf, keyf, err := shared.ReadMyCert("client.crt", "client.key")
	if err != nil {
		return mynil, err
	}
	tlsConfig, err := shared.GetTLSConfig(certf, keyf)
	if err != nil {
		return mynil, err
	}

	//loadServerCert()
	uri := fmt.Sprintf("https://%s:%d/register", serverIp, serverPort)

	tr := &http.Transport{
		TLSClientConfig: tlsConfig,
		Proxy:           http.ProxyFromEnvironment,
	}
	hc := http.Client{Transport: tr}

	form := url.Values{}
	form.Add("password", pass)

	resp, err := hc.PostForm(uri, form)
	if err != nil {
		return mynil, err
	}
	defer resp.Body.Close()
	s, err := ioutil.ReadAll(resp.Body)
	val := fmt.Sprintf("%s", s)
	if err != nil {
		return mynil, err
	}
	return val, err
}
コード例 #5
0
ファイル: oauth.go プロジェクト: freeformz/go-oauth
func (c *Client) request(client *http.Client, credentials *Credentials, urlStr string, params url.Values) (*Credentials, url.Values, error) {
	c.SignParam(credentials, "POST", urlStr, params)
	resp, err := client.PostForm(urlStr, params)
	if err != nil {
		return nil, nil, err
	}
	p, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return nil, nil, err
	}
	if resp.StatusCode != 200 {
		return nil, nil, fmt.Errorf("OAuth server status %d, %s", resp.StatusCode, string(p))
	}
	vals, err := url.ParseQuery(string(p))
	if err != nil {
		return nil, nil, err
	}
	credentials = &Credentials{
		Token:  vals.Get("oauth_token"),
		Secret: vals.Get("oauth_token_secret"),
	}
	if credentials.Token == "" {
		return nil, nil, errors.New("No OAuth token in server result")
	}
	if credentials.Secret == "" {
		return nil, nil, errors.New("No OAuth secret in server result")
	}
	return credentials, vals, nil
}
コード例 #6
0
func (c *Client) post(uri string, values url.Values, seconds int) error {
	if c.Debug {
		fmt.Printf("Making request to to: %s\n", uri)
	}
	timeout := time.Duration(seconds) * time.Second
	dial := func(network, addr string) (net.Conn, error) {
		return net.DialTimeout(network, addr, timeout)
	}

	transport := http.Transport{Dial: dial}
	client := http.Client{Transport: &transport}

	response, err := client.PostForm(uri, values)
	if err != nil {
		return err
	}
	defer response.Body.Close()

	data, _ := ioutil.ReadAll(response.Body)

	if err := json.Unmarshal(data, &c.State); err != nil {
		return err
	}

	if c.Debug {
		fmt.Printf("Setting data to:\n%s\n", string(data))
	}

	return nil
}
コード例 #7
0
ファイル: client.go プロジェクト: mike-marcacci/go-pipl
func (c *V4Client) request(timeout time.Duration, params map[string]string) (PiplResponse, error) {
	req, _ := url.Parse(c.BaseURL)
	p := url.Values{}

	for k, v := range params {
		p.Add(k, v)
	}
	p.Add("key", c.ApiKey)

	// maybe move http client up into struct
	client := http.Client{
		Timeout: timeout,
	}
	response, err := client.PostForm(req.String(), p)
	person := PiplResponse{}

	if err != nil {
		return person, err
	} else {
		defer response.Body.Close()
		contents, err := ioutil.ReadAll(response.Body)
		if err != nil {
			return person, err
		}
		if err = json.Unmarshal(contents, &person); err != nil {
			return person, err
		}
		if len(person.Error) > 0 {
			return person, errors.New(person.Error)
		}
		return person, nil
	}
}
コード例 #8
0
ファイル: clientlogin.go プロジェクト: evmar/picasync
func ClientLogin(client *http.Client, email, password, service string) (string, error) {
	resp, err := client.PostForm(clientLoginUrl, url.Values{
		"accountType": {"HOSTED_OR_GOOGLE"},
		"Email":       {email},
		"Passwd":      {password},
		"service":     {"lh2"},
	})
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// check for 200

	r := bufio.NewReader(resp.Body)
	var auth string
	for {
		line := MustReadLine(r)
		if line == nil {
			break
		}

		parts := bytes.SplitN(line, []byte("="), 2)
		if len(parts) != 2 {
			log.Panicf("bad line %q", line)
		}
		if string(parts[0]) == "Auth" {
			auth = string(parts[1])
		}
	}

	return auth, nil
}
コード例 #9
0
// Retry wrapper for http://golang.org/pkg/net/http/#Client.PostForm where attempts is the number of http calls made (one plus number of retries).
func (httpRetryClient *Client) ClientPostForm(c *http.Client, url string, data url.Values) (resp *http.Response, attempts int, err error) {
	return httpRetryClient.Retry(func() (*http.Response, error, error) {
		resp, err := c.PostForm(url, data)
		// assume all errors should result in a retry
		return resp, err, nil
	})
}
コード例 #10
0
ファイル: collector.go プロジェクト: marcelom/gocollector
func main() {
	client := http.Client{}

	for {

		si := syscall.Sysinfo_t{}
		syscall.Sysinfo(&si)

		l := strconv.FormatFloat(float64(si.Loads[0])/65536, 'f', 2)
		fmt.Println(l, si.Loads[0]/65536.0, si.Loads[0])

		time.Sleep(1 * time.Second)
		continue

		resp, err := client.PostForm("https://api.stathat.com/ez", url.Values{
			"stat":  {"loadavg"},
			"ezkey": {"YLJRun7adtSFKR2u"},
			"value": {l},
		})
		if err != nil {
			// Problems...
			fmt.Println("Error sending stat... : %v", err)
			os.Exit(1)
		}
		fmt.Println(resp)
		resp.Body.Close()
		time.Sleep(1 * time.Second)
	}
}
コード例 #11
0
ファイル: notice.go プロジェクト: qwo/abelana-gcp
func incomingImageHandler(w http.ResponseWriter, r *http.Request) error {
	c := appengine.NewContext(r)
	config := google.NewAppEngineConfig(c, "https://www.googleapis.com/auth/userinfo.email")
	config.Transport = &urlfetch.Transport{
		Context:                       c,
		Deadline:                      time.Minute,
		AllowInvalidServerCertificate: true,
	}
	client := http.Client{Transport: config.NewTransport()}

	r.ParseForm()
	res, err := client.PostForm(backendAddress, r.Form)
	if err != nil {
		return fmt.Errorf("backend: %v", err)
	}

	if res.StatusCode != http.StatusOK {
		b, err := httputil.DumpResponse(res, true)
		if err != nil {
			return fmt.Errorf("dump response: %v", err)
		}
		c.Errorf("backend failed with code %v:\n%s", res.Status, b)
	}

	w.WriteHeader(res.StatusCode)
	_, err = io.Copy(w, res.Body)
	return err
}
コード例 #12
0
func (c *Client) post(uri string, params map[string]string, timeout time.Duration) error {
	p := url.Values{}
	for key := range params {
		p.Set(key, params[key])
	}

	dialFunc := func(network, addr string) (net.Conn, error) {
		return net.DialTimeout(network, addr, timeout)
	}

	transport := http.Transport{Dial: dialFunc}
	client := http.Client{Transport: &transport}

	response, err := client.PostForm(uri, p)
	if err != nil {
		return err
	}
	defer response.Body.Close()

	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}

	decoder := json.NewDecoder(bytes.NewReader(data))
	if err := decoder.Decode(&c.state); err != nil {
		return err
	}

	return nil
}
コード例 #13
0
ファイル: openqq.go プロジェクト: jacky2007/openqq_sdk
//提交HTTP请求
func postRequest(callUrl string, method string, params map[string]string, protocol string) (map[string]interface{}, error) {
	var client *http.Client
	if strings.ToUpper(protocol) == "HTTPS" {
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		client = &http.Client{Transport: tr}
	} else {
		client = &http.Client{}
	}

	urlvs := url.Values{}
	for k, v := range params {
		urlvs.Add(k, v)
	}
	resp, err := client.PostForm(callUrl, urlvs)
	if err != nil {
		//fmt.Println("error")
		return nil, err
	}
	defer resp.Body.Close()
	body, tmpErr := ioutil.ReadAll(resp.Body)
	if tmpErr != nil {
		return nil, tmpErr
	}
	result := make(map[string]interface{})
	json.Unmarshal([]byte(body), &result)
	return result, nil

}
コード例 #14
0
func validateCourseID(stuid string, courseContent CourseContent, client *http.Client) (flag bool) {
	grade := stuid[:2]
	major := "11" + stuid[2:6]
	res, err := client.PostForm(DHUHostUrl+DHUTeachSchemaUrl, MakeParameters(map[string]string{"gradeYear": grade, "majorId": major}))
	if err != nil {
		return
	}
	doc, err := goquery.NewDocumentFromResponse(res)
	if err != nil {
		return
	}
	doc.Find("tr").EachWithBreak(func(i int, s *goquery.Selection) bool {
		breaks := true
		element := s.Find("td").Eq(1).Text()
		element = strings.TrimSpace(element)
		_, err := strconv.Atoi(element)
		if err == nil {
			if courseContent.CourseID == element {
				breaks = false
				flag = true
			}
		}
		return breaks
	})
	return
}
コード例 #15
0
ファイル: http.go プロジェクト: rinosukmandityo/toolkit
func HttpGetCookieJar(url string, callType string,
	config M) (*cookiejar.Jar, error) {

	var resp *http.Response
	var errCall error
	var client *http.Client

	jar, e := cookiejar.New(nil)
	if e != nil {
		return nil, fmt.Errorf("Unable to initialize cookie jar: %s", e.Error())
	}

	client = &http.Client{
		Jar: jar,
	}

	if callType == "POST" {
		if config.Has("loginvalues") {
			fvs := config["loginvalues"].(M)
			vs := httpurl.Values{}
			for k, v := range fvs {
				vs.Set(k, v.(string))
			}

			resp, errCall = client.PostForm(url, vs)
			if errCall == nil {
				resp.Body.Close()
			}
		}
	} else {
		_, errCall = client.Get(url)
	}

	return jar, errCall
}
コード例 #16
0
ファイル: cdrs.go プロジェクト: gale320/cgrates
// ToDo: Add websocket support
func (self *CdrServer) replicateCdr(cdr *StoredCdr) error {
	for _, rplCfg := range self.cgrCfg.CDRSCdrReplication {
		passesFilters := true
		for _, cdfFltr := range rplCfg.CdrFilter {
			if fltrPass, _ := cdr.PassesFieldFilter(cdfFltr); !fltrPass {
				passesFilters = false
				break
			}
		}
		if !passesFilters { // Not passes filters, ignore this replication
			continue
		}
		switch rplCfg.Transport {
		case utils.META_HTTP_POST:
			httpClient := new(http.Client)
			errChan := make(chan error)
			go func(cdr *StoredCdr, rplCfg *config.CdrReplicationCfg, errChan chan error) {
				if _, err := httpClient.PostForm(fmt.Sprintf("%s", rplCfg.Server), cdr.AsHttpForm()); err != nil {
					Logger.Err(fmt.Sprintf("<CDRReplicator> Replicating CDR: %+v, got error: %s", cdr, err.Error()))
					errChan <- err
				}
				errChan <- nil
			}(cdr, rplCfg, errChan)
			if rplCfg.Synchronous { // Synchronize here
				<-errChan
			}
		}
	}
	return nil
}
コード例 #17
0
ファイル: google.go プロジェクト: ecampbellrc/gdrive2slack
func NewAccessToken(conf *OauthConfiguration, client *http.Client, code string) (string, string, StatusCode, error) {
	response, err := client.PostForm("https://accounts.google.com/o/oauth2/token", url.Values{
		"code":          {code},
		"client_id":     {conf.ClientId},
		"client_secret": {conf.ClientSecret},
		"redirect_uri":  {conf.RedirectUri},
		"grant_type":    {"authorization_code"},
	})
	if err != nil {
		return "", "", CannotConnect, err
	}
	defer response.Body.Close()
	if response.StatusCode >= 400 {
		oauthError := &OauthError{}
		err = json.NewDecoder(response.Body).Decode(oauthError)
		if err != nil {
			return "", "", CannotDeserialize, err
		}
		if response.StatusCode >= 500 {
			return "", "", ServerError, errors.New(oauthError.ErrorDescription)
		}
		if response.StatusCode == 401 || response.StatusCode == 403 {
			return "", "", Unauthorized, errors.New(oauthError.ErrorDescription)
		}
		return "", "", ApiError, errors.New(oauthError.ErrorDescription)
	}
	var self = new(OauthState)
	err = json.NewDecoder(response.Body).Decode(self)
	if err != nil {
		return "", "", CannotDeserialize, err
	}
	return self.RefreshToken, self.AccessToken, Ok, nil
}
コード例 #18
0
ファイル: oauth.go プロジェクト: rfistman/camlistore
func (c *Client) request(client *http.Client, credentials *Credentials, urlStr string, params url.Values) (*Credentials, url.Values, error) {
	c.SignParam(credentials, "POST", urlStr, params)
	resp, err := client.PostForm(urlStr, params)
	if err != nil {
		return nil, nil, err
	}
	p, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return nil, nil, err
	}
	if resp.StatusCode != 200 && resp.StatusCode != 201 {
		return nil, nil, fmt.Errorf("OAuth server status %d, %s", resp.StatusCode, string(p))
	}
	m, err := url.ParseQuery(string(p))
	if err != nil {
		return nil, nil, err
	}
	tokens := m["oauth_token"]
	if len(tokens) == 0 || tokens[0] == "" {
		return nil, nil, errors.New("oauth: token missing from server result")
	}
	secrets := m["oauth_token_secret"]
	if len(secrets) == 0 { // allow "" as a valid secret.
		return nil, nil, errors.New("oauth: secret mssing from server result")
	}
	return &Credentials{Token: tokens[0], Secret: secrets[0]}, m, nil
}
コード例 #19
0
ファイル: user.go プロジェクト: gwitmond/ecca-proxy
// Signup at the registerURL with the Public key and cn for username
// expect a 201-Created with a PEM certificate or
// a 403-forbidden when the cn is already in use
func signupPubkey(client *http.Client, registerURL string, cn string, pub rsa.PublicKey) ([]byte, error) {
	pubkey := publicKeyToPEM(pub)
	resp, err := client.PostForm(registerURL, url.Values{"cn": {cn}, "pubkey": {pubkey}})
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.New("error reading response.body")
	}

	if resp.StatusCode == 403 {
		return nil, fmt.Errorf("Username '%s' is already taken. Please choose another", cn)
	}

	if resp.StatusCode == 201 {
		_ = pemDecodeCertificate(body) // decode and panic if it fails to decode properly.
		return body, nil
	}

	log.Printf("SignPubKey got response: %#v\n", resp)

	return nil, errors.New(fmt.Sprintf("Some error happened: %s ", body))
}
コード例 #20
0
ファイル: etcd_tls_test.go プロジェクト: joshuaconner/etcd
func assertServerFunctional(client http.Client, scheme string) error {
	path := fmt.Sprintf("%s://127.0.0.1:4001/v2/keys/foo", scheme)
	fields := url.Values(map[string][]string{"value": {"bar"}})

	for i := 0; i < 10; i++ {
		time.Sleep(1 * time.Second)

		resp, err := client.PostForm(path, fields)
		// If the status is Temporary Redirect, we should follow the
		// new location, because the request did not go to the leader yet.
		// TODO(yichengq): the difference between Temporary Redirect(307)
		// and Created(201) could distinguish between leader and followers
		for err == nil && resp.StatusCode == http.StatusTemporaryRedirect {
			loc, _ := resp.Location()
			newPath := loc.String()
			resp, err = client.PostForm(newPath, fields)
		}

		if err == nil {
			// Internal error may mean that servers are in leader election
			if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusInternalServerError {
				return errors.New(fmt.Sprintf("resp.StatusCode == %s", resp.Status))
			} else {
				return nil
			}
		}
	}

	return errors.New("etcd server was not reachable in time / had internal error")
}
コード例 #21
0
func (d *DHUStruct) sendRequest(url string, m map[string]string, client *http.Client) (*http.Response, error) {
	var err error
	var res *http.Response
	isPost, err := checkPost(m)
	delete(m, "Action")
	if err == nil {
		for i := 0; i < 3; i++ {
			if d.mutexClient != nil {
				d.mutexClient.RLock()
				defer d.mutexClient.RUnlock()
			}
			if isPost {
				res, err = client.PostForm(url, MakeParameters(m))
			} else {
				res, err = client.Get(url + getParaString(m))
			}
			if err == nil {
				break
			}
			time.Sleep(time.Duration(i*2+1) * time.Second)
		}
		if err != nil {
			err = networkErr
		}
		return res, err
	} else {
		return nil, errors.New("Error in Login")
	}
}
コード例 #22
0
ファイル: main.go プロジェクト: ameihm0912/service-map
func sendIndicators(indparam slib.IndicatorParams) error {
	if postOut == "-" {
		for _, x := range indparam.Indicators {
			buf, err := json.Marshal(&x)
			if err != nil {
				fmt.Fprintf(os.Stderr, "error marshaling indicator: %v\n", err)
				continue
			}
			fmt.Printf("%v\n", string(buf))
		}
		return nil
	}
	buf, err := json.Marshal(&indparam)
	if err != nil {
		return err
	}
	tcfg := &http.Transport{}
	if noVerify {
		tcfg.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
	}
	clnt := http.Client{Transport: tcfg}
	form := url.Values{}
	form.Add("params", string(buf))
	resp, err := clnt.PostForm(postOut, form)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return fmt.Errorf("request failed: %v", resp.Status)
	}
	return nil
}
コード例 #23
0
ファイル: work.go プロジェクト: mehulsbhatt/pinger-2
func (w Work) PostPingStats(result *WorkResult) {
	if result == nil {
		fmt.Println("Result is nil")
		return
	}

	if w.HTTP != "" {
		transport := http.Transport{
			Dial: func(network, addr string) (net.Conn, error) {
				return net.DialTimeout(network, addr, 2e9)
			},
			ResponseHeaderTimeout: 2e9,
		}
		client := http.Client{
			Transport: &transport,
		}
		resp, err := client.PostForm(
			w.HTTP, url.Values{
				"Min":      {result.Min.String()},
				"Max":      {result.Max.String()},
				"Avg":      {result.Avg.String()},
				"Success":  {fmt.Sprintf("%d", result.Success)},
				"Timeouts": {fmt.Sprintf("%d", result.Timeouts)},
				"Data":     {w.Data},
			},
		)
		if err != nil {
			fmt.Println(err)
			return
		}
		if resp.StatusCode >= 400 {
			fmt.Println("Worker: HTTP not ok:", resp.Status)
			return
		}
		fmt.Println("Worker: Posted data over HTTP.")
	}

	if w.UDP != "" {
		conn, err := net.DialTimeout("udp", w.UDP, 1e9)
		if err != nil {
			fmt.Println("Error establishing connection to host: %s\n", err)
			return
		}

		result.Data = w.Data

		bytes, err := json.Marshal(result)
		if err != nil {
			fmt.Println("Error marshalling:", err)
			return
		}
		_, err = conn.Write(bytes)
		if err != nil {
			fmt.Println("Error marshalling:", err)
		}
		fmt.Println("Worker: Posted data over UDP.")
	}
}
コード例 #24
0
func (auth OAuthAuthenticator) Authorize(credentials ClientCredentials,
	code string,
	client *http.Client) (*OAuthAuthorizationResponse, error) {
	if code == "" {
		return nil, OAuthInvalidCodeErr
	}

	if client == nil {
		client = http.DefaultClient
	}

	resp, err := client.PostForm(BaseOAuthPath+"/token",
		url.Values{
			"grant_type": {
				"authorization_code",
			},
			"code": {
				code,
			},
			"client_id": {
				credentials.ClientId,
			},
			"client_secret": {
				credentials.ClientSecret,
			},
		})

	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode/100 == 5 {
		return nil, OAuthServerErr
	}

	if resp.StatusCode/100 != 2 {
		var response OAuthErrorResponse
		contents, _ := ioutil.ReadAll(resp.Body)
		json.Unmarshal(contents, &response)

		// TODO Create instances for documented error codes

		return nil, &response
	}

	var response OAuthAuthorizationResponse
	contents, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(contents, &response)

	if err != nil {
		return nil, err
	}

	return &response, nil
}
コード例 #25
0
ファイル: session.go プロジェクト: ee1yae8i/myebirdfeed
func login(client *http.Client, username, password string) {
	form := url.Values{}
	form.Set("j_username", username)
	form.Set("j_password", password)
	form.Set("cmd", "login")
	resp, err := client.PostForm("https://ebird.org/ebird/j_acegi_security_check", form)
	if err != nil {
		panic(err.Error())
	}
}
コード例 #26
0
ファイル: oauth.go プロジェクト: cdupuis/strava
// Authorize performs the second part of the OAuth exchange. The client has already been redirected to the
// Strava authorization page, has granted authorization to the application and has been redirected back to the
// defined URL. The code param was returned as a query string param in to the redirect_url.
func (auth OAuthAuthenticator) Authorize(code string, client *http.Client) (*AuthorizationResponse, error) {
	// make sure a code was passed
	if code == "" {
		return nil, OAuthInvalidCodeErr
	}

	// if a client wasn't passed use the default client
	if client == nil {
		client = http.DefaultClient
	}

	resp, err := client.PostForm(basePath+"/oauth/token",
		url.Values{"client_id": {fmt.Sprintf("%d", ClientId)}, "client_secret": {ClientSecret}, "code": {code}})

	// this was a poor request, maybe strava servers down?
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// check status code, could be 500, or most likely the client_secret is incorrect
	if resp.StatusCode/100 == 5 {
		return nil, OAuthServerErr
	}

	if resp.StatusCode/100 != 2 {
		var response Error
		contents, _ := ioutil.ReadAll(resp.Body)
		json.Unmarshal(contents, &response)

		if len(response.Errors) == 0 {
			return nil, OAuthServerErr
		}

		if response.Errors[0].Resource == "Application" {
			return nil, OAuthInvalidCredentialsErr
		}

		if response.Errors[0].Resource == "RequestToken" {
			return nil, OAuthInvalidCodeErr
		}

		return nil, &response
	}

	var response AuthorizationResponse
	contents, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(contents, &response)

	if err != nil {
		return nil, err
	}

	return &response, nil
}
コード例 #27
0
ファイル: http.go プロジェクト: rinosukmandityo/toolkit
func httpcall(req *http.Request, config M) (*http.Response, error) {
	var client *http.Client

	//-- handling cookie
	if config.Has("cookie") == false {
		client = new(http.Client)
	} else {
		//-- preparing cookie jar and http client
		jar, err := cookiejar.New(nil)
		if err != nil {
			return nil, fmt.Errorf("Unable to initialize cookie jar: %s", err.Error())
		}

		tjar := config.Get("cookie", nil).(*cookiejar.Jar)

		if tjar != nil {
			jar = tjar
		}

		client = &http.Client{
			Jar: jar,
		}
	}

	//--- handling header
	if headers, hasHeaders := config["headers"]; hasHeaders {
		mHeaders := headers.(M)
		for k, v := range mHeaders {
			req.Header.Add(k, v.(string))
		}
	}

	var resp *http.Response
	var errCall error

	if config.Has("formvalues") {
		fvs := config["formvalues"].(M)
		vs := httpurl.Values{}
		for k, v := range fvs {
			// fmt.Printf("Add formvalue %s = %v \n", k, v)
			//q += k + "="
			//q += v.(string)
			vs.Set(k, v.(string))
		}
		resp, errCall = client.PostForm(req.URL.String(), vs)
	} else {
		resp, errCall = client.Do(req)
	}
	if errCall == nil {
		if expectedStatus := config.Get("expectedstatus", 0).(int); expectedStatus != 0 && resp.StatusCode != expectedStatus {
			return nil, fmt.Errorf("Code error: " + resp.Status)
		}
	}
	return resp, errCall
}
コード例 #28
0
ファイル: acousticid.go プロジェクト: raks81/go-acousticid
func (a *AcousticidRequest) Request() AcousticidResponse {
	client := http.Client{}
	response, err := client.PostForm("http://api.acoustid.org/v2/lookup", a.PostValues())
	check(err)
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	aidresponse := AcousticidResponse{}
	err = json.Unmarshal(body, &aidresponse)
	check(err)
	return aidresponse
}
コード例 #29
0
// Assert obtains an *oauth.Token from the remote server by encoding and sending
// a JWT.  The access_token will expire in one hour (3600 seconds) and cannot be
// refreshed (no refresh_token is returned with the response).  Once this token
// expires call this method again to get a fresh one.
func (t *Token) Assert(c *http.Client) (*oauth.Token, error) {
	var o *oauth.Token
	u, v, err := t.buildRequest()
	if err != nil {
		return o, err
	}
	resp, err := c.PostForm(u, v)
	if err != nil {
		return o, err
	}
	o, err = handleResponse(resp)
	return o, err
}
コード例 #30
0
ファイル: goth_test.go プロジェクト: jroes/goth
func createAndSignInUser(ts *httptest.Server, authHandler goth.AuthHandler, client http.Client) {
	user := user.New("*****@*****.**", "password")
	authHandler.UserStore.Save(*user)
	resp, err := client.PostForm(ts.URL+"/auth/sign_in",
		url.Values{"email": {"*****@*****.**"}, "password": {"password"}})
	if err != nil {
		panic(err)
	}
	contents, _ := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	if !strings.Contains(string(contents), "*****@*****.**") {
		panic(fmt.Sprintf("Expected response to contain [email protected]: %s", contents))
	}
}