當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Response.StatusCode方法代碼示例

本文整理匯總了Golang中net/http.Response.StatusCode方法的典型用法代碼示例。如果您正苦於以下問題:Golang Response.StatusCode方法的具體用法?Golang Response.StatusCode怎麽用?Golang Response.StatusCode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在net/http.Response的用法示例。


在下文中一共展示了Response.StatusCode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestCheckResponseForErrors

func TestCheckResponseForErrors(t *testing.T) {
	var err error
	var resp http.Response

	resp.StatusCode = 300
	_, err = checkResponseForErrors(&resp)
	if err == nil {
		t.Error("should have returned error")
	}

	resp.StatusCode = 503
	_, err = checkResponseForErrors(&resp)
	if err == nil {
		t.Error("should have returned error")
	}

	resp.StatusCode = 404
	resp.Body = ioutil.NopCloser(strings.NewReader(`{"message":"Record Not Found","errors":[{"resource":"Activity","field":"id","code":"invalid"}]}`))
	_, err = checkResponseForErrors(&resp)
	if err == nil {
		t.Error("should have returned error")
	}

	if se, ok := err.(Error); ok {
		if len(se.Errors) == 0 {
			t.Error("Detailed errors not parsed")
		}
	} else {
		t.Error("Should have returned strava error")
	}
}
開發者ID:disastrous-charly,項目名稱:go.strava,代碼行數:31,代碼來源:service_test.go

示例2: Fetch

// FileFetcher's Fetch() implementation
func (this *fileFetcherExtender) Fetch(u *url.URL, userAgent string, headRequest bool) (*http.Response, error) {
	var res *http.Response = new(http.Response)
	var req *http.Request
	var e error

	if req, e = http.NewRequest("GET", u.String(), nil); e != nil {
		panic(e)
	}

	// Prepare the pseudo-request
	req.Header.Add("User-Agent", userAgent)

	// Open the file specified as path in u, relative to testdata/[host]/
	f, e := os.Open(path.Join(FileFetcherBasePath, u.Host, u.Path))
	if e != nil {
		// Treat errors as 404s - file not found
		res.Status = "404 Not Found"
		res.StatusCode = 404
	} else {
		res.Status = "200 OK"
		res.StatusCode = 200
		res.Body = f
	}
	res.Request = req

	return res, e
}
開發者ID:winglechen,項目名稱:gocrawl,代碼行數:28,代碼來源:helper_test.go

示例3: TestOAuth2Provider_Non200Response

func TestOAuth2Provider_Non200Response(t *testing.T) {

	config := &common.Config{
		Map: objx.MSI(
			OAuth2KeyRedirectUrl, OAuth2KeyRedirectUrl,
			OAuth2KeyScope, OAuth2KeyScope,
			OAuth2KeyClientID, OAuth2KeyClientID,
			OAuth2KeySecret, OAuth2KeySecret,
			OAuth2KeyAuthURL, OAuth2KeyAuthURL,
			OAuth2KeyTokenURL, OAuth2KeyTokenURL)}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testProvider := new(test.TestProvider)

	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "text/plain")
	testResponse.StatusCode = 401
	testResponse.Body = ioutil.NopCloser(strings.NewReader("No mate"))

	testTripperFactory.On("NewTripper", common.EmptyCredentials, mock.Anything).Return(testTripper, nil)
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	data := objx.MSI(OAuth2KeyCode, []string{"123"})
	_, err := CompleteAuth(testTripperFactory, data, config, testProvider)

	if assert.Error(t, err) {
		assert.IsType(t, &common.AuthServerError{}, err)
	}

	mock.AssertExpectationsForObjects(t, testTripperFactory.Mock, testTripper.Mock, testProvider.Mock)

}
開發者ID:jmptrader,項目名稱:gomniauth,代碼行數:34,代碼來源:complete_auth_test.go

示例4: TestEventsList

func TestEventsList(t *testing.T) {
	for _, c := range eventsListCases {
		client := NewClient(ClientConfig{APIToken: "0"})
		hc := test.NewHTTPClient()
		client.httpClient = hc

		res := new(http.Response)
		res.Body = ioutil.NopCloser(strings.NewReader(c.Body))
		res.StatusCode = 200
		hc.SetResponseData(res)

		events, _, err := client.EventsList(c.App, c.PaginationOpts)
		if len(hc.Calls) != 1 {
			t.Errorf("expected 1 http request, got %v", len(hc.Calls))
		}
		if len(events) != c.EventsCount {
			t.Errorf("expected %d event, got %v", c.EventsCount, len(events))
		}
		if err != c.Error {
			t.Errorf("expected '%v' error got %v", c.Error, err)
		}

		req := hc.Calls[0]
		if c.ReqURL != "" && req.URL.String() != c.ReqURL {
			t.Errorf("expected request to URL %v, got %v", c.ReqURL, req.URL.String())
		}
		if c.ReqMethod != "" && req.Method != c.ReqMethod {
			t.Errorf("expected request with verb %v, got %v", c.ReqMethod, req.Method)
		}
	}
}
開發者ID:Scalingo,項目名稱:go-scalingo,代碼行數:31,代碼來源:events_test.go

