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


Golang Client.CheckRedirect方法代码示例

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


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

示例1: NewClient

// Create a new client for making http requests against a Jazz server with the provided credentials
// The client will execute the requests authenticating somewhat transparently when needed
func NewClient(userID string, password string) (*Client, error) {
	jClient := &Client{}

	jClient.userID = userID
	jClient.password = password

	options := cookiejar.Options{
		PublicSuffixList: publicsuffix.List,
	}
	jar, err := cookiejar.New(&options)
	if err != nil {
		return nil, err
	}
	client := http.Client{Jar: jar}

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client.Transport = tr
	client.CheckRedirect = nil

	jClient.httpClient = &client

	// Provide a no-op logger as the default
	jClient.Log = log.New(ioutil.Discard, "", log.LstdFlags)

	return jClient, nil
}
开发者ID:sirnewton01,项目名称:gojazz,代码行数:30,代码来源:client.go

示例2: addRedirectFunctionality

func addRedirectFunctionality(client *http.Client, ro *RequestOptions) {
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		if ro.RedirectLimit == 0 {
			ro.RedirectLimit = RedirectLimit
		}

		if len(via) >= ro.RedirectLimit {
			return ErrRedirectLimitExceeded
		}

		if ro.SensitiveHTTPHeaders == nil {
			ro.SensitiveHTTPHeaders = SensitiveHTTPHeaders
		}

		for k, vv := range via[0].Header {
			// Is this a sensitive header?
			if _, found := ro.SensitiveHTTPHeaders[k]; found && !ro.RedirectLocationTrusted {
				continue
			}

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

		return nil
	}
}
开发者ID:wambiri,项目名称:grequests,代码行数:28,代码来源:utils.go

示例3: TestCallbackError

/*-------------------------------------------------------------------------------*/
func TestCallbackError(t *testing.T) {
	port := 8202

	//create controller for all mocks
	ctrl := gomock.NewController(t)
	//check mocks at end
	defer ctrl.Finish()

	//key values
	loser := "you are a loser"
	state := "jabba da hut/:)" //make sure we are decoding correctly by adding strange chars

	pageMapper := NewSimplePageMapper(three, "notused", "notused")
	cookieMapper := NewMockCookieMapper(ctrl)
	serveMux, authConn := createDispatcherWithMocks(ctrl, pageMapper, cookieMapper, nil)
	go func() {
		http.ListenAndServe(fmt.Sprintf(":%d", port), serveMux)
	}()

	//don't care about the cookie name
	cookieMapper.EXPECT().CookieName().Return("my_chef").AnyTimes()

	//just to get the constants
	authConn.EXPECT().ErrorValueName().Return("error")
	authConn.EXPECT().CodeValueName().Return("code")
	authConn.EXPECT().ClientTokenValueName().Return("dontbotherimnotgoingtousethisanyway")

	// this is what happens when google refuses
	v := url.Values{
		//no code!
		"state": []string{state},
		"error": []string{loser},
	}

	returnURLHost := fmt.Sprintf("localhost:%d", port)
	returnURL, err := url.Parse(fmt.Sprintf("http://%s%s?%s", returnURLHost, returl, v.Encode()))
	if err != nil {
		t.Fatalf("Can't understand url: %s", err)
	}

	client := new(http.Client)
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		checkRedirValues(t, "error from goog", via, map[string][]string{
			"path":       []string{req.URL.Path, three},
			"host":       []string{req.URL.Host, returnURLHost},
			"state":      []string{req.URL.Query().Get("state"), ""},
			"error":      []string{req.URL.Query().Get("error"), loser},
			"service":    []string{req.URL.Query().Get("service"), "google"},
			"via url[0]": []string{via[0].URL.String(), returnURL.String()},
		})
		return stopProcessing
	}
	resp := createReqAndDo(t, client, returnURL.String(), nil)
	for k, v := range resp.Header {
		if k == "Set-Cookie" {
			t.Errorf("Should not have set cookie on error: %s\n", v[0])
		}
	}

}
开发者ID:jmcvetta,项目名称:seven5,代码行数:61,代码来源:auth_test.go

