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


Golang Request.Do方法代码示例

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


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

示例1: post

func (c Client) post(url string, requestData interface{}) []error {

	var errs []error
	req := goreq.Request{
		Method:      "POST",
		Body:        requestData,
		Uri:         url,
		ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
		CookieJar:   c.cookie,
	}
	req.AddHeader("X-Requested-With", "XMLHttpRequest")
	resp, err := req.Do()

	if err != nil {
		errs = append(errs, errors.New(err.Error()))
		log.Fatalln(err.Error())
	}
	defer func() {
		err := resp.Body.Close()
		if err != nil {
			log.Fatal(err)
		}
	}()

	if resp.StatusCode != http.StatusOK {
		errs = append(errs, errors.New("Failed login: status code is "+resp.Status))
	}

	return errs
}
开发者ID:igrybkov,项目名称:leosync,代码行数:30,代码来源:client.go

示例2: Worker

func (m webhooksAlerter) Worker(q chan webhook) {
	for {
		select {
		case webhook := <-q:
			log.Info("Sending webhook alert to %s", webhook.Url)

			req := goreq.Request{
				Uri:         webhook.Url,
				Accept:      "application/json",
				ContentType: "application/json",
				UserAgent:   "Lovebeat",
				Timeout:     10 * time.Second,
				Body:        webhook.Data,
			}

			req.AddHeader("X-Lovebeat", "1")

			_, err := req.Do()
			if err != nil {
				log.Error("Failed to post webhook: %s", err)
			}
		}
	}

}
开发者ID:walmartlabs,项目名称:lovebeat,代码行数:25,代码来源:webhooks.go

示例3: LogRequestFromValidationResult

//LogRequestFromValidationResult unmarshalls the ValidationResult and logs to keen.io
//
//http://api.keen.io/3.0/projects/<project_id>/events/<event_collection>
func (keen *KeenMetrics) LogRequestFromValidationResult(collectionName string, validationResult string) {
	var url = keen.getEndpoint() + collectionName

	var result goiban.ValidationResult
	json.Unmarshal([]byte(validationResult), &result)

	req := goreq.Request{
		Method:      "POST",
		Uri:         url,
		ContentType: "application/json",
		Body:        ValidationResultToEvent(&result),
	}

	req.AddHeader("Authorization", keen.WriteAPIKey)

	res, err := req.Do()

	if err != nil {
		log.Printf("Error while posting stats: %v", err)
		return
	}

	// Close the response body
	if res.Body != nil {
		defer res.Body.Close()
	}

	if collectionName == "Test" {
		log.Printf(url)
		text, _ := res.Body.ToString()
		log.Printf("Response (%v): %v", res.StatusCode, text)
	}

}
开发者ID:cnstudios,项目名称:goiban-service,代码行数:37,代码来源:keen.go

示例4: callURL

func (wa *webAuth) callURL(url, method string, body interface{}, statusCode int, resJSON interface{}) (res *goreq.Response, err error) {
	req := goreq.Request{
		Method:      method,
		Uri:         url,
		Body:        body,
		CookieJar:   wa.jar,
		Accept:      "application/json",
		Host:        "hub.docker.com",
		ContentType: "application/json",
	}.WithHeader("Referer", "https://hub.docker.com/login/")
	if wa.token != "" {
		req = req.WithHeader("Authorization", fmt.Sprintf("JWT %v", wa.token))

	}
	res, err = req.Do()
	if err != nil {
		return res, wrapError(err, fmt.Sprintf("%v to %v", method, url))
	}
	if statusCode != 0 && res.StatusCode != statusCode {
		return res, wrongResponseError(res,
			fmt.Sprintf("%v to %v should have returned a %v", method, url, statusCode))
	}
	if resJSON == nil {
		return
	}
	err = res.Body.FromJsonTo(resJSON)
	if err != nil {
		return res, wrapError(err, fmt.Sprintf("extracting JSON from %v to %v", method, url))
	}
	return
}
开发者ID:saulshanabrook,项目名称:pypi-dockerhub,代码行数:31,代码来源:client.go

示例5: Dispatch

