本文整理汇总了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")
}
}
示例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
}
示例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)
}
示例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)
}
}
}
示例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)
}
}
示例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())
}
}
}
示例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/")
}
}
示例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")
}
}
示例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
}
示例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")
}
示例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
}
示例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())
}
示例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
}
示例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")
}
示例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)
}