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


Golang Transport.RoundTrip方法代码示例

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


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

示例1: worker

// Worker
func worker(t *http.Transport, reqChan chan *http.Request, respChan chan Response) {
	for req := range reqChan {
		resp, err := t.RoundTrip(req)
		r := Response{resp, err}
		respChan <- r
	}
}
开发者ID:ramvjai,项目名称:bustracker,代码行数:8,代码来源:ddos_2.go

示例2: login

func login(c *cli.Context) {
	println("echo login,", c.Args().Get(0), c.Args().Get(1))

	// client := &http.Client{}
	reqest, _ := http.NewRequest("GET", "https://passport.baidu.com", nil)

	reqest.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
	reqest.Header.Set("Accept-Encoding", "gzip, deflate, sdch")
	reqest.Header.Set("Accept-Language", "en-US,en;q=0.8,zh-CN;q=0.6,zh-TW;q=0.4")
	reqest.Header.Set("Connection", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36")

	transport := http.Transport{}
	response, err := transport.RoundTrip(reqest)
	if err != nil {
		// t.Fatal(err)
	}
	// // Check if you received the status codes you expect. There may
	// // status codes other than 200 which are acceptable.
	// if resp.StatusCode != 200 && resp.StatusCode != 302 {
	//     t.Fatal("Failed with status", resp.Status)
	// }

	// response,_ := client.Do(reqest)
	if response.StatusCode == 302 {
		// body, _ := ioutil.ReadAll(response.Body)
		// bodystr := string(body);
		fmt.Println("cookie: ", response.Cookies())
	} else {
		fmt.Println("error, code=", response.StatusCode)
	}

	println("login done")
}
开发者ID:stainboy,项目名称:bcfs,代码行数:33,代码来源:login.go

示例3: image

func image(command *bot.Cmd, matches []string) (msg string, err error) {
	client := &http.Client{}
	request, _ := http.NewRequest("GET", fmt.Sprintf(imageURL, url.QueryEscape(matches[1])), nil)
	request.Header.Set("Ocp-Apim-Subscription-Key", bot.Config.Bing)

	response, _ := client.Do(request)
	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)

	var results ImageResults
	json.Unmarshal(body, &results)

	if err != nil {
		return fmt.Sprintf("No results for %s", matches[1]), nil
	}

	if len(results.Value) == 0 {
		return fmt.Sprintf("No results for %s", matches[1]), nil
	}

	pageURL := results.Value[0].ContentURL

	transport := http.Transport{}

	request, _ = http.NewRequest("HEAD", pageURL, nil)
	response, _ = transport.RoundTrip(request)
	pageURL = response.Header.Get("Location")

	output := fmt.Sprintf("Bing | %s | %s", matches[1], pageURL)
	return output, nil
}
开发者ID:0x263b,项目名称:Porygon2,代码行数:31,代码来源:images.go

示例4: RoundTrip

func (r exampleDomainRewriter) RoundTrip(req *http.Request) (resp *http.Response, err error) {
	req.URL.Scheme = "http"
	req.URL.Host = r.RewriteURL.Host

	t := http.Transport{}
	return t.RoundTrip(req)
}
开发者ID:rupakg,项目名称:clcgo,代码行数:7,代码来源:example_test.go

示例5: ServeHTTP

func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
	transport := new(http.Transport)
	h, ok := w.(http.Hijacker)

	if !ok {
		return errors.New("Unable to hijack connection")
	}

	r.Host = srv.addr
	r.URL.Host = r.Host

	if len(r.URL.Scheme) == 0 {
		r.URL.Scheme = "http"
	}

	response, err := transport.RoundTrip(r)

	if err != nil {
		return err
	}

	conn, _, err := h.Hijack()

	if err != nil {
		return err
	}

	defer conn.Close()
	defer response.Body.Close()
	return response.Write(conn)
}
开发者ID:jiakuan,项目名称:livedev,代码行数:31,代码来源:server.go

示例6: proxyToEndpoint