func Dispatch(req goreq.Request) (string, error) {
	// --debug to show only request uri (plus data if POSTing)
	for _, arg := range os.Args {
		if arg == "-d" || arg == "--debug" {
			httpreq, _ := req.NewRequest()
			fmt.Printf("%# v", pretty.Formatter(httpreq))
			os.Exit(0)
		}
	}

	// dispatch
	res, err := req.Do()
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}
	body, err := res.Body.ToString()

	// --prettify
	for _, arg := range os.Args {
		if arg == "--prettify" {
			body, _ = PrettifyJson(body)
		}
	}
	return body, err
}
开发者ID:2008chny,项目名称:axapi-cli-go,代码行数:26,代码来源:dispatcher.go

示例6: sendRequest

// sendRequest is an internal method to send the prepared requests to OpsGenie.
func (cli *OpsGenieClient) sendRequest(req goreq.Request) (*goreq.Response, error) {
	// send the request
	var resp *goreq.Response
	var err error
	for i := 0; i < cli.httpTransportSettings.MaxRetryAttempts; i++ {
		resp, err = req.Do()
		if err == nil && resp.StatusCode < 500 {
			break
		}
		if resp != nil {
			defer resp.Body.Close()
			logging.Logger().Info(fmt.Sprintf("Retrying request [%s] ResponseCode:[%d]. RetryCount: %d", req.Uri, resp.StatusCode, (i + 1)))
		} else {
			logging.Logger().Info(fmt.Sprintf("Retrying request [%s] Reason:[%s]. RetryCount: %d", req.Uri, err.Error(), (i + 1)))
		}
		time.Sleep(timeSleepBetweenRequests * time.Duration(i+1))
	}
	if err != nil {
		message := "Unable to send the request " + err.Error()
		logging.Logger().Warn(message)
		return nil, errors.New(message)
	}
	// check for the returning http status
	statusCode := resp.StatusCode
	if statusCode >= 400 {
		body, err := resp.Body.ToString()
		if err != nil {
			message := "Server response with error can not be parsed " + err.Error()
			logging.Logger().Warn(message)
			return nil, errors.New(message)
		}
		return nil, errorMessage(statusCode, body)
	}
	return resp, nil
}
开发者ID:tablexi,项目名称:opsgenie-go-sdk,代码行数:36,代码来源:client.go

示例7: WriteLogRequest

//WriteLogRequest logs to keen.io
//
// http://api.keen.io/3.0/projects/<project_id>/events/<event_collection>
func (keen *KeenMetrics) WriteLogRequest(collectionName string, iban *goiban.Iban) {
	var url = keen.getEndpoint() + collectionName

	req := goreq.Request{
		Method:      "POST",
		Uri:         url,
		ContentType: "application/json",
		Body:        IbanToEvent(iban),
	}

	req.AddHeader("Authorization", keen.WriteAPIKey)

	res, err := req.Do()

	if err != nil {
		log.Printf("Error while posting stats: %v", err)
		return
	}

	// Close the response body
	if res.Body != nil {
		defer res.Body.Close()
	}

	if collectionName == "Test" {
		log.Printf(url)
		text, _ := res.Body.ToString()
		log.Printf("Response (%v): %v", res.StatusCode, text)
	}

}
开发者ID:cnstudios,项目名称:goiban-service,代码行数:34,代码来源:keen.go

示例8: Worker

func (m slackhookAlerter) Worker(q chan slackhook, cfg *config.ConfigSlackhook) {
	for {

		select {
		case slackhook := <-q:

			var err error

			var context = make(map[string]interface{})
			context["View"] = slackhook.Data.View
			context["Previous"] = slackhook.Data.Previous
			context["Current"] = slackhook.Data.Current

			var doc bytes.Buffer

			err = m.template.Execute(&doc, context)
			if err != nil {
				log.Error("Failed to render template", err)
				return
			}

			req := goreq.Request{
				Method:      "POST",
				Uri:         cfg.Uri,
				Accept:      "*/*",
				ContentType: "application/x-www-form-urlencoded",
				UserAgent:   "Lovebeat",
				Timeout:     10 * time.Second,
				Body:        "payload=" + url.QueryEscape(doc.String()),
			}

			req.AddHeader("X-Lovebeat", "1")

			res, err := req.Do()

			if err != nil {
				log.Error("Failed to post slackhook:%v:", err)
			}

			robots, err := ioutil.ReadAll(res.Body)
			res.Body.Close()

			//it returned a 200 so ignore any error here
			if err != nil {
				log.Error("OK:unreadable response:%v:", err)
			} else if res.StatusCode != http.StatusOK {
				log.Error("NOK:non-200:%d:", res.StatusCode)
			} else {
				log.Info("OK:response:%s:", string(robots))
			}

		}
	}

}
开发者ID:walmartlabs,项目名称:lovebeat,代码行数:55,代码来源:slack.go

