本文整理匯總了Golang中io/ioutil.NopCloser函數的典型用法代碼示例。如果您正苦於以下問題:Golang NopCloser函數的具體用法?Golang NopCloser怎麽用?Golang NopCloser使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NopCloser函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestValidateResponse
func TestValidateResponse(t *testing.T) {
valid := &http.Response{
Request: &http.Request{},
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(strings.NewReader("OK")),
}
if err := validateResponse(valid); err != nil {
t.Errorf("ValidateResponse with valid response returned error %+v", err)
}
invalid := &http.Response{
Request: &http.Request{},
StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader(`{
"error" : {
"statuscode": 400,
"statusdesc": "Bad Request",
"errormessage": "This is an error"
}
}`)),
}
want := &PingdomError{400, "Bad Request", "This is an error"}
if err := validateResponse(invalid); !reflect.DeepEqual(err, want) {
t.Errorf("ValidateResponse with invalid response returned %+v, want %+v", err, want)
}
}
示例2: RoundTrip
// Map the Path into Content based on FileContent.Name
func (v *VirtualRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
res := &http.Response{Proto: "HTTP/1.0",
ProtoMajor: 1,
Header: make(http.Header),
Close: true,
}
full := req.URL.String()
for urlPrefix, statusCode := range v.errorURLS {
if strings.HasPrefix(full, urlPrefix) {
res.Status = fmt.Sprintf("%d Error", statusCode)
res.StatusCode = statusCode
res.ContentLength = 0
res.Body = ioutil.NopCloser(strings.NewReader(""))
return res, nil
}
}
for _, fc := range v.contents {
if fc.Name == req.URL.Path {
res.Status = "200 OK"
res.StatusCode = http.StatusOK
res.ContentLength = int64(len(fc.Content))
res.Body = ioutil.NopCloser(strings.NewReader(fc.Content))
return res, nil
}
}
res.Status = "404 Not Found"
res.StatusCode = http.StatusNotFound
res.ContentLength = 0
res.Body = ioutil.NopCloser(strings.NewReader(""))
return res, nil
}
示例3: HandleStringReader
// Will receive an input stream which would convert the response to utf-8
// The given function must close the reader r, in order to close the response body.
func HandleStringReader(f func(r io.Reader, ctx *goproxy.ProxyCtx) io.Reader) goproxy.RespHandler {
return goproxy.FuncRespHandler(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
if ctx.Error != nil {
return nil
}
charsetName := ctx.Charset()
if charsetName == "" {
charsetName = "utf-8"
}
if strings.ToLower(charsetName) != "utf-8" {
r, err := charset.NewReader(charsetName, resp.Body)
if err != nil {
ctx.Warnf("Cannot convert from %v to utf-8: %v", charsetName, err)
return resp
}
tr, err := charset.TranslatorTo(charsetName)
if err != nil {
ctx.Warnf("Can't translate to %v from utf-8: %v", charsetName, err)
return resp
}
if err != nil {
ctx.Warnf("Cannot translate to %v: %v", charsetName, err)
return resp
}
newr := charset.NewTranslatingReader(f(r, ctx), tr)
resp.Body = &readFirstCloseBoth{ioutil.NopCloser(newr), resp.Body}
} else {
//no translation is needed, already at utf-8
resp.Body = &readFirstCloseBoth{ioutil.NopCloser(f(resp.Body, ctx)), resp.Body}
}
return resp
})
}
示例4: TestConfigureAcessToken
func TestConfigureAcessToken(t *testing.T) {
t.Parallel()
h, _ := newAppHarness(t)
defer h.Stop()
c := configureCmd{login: login{tokenReader: strings.NewReader("")}}
h.env.In = ioutil.NopCloser(strings.NewReader("token\n"))
ensure.Nil(t, c.accountKey(h.env))
ensure.DeepEqual(
t,
h.Out.String(),
`
Input your account key or press enter to generate a new one.
Account Key: Successfully stored credentials.
`)
h.env.In = ioutil.NopCloser(strings.NewReader("email\ninvalid\n"))
ensure.Err(t, c.accountKey(h.env), regexp.MustCompile("Please try again"))
ensure.DeepEqual(t,
h.Err.String(),
`Sorry, the account key you provided is not valid.
Please follow instructions at https://www.parse.com/account_keys to generate a new account key.
`,
)
}
示例5: TestTriggerHooksUpdate
func TestTriggerHooksUpdate(t *testing.T) {
t.Parallel()
h := newTriggersHarness(t)
var tr triggerHooksCmd
h.env.In =
ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/_foo/beforeSave\n"))
ensure.Nil(t, tr.triggerHooksUpdate(h.env, nil))
ensure.DeepEqual(t,
h.Out.String(),
`Please enter following details about the trigger webhook
Class name: Trigger name: URL: https://Successfully update the "beforeSave" trigger for class "foo" to point to "https://api.example.com/_foo/beforeSave"
`)
ensure.DeepEqual(t, h.Err.String(), "WARNING: beforeSave trigger already exists for class: foo\n")
h.Out.Reset()
h.Err.Reset()
h.env.In =
ioutil.NopCloser(strings.NewReader("bar\nafterSave\napi.example.com/_bar/afterSave\n"))
ensure.Nil(t, tr.triggerHooksUpdate(h.env, nil))
ensure.DeepEqual(t,
h.Out.String(),
`Please enter following details about the trigger webhook
Class name: Trigger name: URL: https://Successfully update the "afterSave" trigger for class "bar" to point to "https://api.example.com/_bar/afterSave"
`)
ensure.DeepEqual(t, h.Err.String(), "")
}
示例6: TestProjectType
func TestProjectType(t *testing.T) {
t.Parallel()
h := parsecli.NewHarness(t)
defer h.Stop()
h.MakeEmptyRoot()
ensure.Nil(t, parsecli.CloneSampleCloudCode(h.Env, false))
c := &configureCmd{}
err := c.projectType(h.Env, []string{"1", "2"})
ensure.Err(t, err, regexp.MustCompile("only an optional project type argument is expected"))
h.Env.In = ioutil.NopCloser(strings.NewReader("invalid\n"))
err = c.projectType(h.Env, nil)
ensure.StringContains(t, h.Err.String(), "Invalid selection. Please enter a number")
ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again."))
h.Err.Reset()
h.Out.Reset()
h.Env.In = ioutil.NopCloser(strings.NewReader("0\n"))
err = c.projectType(h.Env, nil)
ensure.StringContains(t, h.Err.String(), "Please enter a number between 1 and")
ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again."))
h.Err.Reset()
h.Out.Reset()
h.Env.In = ioutil.NopCloser(strings.NewReader("1\n"))
err = c.projectType(h.Env, nil)
ensure.StringContains(t, h.Out.String(), "Successfully set project type to: parse")
ensure.Nil(t, err)
}
示例7: TestConfigureAcessToken
func TestConfigureAcessToken(t *testing.T) {
t.Parallel()
h, _ := newAppHarness(t)
defer h.Stop()
c := configureCmd{login: login{tokenReader: strings.NewReader("")}}
h.env.In = ioutil.NopCloser(strings.NewReader("n\ntoken\n"))
ensure.Nil(t, c.accessToken(h.env))
ensure.DeepEqual(t,
h.Out.String(),
`Please enter an access token if you already generated it.
If you do not have an access token or would like to generate a new one,
please type: "y" to open the browser or "n" to continue: Access Token: Successfully stored credentials.
`,
)
h.env.In = ioutil.NopCloser(strings.NewReader("n\nemail\ninvalid\n"))
ensure.Err(t, c.accessToken(h.env), regexp.MustCompile("Please try again"))
ensure.DeepEqual(t,
h.Err.String(),
`Sorry, the access token you provided is not valid.
Please follow instructions at https://www.parse.com/account_keys to generate a new access token.
`,
)
}
示例8: DoesntChangeReadsOfAppropriateSize
func (t *RandomReaderTest) DoesntChangeReadsOfAppropriateSize() {
t.object.Size = 1 << 40
const readSize = 2 * minReadSize
// Simulate an existing reader at a mismatched offset.
t.rr.wrapped.reader = ioutil.NopCloser(strings.NewReader("xxx"))
t.rr.wrapped.cancel = func() {}
t.rr.wrapped.start = 2
t.rr.wrapped.limit = 5
// The bucket should be asked to read readSize bytes.
r := strings.NewReader(strings.Repeat("x", readSize))
rc := ioutil.NopCloser(r)
ExpectCall(t.bucket, "NewReader")(
Any(),
AllOf(rangeStartIs(1), rangeLimitIs(1+readSize))).
WillOnce(Return(rc, nil))
// Call through.
buf := make([]byte, readSize)
t.rr.ReadAt(buf, 1)
// Check the state now.
ExpectEq(1+readSize, t.rr.wrapped.limit)
}
示例9: TestFindIDInConfigurationsPayload
func TestFindIDInConfigurationsPayload(t *testing.T) {
const (
searchedName = "search-for-this-name"
expected = "The-42-id"
)
assert := assert.New(t)
c := Client{}
payload := fmt.Sprintf(
`[{"dataset_id": "1-2-3", "metadata": {"name": "test"}}, {"dataset_id": "The-42-id", "metadata": {"name": "%s"}}]`,
searchedName,
)
id, err := c.findIDInConfigurationsPayload(
ioutil.NopCloser(bytes.NewBufferString(payload)), searchedName,
)
assert.NoError(err)
assert.Equal(expected, id)
id, err = c.findIDInConfigurationsPayload(
ioutil.NopCloser(bytes.NewBufferString(payload)), "it will not be found",
)
assert.Equal(errConfigurationNotFound, err)
id, err = c.findIDInConfigurationsPayload(
ioutil.NopCloser(bytes.NewBufferString("invalid { json")), "",
)
assert.Error(err)
}
示例10: TestParseError
func (cs *clientSuite) TestParseError(c *check.C) {
resp := &http.Response{
Status: "404 Not Found",
}
err := client.ParseErrorInTest(resp)
c.Check(err, check.ErrorMatches, `server error: "404 Not Found"`)
h := http.Header{}
h.Add("Content-Type", "application/json")
resp = &http.Response{
Status: "400 Bad Request",
Header: h,
Body: ioutil.NopCloser(strings.NewReader(`{
"status-code": 400,
"type": "error",
"result": {
"message": "invalid"
}
}`)),
}
err = client.ParseErrorInTest(resp)
c.Check(err, check.ErrorMatches, "invalid")
resp = &http.Response{
Status: "400 Bad Request",
Header: h,
Body: ioutil.NopCloser(strings.NewReader("{}")),
}
err = client.ParseErrorInTest(resp)
c.Check(err, check.ErrorMatches, `server error: "400 Bad Request"`)
}
示例11: DecompressStream
func DecompressStream(archive io.Reader) (io.ReadCloser, error) {
buf := make([]byte, 10)
totalN := 0
for totalN < 10 {
n, err := archive.Read(buf[totalN:])
if err != nil {
if err == io.EOF {
return nil, fmt.Errorf("Tarball too short")
}
return nil, err
}
totalN += n
utils.Debugf("[tar autodetect] n: %d", n)
}
compression := DetectCompression(buf)
wrap := io.MultiReader(bytes.NewReader(buf), archive)
switch compression {
case Uncompressed:
return ioutil.NopCloser(wrap), nil
case Gzip:
return gzip.NewReader(wrap)
case Bzip2:
return ioutil.NopCloser(bzip2.NewReader(wrap)), nil
case Xz:
return xzDecompress(wrap)
default:
return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
}
}
示例12: TestTransformResponse
func TestTransformResponse(t *testing.T) {
invalid := []byte("aaaaa")
uri, _ := url.Parse("http://localhost")
testCases := []struct {
Response *http.Response
Data []byte
Created bool
Error bool
}{
{Response: &http.Response{StatusCode: 200}, Data: []byte{}},
{Response: &http.Response{StatusCode: 201}, Data: []byte{}, Created: true},
{Response: &http.Response{StatusCode: 199}, Error: true},
{Response: &http.Response{StatusCode: 500}, Error: true},
{Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid},
{Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid},
}
for i, test := range testCases {
r := NewRequest(nil, "", uri, testapi.Codec())
if test.Response.Body == nil {
test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
}
response, created, err := r.transformResponse(test.Response, &http.Request{})
hasErr := err != nil
if hasErr != test.Error {
t.Errorf("%d: unexpected error: %f %v", i, test.Error, err)
}
if !(test.Data == nil && response == nil) && !reflect.DeepEqual(test.Data, response) {
t.Errorf("%d: unexpected response: %#v %#v", i, test.Data, response)
}
if test.Created != created {
t.Errorf("%d: expected created %f, got %f", i, test.Created, created)
}
}
}
示例13: TestRequestWrite
func TestRequestWrite(t *testing.T) {
for i := range reqWriteTests {
tt := &reqWriteTests[i]
if tt.Body != nil {
tt.Req.Body = ioutil.NopCloser(bytes.NewBuffer(tt.Body))
}
var braw bytes.Buffer
err := tt.Req.Write(&braw)
if err != nil {
t.Errorf("error writing #%d: %s", i, err)
continue
}
sraw := braw.String()
if sraw != tt.Raw {
t.Errorf("Test %d, expecting:\n%s\nGot:\n%s\n", i, tt.Raw, sraw)
continue
}
if tt.Body != nil {
tt.Req.Body = ioutil.NopCloser(bytes.NewBuffer(tt.Body))
}
var praw bytes.Buffer
err = tt.Req.WriteProxy(&praw)
if err != nil {
t.Errorf("error writing #%d: %s", i, err)
continue
}
sraw = praw.String()
if sraw != tt.RawProxy {
t.Errorf("Test Proxy %d, expecting:\n%s\nGot:\n%s\n", i, tt.RawProxy, sraw)
continue
}
}
}
示例14: SendHandler
// SendHandler is a request handler to send service request using HTTP client.
func SendHandler(r *Request) {
var err error
r.HTTPResponse, err = r.Service.Config.HTTPClient.Do(r.HTTPRequest)
if err != nil {
// Capture the case where url.Error is returned for error processing
// response. e.g. 301 without location header comes back as string
// error and r.HTTPResponse is nil. Other url redirect errors will
// comeback in a similar method.
if e, ok := err.(*url.Error); ok {
if s := reStatusCode.FindStringSubmatch(e.Error()); s != nil {
code, _ := strconv.ParseInt(s[1], 10, 64)
r.HTTPResponse = &http.Response{
StatusCode: int(code),
Status: http.StatusText(int(code)),
Body: ioutil.NopCloser(bytes.NewReader([]byte{})),
}
return
}
}
if r.HTTPRequest == nil {
// Add a dummy request response object to ensure the HTTPResponse
// value is consistent.
r.HTTPResponse = &http.Response{
StatusCode: int(0),
Status: http.StatusText(int(0)),
Body: ioutil.NopCloser(bytes.NewReader([]byte{})),
}
}
// Catch all other request errors.
r.Error = apierr.New("RequestError", "send request failed", err)
r.Retryable.Set(true) // network errors are retryable
}
}
示例15: TestGetResponseCorruptedRequestResponsePair
func TestGetResponseCorruptedRequestResponsePair(t *testing.T) {
RegisterTestingT(t)
server, dbClient := testTools(200, `{'message': 'here'}`)
defer server.Close()
requestBody := []byte("fizz=buzz")
body := ioutil.NopCloser(bytes.NewBuffer(requestBody))
req, err := http.NewRequest("POST", "http://capture_body.com", body)
Expect(err).To(BeNil())
_, err = dbClient.captureRequest(req)
Expect(err).To(BeNil())
fp := matching.GetRequestFingerprint(req, requestBody, false)
dbClient.RequestCache.Set([]byte(fp), []byte("you shall not decode me!"))
// repeating process
bodyNew := ioutil.NopCloser(bytes.NewBuffer(requestBody))
reqNew, err := http.NewRequest("POST", "http://capture_body.com", bodyNew)
Expect(err).To(BeNil())
requestDetails, err := models.NewRequestDetailsFromHttpRequest(reqNew)
Expect(err).To(BeNil())
response, err := dbClient.getResponse(reqNew, requestDetails)
Expect(err).ToNot(BeNil())
Expect(response).To(BeNil())
}