示例4: TestLogout

/*-------------------------------------------------------------------------------*/
func TestLogout(t *testing.T) {
	port := 8203

	//create controller for all mocks
	ctrl := gomock.NewController(t)
	//check mocks at end
	defer ctrl.Finish()

	pageMapper := NewSimplePageMapper("notused", "notused", two)
	sm := NewMockSessionManager(ctrl)
	cookieMapper := NewSimpleCookieMapper(appName)
	serveMux, _ := createDispatcherWithMocks(ctrl, pageMapper, cookieMapper, sm)

	sm.EXPECT().Destroy(gomock.Any()).Return(nil)

	go func() {
		http.ListenAndServe(fmt.Sprintf(":%d", port), serveMux)
	}()

	logoutURLHost := fmt.Sprintf("localhost:%d", port)
	logoutURL, err := url.Parse(fmt.Sprintf("http://%s%s", logoutURLHost, "/fart/google/logout"))
	if err != nil {
		t.Fatalf("Can't understand url: %s", err)
	}

	client := new(http.Client)
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		checkRedirValues(t, "error from goog", via, map[string][]string{
			"path":       []string{req.URL.Path, two},
			"host":       []string{req.URL.Host, logoutURLHost},
			"via url[0]": []string{via[0].URL.String(), logoutURL.String()},
		})
		return stopProcessing
	}
	resp := createReqAndDo(t, client, logoutURL.String(),
		&http.Cookie{
			Name:  cookieMapper.CookieName(),
			Value: "forty-series-tires",
		})
	for k, v := range resp.Header {
		if k == "Set-Cookie" {
			p := strings.Split(v[0], ";")
			for _, piece := range p {
				if strings.Index(piece, cookieMapper.CookieName()) != -1 {
					if strings.TrimSpace(piece) != cookieMapper.CookieName()+"=" {
						t.Errorf("Cookie not destroyed properly! '%s'", piece)
					}
				}
				if strings.Index(piece, "Max-Age") != -1 {
					if strings.TrimSpace(piece) != "Max-Age=0" {
						t.Errorf("Cookie not destroyed properly! '%s'", piece)
					}
				}
			}
		}
	}

}
开发者ID:jmcvetta,项目名称:seven5,代码行数:59,代码来源:auth_test.go

示例5: newRawClient

// newRawClient creates an http package Client taking into account both the parameters and package
// variables.
func newRawClient(noredirect bool) *http.Client {
	tr := http.Transport{ResponseHeaderTimeout: ResponseHeaderTimeout, Proxy: http.ProxyFromEnvironment}
	tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: NoCertCheck}
	c := http.Client{Transport: &tr}
	if noredirect {
		c.CheckRedirect = func(*http.Request, []*http.Request) error {
			return fmt.Errorf(noRedirectError)
		}
	}
	return &c
}
开发者ID:lopaka,项目名称:rsc,代码行数:13,代码来源:http.go

示例6: buildRequest

// buildRequest is where most of the magic happens for request processing
func buildRequest(httpMethod, url string, ro *RequestOptions, httpClient *http.Client) (*http.Response, error) {
	if ro == nil {
		ro = &RequestOptions{}
	}
	// Create our own HTTP client

	if httpClient == nil {
		httpClient = BuildHTTPClient(*ro)
	}

	defaultRedirectLimit := 30

	httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		if len(via) > defaultRedirectLimit {
			return fmt.Errorf("%d consecutive requests(redirects)", len(via))
		}
		if len(via) == 0 {
			// No redirects
			return nil
		}
		// mutate the subsequent redirect requests with the first Header
		for key, val := range via[0].Header {
			req.Header[key] = val
		}
		return nil
	}

	// Build our URL

	var (
		err error
	)

	if len(ro.Params) != 0 {
		if url, err = buildURLParams(url, ro.Params); err != nil {
			return nil, err
		}
	}

	// Build the request
	req, err := buildHTTPRequest(httpMethod, url, ro)

	if err != nil {
		return nil, err
	}

	// Do we need to add any HTTP headers or Basic Auth?
	addHTTPHeaders(ro, req)
	addCookies(ro, req)

	return httpClient.Do(req)
}
开发者ID:farwayer,项目名称:grequests,代码行数:53,代码来源:request.go