示例9: serveValidateServerAuth

func serveValidateServerAuth(backend backend, w http.ResponseWriter, req *http.Request) bool {
	info := backend.GetInfo()
	serverAuth := info.ServerAuth

	if serverAuth == nil {
		return false
	}

	if !strings.HasSuffix(req.URL.Path, SERVER_AUTH_ENDPOINT) {
		return false
	}

	originalPath := strings.Replace(req.URL.Path, SERVER_AUTH_ENDPOINT, "", 1)

	if code := req.URL.Query().Get("code"); code != "" {
		fmt.Printf("Asking server %s about code %s\n", serverAuth.ValidateUrl, code)
		gr := goreq.Request{
			Method:      "POST",
			Uri:         serverAuth.ValidateUrl,
			ContentType: "application/x-www-form-urlencoded",
			Accept:      "application/json",
			UserAgent:   "Undergang/1.0",
			Body:        "code=" + code + "&host=" + req.Host + "&path=" + originalPath,
			Timeout:     5 * time.Second,
		}

		var parsed struct {
			// Not really used.
			AccessToken string `json:"access_token"`
		}

		if ret, err := gr.Do(); err == nil && ret.StatusCode == 200 {
			if ret.Body.FromJsonTo(&parsed) == nil && parsed.AccessToken != "" {
				cookie := &http.Cookie{
					Path:  info.Prefix,
					Name:  SERVER_AUTH_COOKIE,
					Value: NewTimestampSigner(sha1.New()).Sign(getCookieToken(info)),
				}
				http.SetCookie(w, cookie)

				fmt.Println("User authenticated!")
				http.Redirect(w, req, originalPath, 302)
			} else {
				respond(w, req, "Authentication server failure", http.StatusForbidden)
			}
		} else {
			respond(w, req, "Authentication server denied code", http.StatusForbidden)
		}
	} else {
		respond(w, req, "No code provided", http.StatusForbidden)
	}

	return true
}
开发者ID:boivie,项目名称:undergang,代码行数:54,代码来源:server_auth.go

示例10: AuthorizeRequest

func AuthorizeRequest(path string, w http.ResponseWriter, r *http.Request, config Config) (result AuthResponse, err error) {
	if config.AuthURL == "" {
		result = AuthResponse{path, false, false}
		return
	}

	username, password, ok := basicAuth(r)
	if !ok {
		err = errors.New("No HTTP credentials were supplied. Issuing challenge.")
		writeChallenge(w)
		return
	}

	reqBody, err := json.Marshal(map[string]string{"username": username, "password": password, "path": path})
	if err != nil {
		log.Println(err)
		return
	}

	req := goreq.Request{
		Method:      "POST",
		Uri:         config.AuthURL,
		ContentType: "application/json",
		Accept:      "application/json",
		Body:        reqBody,
		Timeout:     3000 * time.Millisecond,
	}

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

	switch res.StatusCode {
	case 200, 201:
		res.Body.FromJsonTo(&result)
	case 204:
		result = AuthResponse{path, false, false}
	case 401, 403:
		body, er := res.Body.ToString()
		if er != nil {
			body = "Unauthorized"
		}

		err = AuthError{res.StatusCode, body}
	case 404:
		err = AuthError{res.StatusCode, "The repository could not be found"}
	default:
		err = AuthError{res.StatusCode, "An unknown error occurred"}
	}

	return
}
开发者ID:divshot,项目名称:gitling,代码行数:53,代码来源:auth.go