示例5: TestGetUser

func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{"full_name":"their-name","id":"uniqueid","username":"loginname","avatar_url":"http://myface.com/","online":true}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {
		assert.Equal(t, user.Name(), "their-name")
		assert.Equal(t, user.AuthCode(), "")
		assert.Equal(t, user.Nickname(), "loginname")
		assert.Equal(t, user.Email(), "") // doesn't come from soundcloud
		assert.Equal(t, user.AvatarURL(), "http://myface.com/")
		assert.Equal(t, user.Data()["online"], true)
	}

}
開發者ID:chikin14niwa,項目名稱:gomniauth,代碼行數:29,代碼來源:soundcloud_test.go

示例6: TestGetUser

func TestGetUser(t *testing.T) {

	g := New("clientID", "secret", "http://myapp.com/")
	creds := &common.Credentials{Map: objx.MSI()}

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", mock.Anything, g).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{"name":"their-name","id":"uniqueid","login":"loginname","email":"[email protected]","picture":"http://myface.com/","blog":"http://blog.com/"}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	g.tripperFactory = testTripperFactory

	user, err := g.GetUser(creds)

	if assert.NoError(t, err) && assert.NotNil(t, user) {

		assert.Equal(t, user.Name(), "their-name")
		assert.Equal(t, user.AuthCode(), "") // doesn't come from google
		assert.Equal(t, user.Email(), "[email protected]")
		assert.Equal(t, user.AvatarURL(), "http://myface.com/")
		assert.Equal(t, user.Data()["blog"], "http://blog.com/")

		googleCreds := user.ProviderCredentials()[googleName]
		if assert.NotNil(t, googleCreds) {
			assert.Equal(t, "uniqueid", googleCreds.Get(common.CredentialsKeyID).Str())
		}

	}

}
開發者ID:toggl,項目名稱:gomniauth,代碼行數:35,代碼來源:google_test.go

示例7: TestGetUser

func TestGetUser(t *testing.T) {

	testProvider := new(test.TestProvider)
	creds := new(common.Credentials)

	testTripperFactory := new(test.TestTripperFactory)
	testTripper := new(test.TestTripper)
	testTripperFactory.On("NewTripper", creds, testProvider).Return(testTripper, nil)
	testResponse := new(http.Response)
	testResponse.Header = make(http.Header)
	testResponse.Header.Set("Content-Type", "application/json")
	testResponse.StatusCode = 200
	testResponse.Body = ioutil.NopCloser(strings.NewReader(`{"name":"their-name","id":"uniqueid","login":"loginname","email":"[email protected]","avatar_url":"http://myface.com/","blog":"http://blog.com/"}`))
	testTripper.On("RoundTrip", mock.Anything).Return(testResponse, nil)

	client := &http.Client{Transport: testTripper}
	testProvider.On("GetClient", creds).Return(client, nil)

	data, err := Get(testProvider, creds, "endpoint")

	if assert.NoError(t, err) && assert.NotNil(t, data) {

		assert.Equal(t, data["name"], "their-name")
		assert.Equal(t, data["id"], "uniqueid")
		assert.Equal(t, data["login"], "loginname")
		assert.Equal(t, data["email"], "[email protected]")
		assert.Equal(t, data["avatar_url"], "http://myface.com/")
		assert.Equal(t, data["blog"], "http://blog.com/")

	}

}
開發者ID:amencarini,項目名稱:gomniauth,代碼行數:32,代碼來源:get_test.go

示例8: TestRateLimitUpdating