示例7: httpDl

func httpDl(uri, fileName string) error {
	fmt.Printf("httpDl: %s\n", uri)
	options := cookiejar.Options{
		PublicSuffixList: publicsuffix.List,
	}
	jar, err := cookiejar.New(&options)
	if err != nil {
		return err
	}
	client := http.Client{Jar: jar}
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		dumpReq(req)
		if len(via) >= 10 {
			return fmt.Errorf("too many redirects")
		}
		if len(via) == 0 {
			return nil
		}
		for attr, val := range via[0].Header {
			if _, ok := req.Header[attr]; !ok {
				req.Header[attr] = val
			}
		}
		return nil
	}

	req, err := http.NewRequest("GET", uri, nil)
	// Note: this is crucial. Dropbox will return some html if User-Agent is not defined
	req.Header.Add("User-Agent", "curl/7.43.0")
	dumpReq(req)
	if err != nil {
		return err
	}
	resp, err := client.Do(req)
	dumpResp(resp)
	if err != nil {
		return err
	}
	d, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return fmt.Errorf("httpDl() failed because StatusCode = %d", resp.StatusCode)
	}
	return ioutil.WriteFile(fileName, d, 0644)
}
开发者ID:sumatrapdfreader,项目名称:chmlib,代码行数:48,代码来源:test_dir.go

示例8: randomPage

func randomPage(command *bot.Cmd) (string, error) {
	var redirectNotAllowed = errors.New("redirect")
	redirectedURL := ""

	client := http.Client{}
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		redirectedURL = req.URL.String()
		return redirectNotAllowed
	}

	_, err := client.Get(randomURL)
	if urlError, ok := err.(*url.Error); ok && urlError.Err == redirectNotAllowed {
		return redirectedURL, nil
	}
	return "", err
}
开发者ID:alessandrousseglioviretta,项目名称:plugins,代码行数:16,代码来源:9gag.go

示例9: Test_RedirectHandleRedirects

func Test_RedirectHandleRedirects(t *testing.T) {
	to := "http://www.yfu.de"
	testStore.Add(&redirect{From: "foo", To: to})

	client := new(http.Client)
	var redirectURL *url.URL
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		redirectURL = req.URL
		return errors.New("") // we don't want to carry out the redirect, just get the target URL
	}
	client.Get(server.URL + "/foo")

	if redirectURL == nil {
		t.Fatalf("no redirect observed!")
	}
	if redirectURL.String() != to {
		t.Errorf("expected %q, got %q", to, redirectURL.String())
	}
}
开发者ID:hperl,项目名称:shortlink,代码行数:19,代码来源:redirect_handle_test.go

示例10: init

func init() {
	_, regex, proxy, _ = parseRule(loadRule("proxy.txt"))
	pool.New = func() interface{} {
		client := new(http.Client)
		client.Transport = &http.Transport{
			Proxy: func(req *http.Request) (*url.URL, error) {
				for i, rule := range regex {
					if rule.MatchString(req.URL.Host) {
						return proxy[i], nil
					}
				}
				return nil, nil
			},
		}
		client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
			return disableRedirect
		}
		return client
	}
}
开发者ID:hydra13142,项目名称:examples,代码行数:20,代码来源:proxy.go

示例11: proxyRequest

