当前位置: 首页>>代码示例>>Golang>>正文


Golang Request.SetBasicAuth方法代码示例

本文整理汇总了Golang中net/http.Request.SetBasicAuth方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.SetBasicAuth方法的具体用法?Golang Request.SetBasicAuth怎么用?Golang Request.SetBasicAuth使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.Request的用法示例。


在下文中一共展示了Request.SetBasicAuth方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: initRequest

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
}
开发者ID:jameswei,项目名称:goreq,代码行数:34,代码来源:goreq.go

示例2: GetTagList

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
开发者ID:rmulley,项目名称:intercom-go,代码行数:35,代码来源:tag.go

示例3: performRequest

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
}
开发者ID:jk-todo,项目名称:syncthing-inotify,代码行数:25,代码来源:syncwatcher.go

示例4: RoundTrip

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
}
开发者ID:ojacobson,项目名称:docker-registry-client,代码行数:7,代码来源:basictransport.go

示例5: SelectDirector

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)
	}
}
开发者ID:brendandburns,项目名称:getting-started,代码行数:7,代码来源:service-handler.go

示例6: addAuthHeader

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)
	}
}
开发者ID:soniah,项目名称:splunk-golang,代码行数:7,代码来源:http.go

示例7: execHTTPRequest

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
}
开发者ID:mheese,项目名称:journalbeat,代码行数:26,代码来源:client.go

示例8: APICall

// 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
}
开发者ID:Lucius-,项目名称:go-bigip,代码行数:34,代码来源:bigip.go

示例9: QueryDoc

// 根据文档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
}
开发者ID:TYuenCN,项目名称:TYGo,代码行数:32,代码来源:couchdb.go

示例10: GetUUIDFromCouchDB

// 让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
}
开发者ID:TYuenCN,项目名称:TYGo,代码行数:29,代码来源:couchdb.go

示例11: doRequest

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
}
开发者ID:emc-xchallenge,项目名称:nsync,代码行数:32,代码来源:fetcher.go

示例12: ClientRequest

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)
}
开发者ID:cyrrill,项目名称:gopaymill,代码行数:27,代码来源:request.go

示例13: Sign

func (auth basicAuth) Sign(request *http.Request) {
	if request == nil {
		return
	}

	request.SetBasicAuth(auth.Username, auth.Password)
}
开发者ID:gitter-badger,项目名称:alkasir,代码行数:7,代码来源:credentials.go

示例14: DoWithBody

// 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))
	})
}
开发者ID:makyo,项目名称:juju,代码行数:29,代码来源:http.go

示例15: PostMetrics

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
}
开发者ID:Raskal8,项目名称:go-ethereum,代码行数:35,代码来源:client.go


注:本文中的net/http.Request.SetBasicAuth方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。