// Proxy the request to the given endpoint, execute observers and middlewares chains
func (l *HttpLocation) proxyToEndpoint(tr *http.Transport, o *Options, endpoint endpoint.Endpoint, req request.Request) (*http.Response, error) {

	a := &request.BaseAttempt{Endpoint: endpoint}

	l.observerChain.ObserveRequest(req)
	defer l.observerChain.ObserveResponse(req, a)
	defer req.AddAttempt(a)

	it := l.middlewareChain.GetIter()
	defer l.unwindIter(it, req, a)

	for v := it.Next(); v != nil; v = it.Next() {
		a.Response, a.Error = v.ProcessRequest(req)
		if a.Response != nil || a.Error != nil {
			// Move the iterator forward to count it again once we unwind the chain
			it.Next()
			log.Errorf("Midleware intercepted request with response=%s, error=%s", a.Response.Status, a.Error)
			return a.Response, a.Error
		}
	}

	// Forward the request and mirror the response
	start := o.TimeProvider.UtcNow()
	a.Response, a.Error = tr.RoundTrip(req.GetHttpRequest())
	a.Duration = o.TimeProvider.UtcNow().Sub(start)
	return a.Response, a.Error
}
开发者ID:irasmaster,项目名称:vulcan,代码行数:28,代码来源:httploc.go

示例7: HandleHttpRequest

func (this *RequestHandler) HandleHttpRequest(transport *http.Transport, address string) (*http.Response, error) {
	this.request.URL.Scheme = "http"
	this.request.URL.Host = address

	if host, _, err := net.SplitHostPort(this.request.RemoteAddr); err == nil {
		xForwardFor := append(this.request.Header["X-Forwarded-For"], host)
		this.request.Header.Set("X-Forwarded-For", strings.Join(xForwardFor, ", "))
	} else {
		log.Println("set X-Forwarded-For error:", err)
	}

	if _, ok := this.request.Header[http.CanonicalHeaderKey("X-Request-Start")]; !ok {
		this.request.Header.Set("X-Request-Start", strconv.FormatInt(time.Now().UnixNano()/1e6, 10))
	}

	this.request.Close = true
	this.request.Header.Del("Connection")

	response, err := transport.RoundTrip(this.request)
	if err != nil {
		return response, err
	}

	for k, vv := range response.Header {
		for _, v := range vv {
			this.response.Header().Add(k, v)
		}
	}

	return response, err
}
开发者ID:hugb,项目名称:beege-controller,代码行数:31,代码来源:request_handler.go

示例8: TestAuthRequest

func TestAuthRequest(t *testing.T) {
	const backendResponse = "I am the backend"
	const backendStatus = 200
	mux := http.NewServeMux()
	mux.HandleFunc(serverConfig.ProtectPath, genericRequestHandlerAuthWrapper)
	mux.HandleFunc(serverConfig.CallbackPath, oauthCallbackHandler)
	server = httptest.NewServer(mux)

	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if len(r.TransferEncoding) > 0 {
			t.Errorf("backend got unexpected TransferEncoding: %v", r.TransferEncoding)
		}
		if r.Header.Get("X-Forwarded-For") == "" {
			t.Errorf("didn't get X-Forwarded-For header")
		}

		w.Header().Set("X-Foo", "bar")
		http.SetCookie(w, &http.Cookie{Name: "flavor", Value: "chocolateChip"})
		w.WriteHeader(backendStatus)
		w.Write([]byte(backendResponse))
	}))
	defer backend.Close()
	backendURL, err := url.Parse(backend.URL)
	if err != nil {
		t.Fatal(err)
	}

	serverConfig.ProxyURL = *backendURL
	// Test request & response
	req, _ := http.NewRequest("GET", server.URL, nil)
	req.Host = "some-name"
	req.Header.Set("Connection", "close")
	req.Close = true

	// Handle the request
	transport := new(http.Transport)
	response, err := transport.RoundTrip(req)
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	if g, e := response.StatusCode, backendStatus; g != e {
		t.Errorf("got response.StatusCode %d; expected %d", g, e)
	}
	bodyBytes, _ := ioutil.ReadAll(response.Body)
	if g, e := string(bodyBytes), backendResponse; g != e {
		t.Errorf("got body %q; expected %q", g, e)
	}
	if g, e := response.Header.Get("X-Foo"), "bar"; g != e {
		t.Errorf("got X-Foo %q; expected %q", g, e)
	}
	if cookie := response.Cookies()[0]; cookie.Name != "flavor" {
		t.Errorf("unexpected cookie %q", cookie.Name)
	}
}
开发者ID:msurdi,项目名称:oauthproxy,代码行数:54,代码来源:server_test.go