func TestRateLimitUpdating(t *testing.T) {
	var resp http.Response

	resp.StatusCode = 200
	resp.Header = http.Header{"Date": []string{"Tue, 10 Oct 2013 20:11:05 GMT"}, "X-Ratelimit-Limit": []string{"600,30000"}, "X-Ratelimit-Usage": []string{"300,10000"}}
	RateLimiting.updateRateLimits(&resp)

	if RateLimiting.RequestTime.IsZero() {
		t.Errorf("rate limiting should set request time")
	}

	if v := RateLimiting.FractionReached(); v != 0.5 {
		t.Errorf("fraction of rate limit computed incorrectly, got %v", v)
	}

	resp.Header = http.Header{"Date": []string{"Tue, 10 Oct 2013 20:11:05 GMT"}, "X-Ratelimit-Limit": []string{"600,30000"}, "X-Ratelimit-Usage": []string{"300,27000"}}
	RateLimiting.updateRateLimits(&resp)

	if RateLimiting.RequestTime.IsZero() {
		t.Errorf("rate limiting should set request time")
	}

	if v := RateLimiting.FractionReached(); v != 0.9 {
		t.Errorf("fraction of rate limit computed incorrectly, got %v", v)
	}

	// we'll feed it nonsense
	resp.Header = http.Header{"Date": []string{"Tue, 10 Oct 2013 20:11:05 GMT"}, "X-Ratelimit-Limit": []string{"xxx"}, "X-Ratelimit-Usage": []string{"zzz"}}
	RateLimiting.updateRateLimits(&resp)

	if !RateLimiting.RequestTime.IsZero() {
		t.Errorf("nonsense in rate limiting fields should set next reset to zero")
	}
}
開發者ID:disastrous-charly,項目名稱:go.strava,代碼行數:34,代碼來源:ratelimit_test.go

示例9: readFakeResponse

func readFakeResponse(statusCode int, file string, header http.Header) (res http.Response) {
	body, _ := os.Open(file)
	response := http.Response{}
	response.Body = body
	response.Header = header
	response.StatusCode = statusCode
	return response
}
開發者ID:rdrew4,項目名稱:cfops,代碼行數:8,代碼來源:bosh_test.go

示例10: TestHandleHttpResponseReturnsErrOnNon200StatusCode

func TestHandleHttpResponseReturnsErrOnNon200StatusCode(t *testing.T) {
	var response http.Response

	response.StatusCode = 400
	_, err := handleHTTPResponse(&response, nil)

	assertEqual(t, "Non-200 status code received from server: 400", err.Error(), "The returned error was not the expected error")
}
開發者ID:mark-adams,項目名稱:cap-go,代碼行數:8,代碼來源:atom_test.go

示例11: generatePolicyResponse

// Mocks valid http response containing bucket policy from server.
func generatePolicyResponse(resp *http.Response, policy BucketAccessPolicy) (*http.Response, error) {
	policyBytes, err := json.Marshal(policy)
	if err != nil {
		return nil, err
	}
	resp.StatusCode = http.StatusOK
	resp.Body = ioutil.NopCloser(bytes.NewBuffer(policyBytes))
	return resp, nil
}
開發者ID:MirkoDziadzka,項目名稱:restic,代碼行數:10,代碼來源:api-get-policy_test.go

示例12: TestResponse

func TestResponse(t *testing.T) {
	var resp http.Response
	resp.StatusCode = http.StatusOK
	resp.Header = make(http.Header)
	resp.Header["SID"] = []string{"uuid:1337"}
	var buf bytes.Buffer
	resp.Write(&buf)
	t.Logf("%q", buf.String())
}
開發者ID:ronindev,項目名稱:dms,代碼行數:9,代碼來源:dms_test.go

示例13: respFromRecorder

// respFromRecorder builds an http response from a httptest recorder
func respFromRecorder(w *httptest.ResponseRecorder) *http.Response {
	resp := http.Response{}
	resp.StatusCode = w.Code
	resp.Header = w.Header()
	// TODO: fill in the rest of response

	b := w.Body.Bytes()
	resp.Body = ioutil.NopCloser(bytes.NewReader(b))
	return &resp
}
開發者ID:trotha01,項目名稱:snowflake,代碼行數:11,代碼來源:mockflake.go

示例14: TestHandleHttpResponseReturnsErrOnZeroContentLength

func TestHandleHttpResponseReturnsErrOnZeroContentLength(t *testing.T) {
	var response http.Response

	response.StatusCode = 200
	response.ContentLength = 0

	_, err := handleHTTPResponse(&response, nil)

	assertEqual(t, "No content was returned", err.Error(), "The returned error was not the expected error")
}
開發者ID:mark-adams,項目名稱:cap-go,代碼行數:10,代碼來源:atom_test.go

示例15: MakeTestResponseWithBody

func MakeTestResponseWithBody(body string) (*Response, error) {

	testHTTPResponse := new(http.Response)
	testHTTPResponse.Body = ioutil.NopCloser(bytes.NewBufferString(body))
	testHTTPResponse.StatusCode = 200
	testHTTPResponse.Header = make(map[string][]string)

	return NewResponse(GetTestSession(), testHTTPResponse)

}
開發者ID:stretchr,項目名稱:sdk-go,代碼行數:10,代碼來源:helper_test.go


注:本文中的net/http.Response.StatusCode方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。