// proxyRequest does not use the local storage and directly proxies the
// request to the upstream server.
func (ph *Handler) proxyRequest(ctx context.Context,
	w http.ResponseWriter, r *http.Request, vh *types.VirtualHost) {

	//!TODO: use the upstream for the vhost - if the vhost is not a "simple" one
	// or has authentication or is a FS, this will not work
	client := http.Client{}
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		return ErrNoRedirects
	}

	newURL := vh.UpstreamAddress.ResolveReference(r.URL)

	req, err := http.NewRequest("GET", newURL.String(), nil)
	if err != nil {
		log.Printf("[%p] Got error\n %s\n while making request ", r, err)
		return
	}

	for headerName, headerValue := range r.Header {
		req.Header.Set(headerName, strings.Join(headerValue, ","))
	}

	resp, err := client.Do(req)
	if err != nil && err != ErrNoRedirects {
		if urlError, ok := err.(*url.Error); !(ok && urlError.Err == ErrNoRedirects) {
			log.Printf("[%p] Got error\n %s\n while proxying %s to %s", r, err,
				r.URL.String(), newURL.String())
			return
		}
	}

	defer resp.Body.Close()

	respHeaders := w.Header()
	for headerName, headerValue := range resp.Header {
		respHeaders.Set(headerName, strings.Join(headerValue, ","))
	}

	ph.finishRequest(resp.StatusCode, w, r, resp.Body)
}
开发者ID:gitter-badger,项目名称:nedomi,代码行数:42,代码来源:handler.go

示例12: TestResponseURL

func TestResponseURL(t *testing.T) {
	c := new(http.Client)
	req := NewRequest(c)
	url := "http://httpbin.org/get"
	resp, _ := req.Get(url)
	u, _ := resp.URL()
	assert.Equal(t, u.String(), url)

	url = "http://httpbin.org/redirect/3"
	resp, _ = req.Get(url)
	u, _ = resp.URL()
	assert.Equal(t, u.String(), "http://httpbin.org/get")
	url = "http://httpbin.org/redirect/3"

	c.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		return errors.New("redirect")
	}
	resp, _ = req.Get(url)
	u, _ = resp.URL()
	assert.Equal(t, u.String(), "http://httpbin.org/relative-redirect/2")

}
开发者ID:disunbow,项目名称:request,代码行数:22,代码来源:response_test.go

示例13: main

func main() {
	client := http.Client{}
	client.CheckRedirect =
		func(req *http.Request, via []*http.Request) error {
			fmt.Fprintf(os.Stderr, "Redirect: %v\n", req.URL)
			return nil
		}

	var url string
	if len(os.Args) < 2 {
		url = "http://golang.org"
	} else {
		url = os.Args[2]
	}

	page, err := client.Get(url)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
		return
	}

	io.Copy(os.Stdout, page.Body)
	page.Body.Close()
}
开发者ID:brettanomyces,项目名称:ici,代码行数:24,代码来源:wget.go

示例14: TestGoogleLogin