示例9: relayHttpRequest

func relayHttpRequest(
	client *http.Client,
	transport *http.Transport,
	request *http.Request,
	responseWriter http.ResponseWriter) {

	// Transform received request struct before using as input to relayed request
	request.Close = false
	request.RequestURI = ""
	for _, key := range hopHeaders {
		request.Header.Del(key)
	}

	// Relay the HTTP request and get the response. Use a client when supplied,
	// otherwise a transport. A client handles cookies and redirects, and a
	// transport does not.
	var response *http.Response
	var err error
	if client != nil {
		response, err = client.Do(request)
	} else {
		response, err = transport.RoundTrip(request)
	}

	if err != nil {
		NoticeAlert("%s", common.ContextError(FilterUrlError(err)))
		forceClose(responseWriter)
		return
	}
	defer response.Body.Close()

	// Relay the remote response headers
	for _, key := range hopHeaders {
		response.Header.Del(key)
	}
	for key, _ := range responseWriter.Header() {
		responseWriter.Header().Del(key)
	}
	for key, values := range response.Header {
		for _, value := range values {
			responseWriter.Header().Add(key, value)
		}
	}

	// Relay the response code and body
	responseWriter.WriteHeader(response.StatusCode)
	_, err = io.Copy(responseWriter, response.Body)
	if err != nil {
		NoticeAlert("%s", common.ContextError(err))
		forceClose(responseWriter)
		return
	}
}
开发者ID:adamkruger,项目名称:psiphon-tunnel-core,代码行数:53,代码来源:httpProxy.go

示例10: Fanout

func Fanout(transport *http.Transport, request *http.Request, endpoints []*Endpoint) (*http.Response, error) {
	body, err := ioutil.ReadAll(request.Body)
	if err != nil {
		return nil, err
	}

	responses := make(chan *http.Response, len(endpoints))
	errs := make(chan error, len(endpoints))

	for _, e := range endpoints {
		url := *request.URL
		url.Scheme = "http"
		url.Host = e.Addr

		req := *request
		req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
		req.URL = &url
		req.Close = true

		request := &req

		go func() {
			response, err := transport.RoundTrip(request)

			if err != nil {
				errs <- err
			} else {
				responses <- response
			}
		}()

		defer transport.CancelRequest(request)
	}

	var fanoutErr error
	var response *http.Response

	for i := 0; i < len(endpoints); i++ {
		select {
		case fanoutErr = <-errs:
		case response = <-responses:
			if response.StatusCode < 400 {
				return response, nil
			}
		}
	}

	if response != nil {
		return response, nil
	}

	return nil, fanoutErr
}
开发者ID:vito,项目名称:fake-diego-release,代码行数:53,代码来源:fanout.go

示例11: RoundRobin

func RoundRobin(transport *http.Transport, request *http.Request, endpoints []*Endpoint) (*http.Response, error) {
	startingPoint := rand.Intn(len(endpoints))

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

	attempts := 0
	i := startingPoint

	for {
		if i == len(endpoints) {
			i = 0
		}

		url := *request.URL
		url.Scheme = "http"
		url.Host = endpoints[i].Addr

		req := *request
		req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
		req.URL = &url
		req.Close = true

		request := &req

		response, err := transport.RoundTrip(request)

		attempts++
		i++

		if attempts == len(endpoints) {
			return response, err
		}

		if err != nil {
			continue
		}

		if response.StatusCode < 400 {
			return response, nil
		}

		response.Body.Close()
	}

	panic("unreachable")
}
开发者ID:vito,项目名称:fake-diego-release,代码行数:49,代码来源:round_robin.go