示例11: doLookup

func doLookup(host string, path string) *PathInfo {
	uri := externalLookupUrl + "?host=" + url.QueryEscape(host) + "&path=" + url.QueryEscape(path)
	log.Printf("Asking %s about pathinfo\n", uri)
	req := goreq.Request{
		Uri:       uri,
		Accept:    "application/json",
		UserAgent: "Undergang/1.0",
		Timeout:   5 * time.Second,
	}

	if ret, err := req.Do(); err == nil && ret.StatusCode == 200 {
		var path PathInfo
		ret.Body.FromJsonTo(&path)
		return &path
	}
	return nil
}
开发者ID:boivie,项目名称:undergang,代码行数:17,代码来源:external_lookup.go

示例12: Del

func Del() {
	item := DelSolr{}
	item.Del.Query = `title:cyeam.com`
	item.Del.CommitWithin = 1000
	req := goreq.Request{
		Method:      "POST",
		Uri:         "http:///solr/post/update?wt=json",
		ContentType: "application/json",
		Body:        item,
		// Proxy:       "http://127.0.0.1:8888",
	}
	res, err := req.Do()
	if err != nil {
		fmt.Println(err, "*****")
		return
	}
	str, _ := res.Body.ToString()
	fmt.Println("del success", str)

}
开发者ID:ikbear,项目名称:go_code,代码行数:20,代码来源:solr_update.go

示例13: Add

func Add() {
	item := AddSolr{}
	item.Add.Doc.Link = time.Now().String()
	item.Add.Doc.Title = "cyeam.com"
	item.Add.Overwrite = true
	item.Add.CommitWithin = 1000
	req := goreq.Request{
		Method:      "POST",
		Uri:         "http:///solr/post/update?wt=json",
		ContentType: "application/json",
		Body:        item,
		// Proxy:       "http://127.0.0.1:8888",
	}
	res, err := req.Do()
	if err != nil {
		fmt.Println(err, "*****")
		return
	}
	str, _ := res.Body.ToString()
	fmt.Println("add success", str)
}
开发者ID:ikbear,项目名称:go_code,代码行数:21,代码来源:solr_update.go

示例14: MakeRequest

func (c *HTTPClient) MakeRequest(args Args) (http.Header, int, []byte, error) {
	header := make(map[string][]string)

	url, err := url.Parse(c.Host)
	if err != nil {
		return header, 0, []byte{}, errors.NewInvalidHostError(err)
	}
	url.Path = args.Path

	req := goreq.Request{
		Uri:       url.String(),
		Method:    args.Method,
		Body:      args.Body,
		Timeout:   args.Timeout,
		ShowDebug: args.ShowDebug,
	}

	for name, value := range args.Headers {
		for _, v := range value {
			req.AddHeader(name, v)
		}
	}

	resp, err := req.Do()
	if err != nil {
		return header, 0, []byte{}, errors.NewRequestError(err)
	}

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return resp.Header, resp.StatusCode, []byte{}, errors.NewResponseError(err)
	}

	if resp.StatusCode == args.AcceptableCode {
		return resp.Header, resp.StatusCode, respBody, nil
	}

	return resp.Header, resp.StatusCode, respBody, errors.NewResponseError(errors.ErrBadResponse)
}
开发者ID:yonglehou,项目名称:maestro,代码行数:39,代码来源:http_client.go

示例15: MakeRequest

// MakeRequest makes an HTTP request.
// The caller is in charge of closing the response body. ( #todo: is this proper? )
func MakeRequest(req goreq.Request) (*Response, error) {

	start := time.Now()

	resp, err := req.Do()
	if err != nil {
		Metrics.Error(err, "failed to make a request")
		return nil, err
	}

	since := time.Since(start)
	r := &Response{
		Duration: since,
		Response: resp,
	}

	Metrics.TrackResponse(&req, since)

	if resp.StatusCode != 200 {
		Metrics.Error(nil, string(resp.StatusCode))
	}

	return r, nil
}
开发者ID:rexposadas,项目名称:simulate,代码行数:26,代码来源:request.go


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