Exemple #1
1
func initRequest(req *http.Request, gr *GoReq) {
	for k, v := range gr.Header {
		req.Header.Set(k, v)
	}
	// Add all querystring from Query func
	q := req.URL.Query()
	for k, v := range gr.QueryData {
		for _, vv := range v {
			q.Add(k, vv)
		}
	}
	req.URL.RawQuery = q.Encode()

	// Add basic auth
	if gr.BasicAuth != (struct{ Username, Password string }{}) {
		req.SetBasicAuth(gr.BasicAuth.Username, gr.BasicAuth.Password)
	}

	// Add cookies
	for _, cookie := range gr.Cookies {
		req.AddCookie(cookie)
	}

	//check client
	if gr.Client == nil {
		gr.setDefaultClient()
	}
	if gr.CheckRedirect != nil {
		gr.Client.CheckRedirect = gr.CheckRedirect
	}

	// Set Transport
	gr.Client.Transport = gr.Transport
}
Exemple #2
0
func (this *Intercom_t) GetTagList(tags *TagList_t) (err error) {
	var (
		req    *http.Request
		resp   *http.Response
		client = new(http.Client)
	) //var

	// Create new GET request
	if req, err = http.NewRequest("GET", TAG_GET_API_ENDPOINT, nil); err != nil {
		return err
	} //if

	// Set authentication and headers
	req.SetBasicAuth(this.AppId, this.ApiKey)
	req.Header.Set("Accept", "application/json")

	// Perform GET request
	if resp, err = client.Do(req); err != nil {
		return err
	} //if
	defer resp.Body.Close()

	// Check reponse code and report any errors
	// Intercom sends back a 200 for valid requests
	if resp.StatusCode != 200 {
		return errors.New(resp.Status)
	} //if

	// Decode JSON response into User_t struct
	if err = json.NewDecoder(resp.Body).Decode(tags); err != nil {
		return err
	} //if

	return nil
} //GetTagList
func performRequest(r *http.Request) (*http.Response, error) {
	if r == nil {
		return nil, errors.New("Invalid HTTP Request object")
	}
	if len(csrfToken) > 0 {
		r.Header.Set("X-CSRF-Token", csrfToken)
	}
	if len(authUser) > 0 {
		r.SetBasicAuth(authUser, authPass)
	}
	if len(apiKey) > 0 {
		r.Header.Set("X-API-Key", apiKey)
	}
	tr := &http.Transport{
		TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},
		ResponseHeaderTimeout: requestTimeout,
		DisableKeepAlives:     true,
	}
	client := &http.Client{
		Transport: tr,
		Timeout:   requestTimeout,
	}
	res, err := client.Do(r)
	return res, err
}
func (t *BasicTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	if t.Username != "" || t.Password != "" {
		req.SetBasicAuth(t.Username, t.Password)
	}
	resp, err := t.Transport.RoundTrip(req)
	return resp, err
}
func (s *ServiceHandler) SelectDirector(req *http.Request) {
	if s.selectedCluster != nil {
		req.URL.Host = s.selectedCluster.Endpoint
		req.URL.Scheme = "https"
		req.SetBasicAuth(s.selectedCluster.MasterAuth.Username, s.selectedCluster.MasterAuth.Password)
	}
}
Exemple #6
0
func (conn SplunkConnection) addAuthHeader(request *http.Request) {
	if conn.sessionKey.Value != "" {
		request.Header.Add("Authorization", fmt.Sprintf("Splunk %s", conn.sessionKey))
	} else {
		request.SetBasicAuth(conn.Username, conn.Password)
	}
}
Exemple #7
0
func (conn *Connection) execHTTPRequest(req *http.Request) (int, []byte, error) {
	req.Header.Add("Accept", "application/json")
	if conn.Username != "" || conn.Password != "" {
		req.SetBasicAuth(conn.Username, conn.Password)
	}

	resp, err := conn.http.Do(req)
	if err != nil {
		conn.connected = false
		return 0, nil, err
	}
	defer closing(resp.Body)

	status := resp.StatusCode
	if status >= 300 {
		conn.connected = false
		return status, nil, fmt.Errorf("%v", resp.Status)
	}

	obj, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		conn.connected = false
		return status, nil, err
	}
	return status, obj, nil
}
Exemple #8
0
// APICall is used to query the BIG-IP web API.
func (b *BigIP) APICall(options *APIRequest) ([]byte, error) {
	var req *http.Request
	client := &http.Client{Transport: b.Transport}
	url := fmt.Sprintf("%s/mgmt/tm/%s", b.Host, options.URL)
	body := bytes.NewReader([]byte(options.Body))
	req, _ = http.NewRequest(strings.ToUpper(options.Method), url, body)
	req.SetBasicAuth(b.User, b.Password)

	//log.Println("REQ -- ", url," -- ",options.Body)

	if len(options.ContentType) > 0 {
		req.Header.Set("Content-Type", options.ContentType)
	}

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

	defer res.Body.Close()

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

	if res.StatusCode >= 400 {
		if res.Header["Content-Type"][0] == "application/json" {
			return data, b.checkError(data)
		}

		return data, errors.New(fmt.Sprintf("HTTP %d :: %s", res.StatusCode, string(data[:])))
	}

	return data, nil
}
Exemple #9
0
// 根据文档struct的ID字段,查询,并返回文档的数据
func (couchDB *CouchDB) QueryDoc(doc IDoc) []byte {
	dbURLString := couchDB.COUCH_DB_HOST + doc.GetDBName() + "/"
	docURLString := dbURLString
	if id := doc.GetID(); id != "" {
		docURLString += id
	}
	//
	docURL, _ := url.Parse(docURLString)
	r := http.Request{
		Method: `GET`,
		URL:    docURL,
		Header: map[string][]string{},
		Close:  true,
	}
	if password, ok := r.URL.User.Password(); ok {
		r.SetBasicAuth(r.URL.User.Username(), password)
	}
	c := http.Client{}
	resp, err := c.Do(&r)
	if err != nil {
		handleError(err, "从CouchDB请求查询Doc,获取响应部分错误。")
	}
	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		handleError(err, "从CouchDB请求查询Doc,解码JSON部分错误。")
	} else {
		return bytes
	}

	return nil
}
Exemple #10
0
// 让CouchDB返回UUID
// count: 请求多少条UUID
func (couchDB *CouchDB) GetUUIDFromCouchDB(count uint8) []string {
	queryUUIDsURLString := couchDB.COUCH_DB_HOST + "_uuids" + "?count=" + fmt.Sprintf("%d", count)
	queryUUIDsURL, _ := url.Parse(queryUUIDsURLString)
	r := http.Request{
		Method: `GET`,
		URL:    queryUUIDsURL,
		Header: map[string][]string{},
		Close:  true,
	}
	if password, ok := r.URL.User.Password(); ok {
		r.SetBasicAuth(r.URL.User.Username(), password)
	}
	c := http.Client{}
	resp, err := c.Do(&r)
	if err != nil {
		handleError(err, "从CouchDB请求创建UUID,获取响应部分错误。")
	}
	bytes, _ := ioutil.ReadAll(resp.Body)
	uuids := &UUIDs{}
	err = json.Unmarshal(bytes, uuids)
	if err != nil {
		handleError(err, "从CouchDB请求创建UUID,解码JSON部分错误。")
	} else {
		return uuids.UUIDs
	}
	return nil
}
Exemple #11
0
func (fetcher *CCFetcher) doRequest(
	logger lager.Logger,
	httpClient *http.Client,
	req *http.Request,
	value interface{},
) error {
	req.Header.Set("Content-Type", "application/json")
	req.SetBasicAuth(fetcher.Username, fetcher.Password)

	resp, err := httpClient.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	logger.Info("fetching-desired-complete", lager.Data{
		"StatusCode": resp.StatusCode,
	})

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("invalid response code %d", resp.StatusCode)
	}

	err = json.NewDecoder(resp.Body).Decode(value)
	if err != nil {
		logger.Error("decode-body", err)
		return err
	}

	return nil
}
Exemple #12
0
func (p *Paymill) ClientRequest(pr *PaymillRequest) string {
	var request *http.Request
	var err error
	if pr.Method == "POST" {
		data := pr.Body
		reader := bytes.NewBufferString(data.Encode())
		request, err = http.NewRequest(pr.Method, pr.Uri, reader)
		request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
		request.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
	} else {
		request, err = http.NewRequest(pr.Method, pr.Uri, bytes.NewBufferString(""))
	}
	if err != nil {
		panic(err)
	}
	request.SetBasicAuth(p.PrivateKey, p.PrivateKey)
	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	contents, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	return string(contents)
}
Exemple #13
0
func (auth basicAuth) Sign(request *http.Request) {
	if request == nil {
		return
	}

	request.SetBasicAuth(auth.Username, auth.Password)
}
Exemple #14
0
// DoWithBody implements httprequest.DoerWithBody.DoWithBody.
func (doer httpRequestDoer) DoWithBody(req *http.Request, body io.ReadSeeker) (*http.Response, error) {
	// Add basic auth if appropriate
	// Call doer.bakeryClient.DoWithBodyAndCustomError
	if doer.st.tag != "" {
		// Note that password may be empty here; we still
		// want to pass the tag along. An empty password
		// indicates that we're using macaroon authentication.
		req.SetBasicAuth(doer.st.tag, doer.st.password)
	}
	// Add any explicitly-specified macaroons.
	for _, ms := range doer.st.macaroons {
		encoded, err := encodeMacaroonSlice(ms)
		if err != nil {
			return nil, errors.Trace(err)
		}
		req.Header.Add(httpbakery.MacaroonsHeader, encoded)
	}
	return doer.st.bakeryClient.DoWithBodyAndCustomError(req, body, func(resp *http.Response) error {
		// At this point we are only interested in errors that
		// the bakery cares about, and the CodeDischargeRequired
		// error is the only one, and that always comes with a
		// response code StatusUnauthorized.
		if resp.StatusCode != http.StatusUnauthorized {
			return nil
		}
		return bakeryError(unmarshalHTTPErrorResponse(resp))
	})
}
Exemple #15
0
func (self *LibratoClient) PostMetrics(batch Batch) (err error) {
	var (
		js   []byte
		req  *http.Request
		resp *http.Response
	)

	if len(batch.Counters) == 0 && len(batch.Gauges) == 0 {
		return nil
	}

	if js, err = json.Marshal(batch); err != nil {
		return
	}

	if req, err = http.NewRequest("POST", MetricsPostUrl, bytes.NewBuffer(js)); err != nil {
		return
	}

	req.Header.Set("Content-Type", "application/json")
	req.SetBasicAuth(self.Email, self.Token)

	if resp, err = http.DefaultClient.Do(req); err != nil {
		return
	}

	if resp.StatusCode != http.StatusOK {
		var body []byte
		if body, err = ioutil.ReadAll(resp.Body); err != nil {
			body = []byte(fmt.Sprintf("(could not fetch response body for error: %s)", err))
		}
		err = fmt.Errorf("Unable to post to Librato: %d %s %s", resp.StatusCode, resp.Status, string(body))
	}
	return
}
Exemple #16
0
func (s *RouterSuite) TestInfoApi(c *C) {
	var client http.Client
	var req *http.Request
	var resp *http.Response
	var err error

	<-s.WaitUntilNatsIsUp()
	s.mbusClient.Publish("router.register", []byte(`{"dea":"dea1","app":"app1","uris":["test.com"],"host":"1.2.3.4","port":1234,"tags":{},"private_instance_id":"private_instance_id"}`))
	time.Sleep(250 * time.Millisecond)

	host := fmt.Sprintf("http://%s:%d/routes", s.Config.Ip, s.Config.Status.Port)

	req, err = http.NewRequest("GET", host, nil)
	req.SetBasicAuth("user", "pass")

	resp, err = client.Do(req)
	c.Assert(err, IsNil)
	c.Assert(resp, Not(IsNil))
	c.Check(resp.StatusCode, Equals, 200)

	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	c.Assert(err, IsNil)
	c.Check(string(body), Matches, ".*1\\.2\\.3\\.4:1234.*\n")
}
Exemple #17
0
// 查询某数据库的DesignDocument(DD)
//
// 		dbName:数据库名
//		ddName: Is the Design Document ID's value,that without "_design/"
//		viewName:Is the view name that without "_view/"
//		queryString:查询参数;(key、startkey、endkey .et)
//
//		注意,queryString参数,需要加引号“”
//		QueryView(DB_USERS_NAME, DB_USERS_DD_NAME, DB_USERS_DD_VIEW_KEY_IS_NAME, `key="`+userDoc.Name+`"`)
//
//		视图的查询结果模版为:{"total_rows":13,"offset":3,"rows":[{"id":"","key":"","value":{}]}
//		rows := &couchdb.ResultRows{}
//		rows.Rows = []map[string]interface{}{} //默认初始化,为nil,不为零值
//		json.Unmarshal(bytes, rows)
func (couchDB *CouchDB) QueryView(dbName string, ddName string, viewName string, queryString string) []byte {
	dbURLString := couchDB.COUCH_DB_HOST + dbName + "/"
	ddURLString := dbURLString + "_design/" + ddName + "/"
	vwURLString := ddURLString + "_view/" + viewName
	vwQueryURLString := vwURLString + "?"
	if queryString != "" {
		vwQueryURLString += queryString
	}

	//
	vwQueryURL, _ := url.Parse(vwQueryURLString)
	r := http.Request{
		Method: `GET`,
		URL:    vwQueryURL,
		Header: map[string][]string{},
		Close:  true,
	}
	if password, ok := r.URL.User.Password(); ok {
		r.SetBasicAuth(r.URL.User.Username(), password)
	}
	c := http.Client{}
	resp, err := c.Do(&r)
	if err != nil {
		handleError(err, "从CouchDB请求DB的View,获取响应部分错误。")
	}
	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		handleError(err, "从CouchDB请求DB的View,解码JSON部分错误。")
	} else {
		//fmt.Println(string(bytes))
		return bytes
	}

	return nil
}
Exemple #18
0
func (c *Client) Do(req *http.Request, v interface{}) error {

	req.SetBasicAuth(c.key, "")

	resp, err := c.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	err = CheckResponse(resp)
	if err != nil {
		return err
	}

	if v != nil {
		err = json.NewDecoder(resp.Body).Decode(v)

		if err == io.EOF {
			err = nil // ignore EOF errors caused by empty response body
		}
	}

	return err
}
// addAuthentication adds to given HTTP request authentication credentials
func addAuthentication(req *http.Request) {
	if *ghAuthKey != "" {
		req.Header.Set("Authorization", fmt.Sprintf("token %s", *ghAuthKey))
	} else {
		req.SetBasicAuth(*ghUserFl, *ghPassFl)
	}
}
Exemple #20
0
// Execute a request, adds authentication (if auth != nil), and HTTPS cert ignoring.
func (c *Client) doRequest(request *http.Request) ([]byte, error) {
	if c.auth != nil {
		request.SetBasicAuth(c.auth.User, c.auth.Password)
	}
	response, err := c.httpClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return body, err
	}
	if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusPartialContent {
		return nil, fmt.Errorf("request [%#v] failed (%d) %s: %s", request, response.StatusCode, response.Status, string(body))
	}
	if response.StatusCode == http.StatusAccepted {
		var status api.Status
		if err := api.DecodeInto(body, &status); err == nil {
			if status.Status == api.StatusSuccess {
				return body, nil
			} else {
				return nil, &StatusErr{status}
			}
		}
		// Sometimes the server returns 202 even though it completely handled the request.
	}
	return body, err
}
Exemple #21
0
// make an api request
func (c *Client) api(method string, path string, fields url.Values) (body []byte, err error) {
	var req *http.Request
	url := fmt.Sprintf("https://%s/v%d%s", API_ENDPOINT, API_VERSION, path)

	if method == "POST" && fields != nil {
		req, err = http.NewRequest(method, url, strings.NewReader(fields.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	} else {
		if fields != nil {
			url += "?" + fields.Encode()
		}
		req, err = http.NewRequest(method, url, nil)
	}

	if err != nil {
		return
	}
	req.SetBasicAuth("api", c.key)
	rsp, err := c.httpClient.Do(req)
	if err != nil {
		return
	}
	defer rsp.Body.Close()
	body, err = ioutil.ReadAll(rsp.Body)
	if err != nil {
		return
	}
	if rsp.StatusCode < 200 || rsp.StatusCode >= 300 {
		err = fmt.Errorf("mailgun error: %d %s", rsp.StatusCode, body)
	}
	return
}
Exemple #22
0
func Send(method string, url string, content []byte, headers map[string]string, user string, password string) (*http.Response, []byte) {
	var req *http.Request
	var err error

	if content != nil {
		req, err = http.NewRequest(method, url, bytes.NewBuffer(content))
	} else {
		req, err = http.NewRequest(method, url, nil)
	}
	CheckError(err)
	req.Close = true
	if user != "" && password != "" {
		req.SetBasicAuth(user, password)
	}
	if headers != nil {
		for name := range headers {
			req.Header.Set(name, headers[name])
		}
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	CheckError(err)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	return resp, body
}
Exemple #23
0
func setAuthentication(req *http.Request) {
	username := os.Getenv("GITHUB_USERNAME")
	token := os.Getenv("GITHUB_TOKEN")
	if username != "" && token != "" {
		req.SetBasicAuth(username, token)
	}
}
Exemple #24
0
// HTTPPost make a POST request to path which also includes domain, headers are optional
func HTTPPost(path string, data *[]byte, headers [][]string, username, password string) ([]byte, error) {
	var (
		req *http.Request
		err error
	)

	client := &http.Client{Transport: &transport}
	if data == nil {
		req, err = http.NewRequest("POST", path, nil)
	} else {
		req, err = http.NewRequest("POST", path, bytes.NewReader(*data))
	}

	if err != nil {
		return nil, err
	}

	if username != "" && password != "" {
		req.SetBasicAuth(username, password)
	}

	if len(headers) > 0 {
		for i := range headers {
			req.Header.Add(headers[i][0], headers[i][1])
		}
	}
	return makeRequest(client, req)
}
// addAuthHeaders adds basic/bearer auth from the given config (if specified)
// This should be run on any requests not handled by the transport returned from TransportFor(config)
func addAuthHeaders(req *http.Request, clientConfig *restclient.Config) {
	if clientConfig.BearerToken != "" {
		req.Header.Set("Authorization", "Bearer "+clientConfig.BearerToken)
	} else if clientConfig.Username != "" || clientConfig.Password != "" {
		req.SetBasicAuth(clientConfig.Username, clientConfig.Password)
	}
}
Exemple #26
0
func (c *Client) doRequest(method, urlpath string, body []byte) (resp *http.Response, b []byte, err error) {
	var req *http.Request

	if body != nil {
		req, err = http.NewRequest(method, c.Url+urlpath, bytes.NewBuffer(body))
	} else {
		req, err = http.NewRequest(method, c.Url+urlpath, nil)
	}

	if err != nil {
		return
	}

	switch method {
	case "PUT", "POST", "DELETE":
		if len(c.creds.Token) > 0 {
			req.Header.Set("Authorization", "BEARER "+c.creds.Token)
		} else {
			req.SetBasicAuth(c.creds.Username, c.creds.Password)
		}
		break
	default:
		break
	}

	if resp, err = http.DefaultClient.Do(req); err != nil {
		return
	}

	defer resp.Body.Close()

	b, err = ioutil.ReadAll(resp.Body)

	return
}
Exemple #27
0
func ecrImageExists(image *imagename.ImageName, auth docker.AuthConfiguration) (exists bool, err error) {
	var (
		req    *http.Request
		res    *http.Response
		client = &http.Client{}
	)

	uri := fmt.Sprintf("https://%s/v2/%s/manifests/%s", image.Registry, image.Name, image.Tag)

	if req, err = http.NewRequest("GET", uri, nil); err != nil {
		return false, err
	}

	req.SetBasicAuth(auth.Username, auth.Password)

	log.Debugf("Request ECR image %s with basic auth %s:****", uri, auth.Username)

	if res, err = client.Do(req); err != nil {
		return false, fmt.Errorf("Failed to authenticate by realm url %s, error %s", uri, err)
	}
	defer res.Body.Close()

	log.Debugf("Got status %d", res.StatusCode)

	if res.StatusCode == 404 {
		return false, nil
	}

	if res.StatusCode != 200 {
		// TODO: maybe more descriptive error
		return false, fmt.Errorf("GET %s status code %d", uri, res.StatusCode)
	}

	return true, nil
}
Exemple #28
0
func PicarusApi(method string, path string, params url.Values) (map[string]interface{}, error) {
	var err error
	var req *http.Request
	if method == "GET" {
		req, err = http.NewRequest(method, "https://api.picar.us/v0"+path+"?"+params.Encode(), nil)
	} else {
		req, err = http.NewRequest(method, "https://api.picar.us/v0"+path, strings.NewReader(params.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}
	if err != nil {
		return nil, err
	}
	req.SetBasicAuth(picarusEmail, picarusApiKey)
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	fmt.Println(body)
	var v map[string]interface{}
	err = json.Unmarshal(body, &v)
	if err != nil {
		fmt.Println("Json error 1")
		return nil, err
	}
	return v, nil
}
Exemple #29
0
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

}
Exemple #30
0
func (this *Intercom_t) DeleteTag(id uint) (err error) {
	var (
		req    *http.Request
		resp   *http.Response
		client = new(http.Client)
	) //var

	// Create new DELETE request.  Add Tag ID to end of URL
	if req, err = http.NewRequest("DELETE", TAG_DELETE_API_ENDPOINT+strconv.Itoa(int(id)), nil); err != nil {
		return err
	} //if

	// Set authentication and headers
	req.SetBasicAuth(this.AppId, this.ApiKey)
	req.Header.Set("Accept", "application/json")

	// Perform DELETE request
	if resp, err = client.Do(req); err != nil {
		return err
	} //if
	defer resp.Body.Close()

	// Check reponse code and report any errors
	// Intercom sends back a 200 for valid requests
	if resp.StatusCode != 200 {
		return errors.New(resp.Status)
	} //if

	return nil
} //DeleteTag