示例12: BenchmarkExpand

// BenchmarkExpand may consume all open files in server. When running this
// test, you should configure max open files server can open. This can
// commonly be done through "ulimit -n 10000" shell command.
func BenchmarkExpand(b *testing.B) {
	b.StopTimer()
	shortReq, _ := json.Marshal(shortReq{LongURL: "http://www.google.com"})
	req, err := http.NewRequest(
		"POST",
		"http://127.0.0.1:3030/short",
		bytes.NewBuffer(shortReq))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		b.Fatal(err)
	}
	if resp.StatusCode != http.StatusOK {
		b.Fatalf("http response status: %v", resp.StatusCode)
	}

	body, _ := ioutil.ReadAll(resp.Body)
	var shortResp shortResp
	json.Unmarshal(body, &shortResp)
	shortURL := shortResp.ShortURL
	b.StartTimer()

	for i := 0; i < b.N; i++ {
		req, err := http.NewRequest(
			"GET",
			fmt.Sprintf("%v", shortURL),
			nil,
		)
		if err != nil {
			b.Fatal(err)
		}

		transport := http.Transport{}
		resp, err := transport.RoundTrip(req)

		if err != nil {
			b.Fatal(err)
		}

		if resp.StatusCode != http.StatusTemporaryRedirect {
			b.Log(shortURL)
			b.Log(resp.Request.URL)
			b.Fatalf("http response status: %v", resp.StatusCode)
		}
	}
}
开发者ID:ccsblueboy,项目名称:shortme,代码行数:51,代码来源:bench_expand_test.go

示例13: HandleHttpRequest

func (h *RequestHandler) HandleHttpRequest(transport *http.Transport, endpoint *route.Endpoint) (*http.Response, error) {
	h.transport = transport

	h.setupRequest(endpoint)
	h.setupConnection()

	endpointResponse, err := transport.RoundTrip(h.request)
	if err != nil {
		return endpointResponse, err
	}

	h.forwardResponseHeaders(endpointResponse)

	h.setupStickySession(endpointResponse, endpoint)

	return endpointResponse, err
}
开发者ID:nakaji-s,项目名称:gorouter,代码行数:17,代码来源:request_handler.go

示例14: TestUnauthRequest

func TestUnauthRequest(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc(serverConfig.ProtectPath, genericRequestHandler)
	mux.HandleFunc(serverConfig.CallbackPath, oauthCallbackHandler)
	server = httptest.NewServer(mux)

	req, _ := http.NewRequest("GET", server.URL, nil)
	client := new(http.Transport)
	response, err := client.RoundTrip(req)
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	location := response.Header.Get("Location")
	if !strings.HasPrefix(location, "https://accounts.google.com/o/oauth2") {
		t.Errorf("Expected Location header incorrect: %q", location)
	}
}
开发者ID:msurdi,项目名称:oauthproxy,代码行数:17,代码来源:server_test.go

示例15: roundTripWithHTTP

// Do an HTTP roundtrip using the payload data in buf and the request metadata
// in info.
func roundTripWithHTTP(buf []byte, info *RequestInfo) (*http.Response, error) {
	tr := new(http.Transport)
	if info.ProxyURL != nil {
		if info.ProxyURL.Scheme != "http" {
			panic(fmt.Sprintf("don't know how to use proxy %s", info.ProxyURL.String()))
		}
		tr.Proxy = http.ProxyURL(info.ProxyURL)
	}
	req, err := http.NewRequest("POST", info.URL.String(), bytes.NewReader(buf))
	if err != nil {
		return nil, err
	}
	if info.Host != "" {
		req.Host = info.Host
	}
	req.Header.Set("X-Session-Id", info.SessionID)
	return tr.RoundTrip(req)
}
开发者ID:scucoco,项目名称:meek,代码行数:20,代码来源:meek-client.go


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