/*-------------------------------------------------------------------------------*/
func TestGoogleLogin(t *testing.T) {
	port := 8201

	//create controller for all mocks
	ctrl := gomock.NewController(t)
	//check mocks at end
	defer ctrl.Finish()

	//the key values
	st := "/frob bob"
	loginurl := "/fart/google/login"
	code := "barfly"
	one := "/1.html"
	sid := "id of session, sid vicious?"

	//authconn is a wrapper around the google auth connector with all mock methods, except AuthURL
	//pm is a mock for testing that we get a call to LoginLandingPage
	pm := NewMockPageMapper(ctrl)
	sm := NewMockSessionManager(ctrl)
	cm := NewSimpleCookieMapper(appName)
	serveMux, authconn := createDispatcherWithMocks(ctrl, pm, cm, sm)

	session := NewMockSession(ctrl)
	session.EXPECT().SessionId().Return(sid).AnyTimes()
	//when we succeed at logging in, it filters down to the session
	sm.EXPECT().Generate(gomock.Any(), gomock.Any(), gomock.Any(), st, code).Return(session, nil)

	//consumed by the google object under test
	deploy := NewMockDeploymentEnvironment(ctrl)
	deploy.EXPECT().RedirectHost(gomock.Any()).Return(fmt.Sprintf("http://localhost:%d", port))

	detail := NewMockOauthClientDetail(ctrl)
	detail.EXPECT().ClientId(gomock.Any()).Return(id)
	detail.EXPECT().ClientSecret(gomock.Any()).Return(seekret)

	//we are testing the AuthURL method, and NOT testing ExchangeForToken() as it requires a
	//real network and a real client id and seekret
	google := NewGoogleOauth2(SCOPE, PROMPT, detail, deploy)

	//these are just accessing the constants, so don't care how many times
	//authconn.EXPECT().Name().Return("google").AnyTimes()
	authconn.EXPECT().StateValueName().Return("state").AnyTimes()
	authconn.EXPECT().ErrorValueName().Return("error").AnyTimes()
	authconn.EXPECT().CodeValueName().Return("code").AnyTimes()
	authconn.EXPECT().ClientTokenValueName().Return("notused").AnyTimes()

	//phase1 is not used by google because of oauth2
	authconn.EXPECT().Phase1(gomock.Any(), gomock.Any()).Return(nil, nil).AnyTimes()

	//this is actually under test, the google.AuthURL method
	authconn.EXPECT().UserInteractionURL(gomock.Any(), st, returl).Return(google.UserInteractionURL(nil, st, returl))

	//this is mocked out because it has the side effect of a network call... we can use the mocks
	//to return an error which we do in the second case
	gomock.InOrder(
		authconn.EXPECT().Phase2("", code).Return(nil, nil),
		authconn.EXPECT().Phase2("", code).Return(nil, badTransport),
	)

	//testing that page mapper's login method gets called during the login process to generate the
	//final web page to land on
	pm.EXPECT().LoginLandingPage(authconn, st, code).Return(one)
	pm.EXPECT().ErrorPage(authconn, gomock.Any()).Return(three)

	go func() {
		http.ListenAndServe(fmt.Sprintf(":%d", port), serveMux)
	}()

	//we need to compute a return url (stage 2) because we expect to see at redir of stage 1
	returnURLBase := fmt.Sprintf("http://localhost:%d%s", port, returl)

	//we need to compute a login url, with a state value to make sure it is propagated all the
	//way through to LoginLandingPage()
	v := url.Values{
		"state": []string{st},
	}
	loginURL, err := url.Parse(fmt.Sprintf("http://localhost:%d%s?%s", port, loginurl, v.Encode()))
	if err != nil {
		t.Fatalf("Can't understand url: %s", err)
	}

	//setup client to not really do redirects so we can look at what's going on
	client := new(http.Client)
	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		checkRedirValues(t, "phase 1 of login", via, map[string][]string{
			"path":       []string{req.URL.Path, GOOGLE_AUTH_URL_PATH},
			"host":       []string{req.URL.Host, GOOGLE_AUTH_URL_HOST[len("https://"):]},
			"scheme":     []string{req.URL.Scheme, "https"},
			"state":      []string{req.URL.Query().Get("state"), st},
			"client_id":  []string{req.URL.Query().Get("client_id"), id},
			"via url[0]": []string{via[0].URL.String(), loginURL.String()},
		})
		if !strings.HasPrefix(req.URL.Query().Get("redirect_uri"), returnURLBase) {
			t.Errorf("Serious problems understanding the callback uri: %s", req.URL.Query().Get("redirect_uri"))
		}
		return stopProcessing
	}

	createReqAndDo(t, client, loginURL.String(), nil)
//.........这里部分代码省略.........
开发者ID:jmcvetta,项目名称:seven5,代码行数:101,代码来源:auth_test.go

示例15: RestrictRedirects

// Wraps a client using WrapCheckRedirect to prevent net-to-Unix redirects.
func RestrictRedirects(c *http.Client) {
	c.CheckRedirect = WrapCheckRedirect(c.CheckRedirect)
}
开发者ID:hlandau,项目名称:degoutils,代码行数:4,代码来源:client.go


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