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


Golang ioutil.ReadAll函数代码示例

本文整理汇总了Golang中io/ioutil.ReadAll函数的典型用法代码示例。如果您正苦于以下问题:Golang ReadAll函数的具体用法?Golang ReadAll怎么用?Golang ReadAll使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: cget

func (c *Conn) cget(name string) (data []byte, err error) {
	cache := filepath.Join(c.cache, name)
	f, err := os.Open(cache)
	if err == nil {
		defer f.Close()
		return ioutil.ReadAll(f)
	}
	if altCache := c.altCachePath(name); altCache != "" {
		f, err := os.Open(altCache)
		if err == nil {
			defer f.Close()
			return ioutil.ReadAll(f)
		}
	}

	data, err = c.bget(name)
	if err != nil {
		return nil, err
	}

	dir, _ := filepath.Split(cache)
	os.MkdirAll(dir, 0700)
	ioutil.WriteFile(cache, data, 0600)
	return data, nil
}
开发者ID:amrhassan,项目名称:rsc,代码行数:25,代码来源:arq.go

示例2: SetUpTest

func (s *archiveDataSuite) SetUpTest(c *gc.C) {
	s.IsolationSuite.SetUpTest(c)

	meta, err := backups.NewMetadataJSONReader(bytes.NewBufferString(`{` +
		`"ID":"20140909-115934.asdf-zxcv-qwe",` +
		`"Checksum":"123af2cef",` +
		`"ChecksumFormat":"SHA-1, base64 encoded",` +
		`"Size":10,` +
		`"Stored":"0001-01-01T00:00:00Z",` +
		`"Started":"2014-09-09T11:59:34Z",` +
		`"Finished":"2014-09-09T12:00:34Z",` +
		`"Notes":"",` +
		`"Environment":"asdf-zxcv-qwe",` +
		`"Machine":"0",` +
		`"Hostname":"myhost",` +
		`"Version":"1.21-alpha3"` +
		`}` + "\n"))
	c.Assert(err, jc.ErrorIsNil)

	archiveFile := s.newArchiveFile(c, meta)
	compressed, err := ioutil.ReadAll(archiveFile)
	c.Assert(err, jc.ErrorIsNil)
	gzr, err := gzip.NewReader(bytes.NewBuffer(compressed))
	c.Assert(err, jc.ErrorIsNil)
	data, err := ioutil.ReadAll(gzr)
	c.Assert(err, jc.ErrorIsNil)

	s.archiveFile = bytes.NewBuffer(compressed)
	s.data = data
	s.meta = meta
}
开发者ID:howbazaar,项目名称:juju,代码行数:31,代码来源:archive_data_test.go

示例3: TestPurge

func TestPurge(t *testing.T) {
	appId := config.ApplicationId
	dataPath := "/resin-data/" + appId

	if err := ioutil.WriteFile(dataPath+"/test", []byte("test"), 0777); err != nil {
		t.Fatal("Could not create test file for purge")
	} else if request, err := http.NewRequest("POST", supervisorAddress+"/v1/purge?apikey=bananas", strings.NewReader(`{"appId": "`+appId+`"}`)); err != nil {
		t.Fatal(err)
	} else {
		request.Header.Set("Content-Type", "application/json")
		response, err := http.DefaultClient.Do(request)
		defer response.Body.Close()
		if err != nil {
			t.Fatal(err)
		} else if response.StatusCode != http.StatusOK {
			t.Errorf("Expected 200, got %d", response.StatusCode)
			if contents, err := ioutil.ReadAll(response.Body); err != nil {
				t.Fatal(err)
			} else {
				t.Fatalf("Response: %s", contents)
			}
		} else {
			if contents, err := ioutil.ReadAll(response.Body); err != nil {
				t.Fatal(err)
			} else if !strings.EqualFold(string(contents), `{"Data":"OK","Error":""}`) {
				t.Errorf("Purge response didn't match the expected JSON, got: %s", contents)
			}
			if dirContents, err := ioutil.ReadDir(dataPath); err != nil {
				t.Errorf("Could not read the data path after purge: %s", err)
			} else if len(dirContents) > 0 {
				t.Error("Data directory not empty after purge")
			}
		}
	}
}
开发者ID:rpio,项目名称:resin-supervisor,代码行数:35,代码来源:super_test.go

示例4: readBody

func readBody(contentEncoding string, body io.Reader) ([]byte, error) {
	var err error
	result := []byte{}
	if contentEncoding == "gzip" {
		reader, err := gzip.NewReader(body)
		if err != nil {
			return result, werrors.NewDetails(ErrReadGZipResponse, err)
		}
		result, err = ioutil.ReadAll(reader)
		if err == nil {
			err = reader.Close()
		} else {
			_ = reader.Close()
		}
		if err != nil {
			return result, werrors.NewDetails(ErrReadGZipResponse, err)
		}
	} else if contentEncoding == "identity" || contentEncoding == "" {
		result, err = ioutil.ReadAll(body)
		if err != nil {
			return result, werrors.NewDetails(ErrReadResponse, err)
		}
	} else {
		return result, werrors.NewFields(ErrUnknownContentEncoding, zap.String("encoding", contentEncoding))
	}

	return result, nil
}
开发者ID:ReanGD,项目名称:go-web-search,代码行数:28,代码来源:body_parser.go

示例5: TestStacktracing

func TestStacktracing(test *testing.T) {
	logBuffer := new(bytes.Buffer)
	logger := &Logger{
		Prefix:    "slogger.logger_test",
		Appenders: []Appender{NewStringAppender(logBuffer)},
	}

	_, err := addZero(6, 0, logger)
	if err != nil {
		logger.Stackf(WARN, err, "Had an illegal argument to addZero. %d", 0)
	}
	logOutput, _ := ioutil.ReadAll(logBuffer)
	if len(logOutput) > 0 {
		test.Errorf("Did not expect any log messages from this first call.")
	}

	_, err = addZero(5, 2, logger)
	if err != nil {
		logger.Stackf(WARN, err, "Had an illegal argument to addZero. %d", 2)
	}
	logOutput, _ = ioutil.ReadAll(logBuffer)
	if len(logOutput) == 0 {
		test.Errorf("Expected a log message when adding 2.")
	}

	_, err = addZero(-8, -4, logger)
	if err != nil {
		logger.Stackf(WARN, err, "Had an illegal argument to addZero. %d", -4)
	}
	logOutput, _ = ioutil.ReadAll(logBuffer)
	if len(logOutput) == 0 {
		test.Errorf("Expected a log message when adding -4.")
	}
}
开发者ID:louisaberger,项目名称:slogger,代码行数:34,代码来源:logger_test.go

示例6: TestUnCompressed

func TestUnCompressed(t *testing.T) {
	assert := assert.New(t)
	// SELECT repeat("a", 50)
	before := `
09 00 00 00 03 53 45 4c 45 43 54 20 31                ....SELECT 1
`
	after := `
0d 00 00 00 00 00 00 09    00 00 00 03 53 45 4c 45    ............SELE
43 54 20 31                                           CT 1
`
	_, _ = before, after

	buf := bytes.NewBufferString("")
	buf.Write(DecodeDump(after))

	r := NewCompressedReader(buf)
	b, err := ioutil.ReadAll(r)
	assert.NoError(err)
	assert.EqualValues(DecodeDump(before), b)

	// write and read again
	w := NewCompressedWriter(buf)
	_, err = w.Write(DecodeDump(before))
	assert.NoError(err)
	b, err = ioutil.ReadAll(r)
	assert.NoError(err)
	assert.EqualValues(DecodeDump(before), b)
}
开发者ID:no2key,项目名称:myfacility,代码行数:28,代码来源:compress_test.go

示例7: get

func (c *Client) get(fullUrl string, query string) (string, error) {
	getUrl, err := url.Parse(fullUrl)
	if err != nil {
		return "", fmt.Errorf("pusher: GET failed: %s", err)
	}

	getUrl.Scheme = c.scheme()
	getUrl.RawQuery = query

	resp, err := HttpClient.Get(getUrl.String())
	if err != nil {
		return "", fmt.Errorf("pusher: GET failed: %s", err)
	}

	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		b, _ := ioutil.ReadAll(resp.Body)
		return "", fmt.Errorf("pusher: GET failed: %s", b)
	}

	fullBody, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return "", fmt.Errorf("pusher: GET failed: %s", err)
	}

	return string(fullBody), nil
}
开发者ID:henrikhodne,项目名称:pusher,代码行数:29,代码来源:client.go

示例8: handleHTTP

// handle http req & response to netplugin
func (cniApp *cniAppInfo) handleHTTP(url string, jsonReq *bytes.Buffer) int {

	cniLog.Infof("http POST url: %s data: %v", url, jsonReq)
	httpResp, err := cniApp.httpClient.Post(url, "application/json", jsonReq)
	if err != nil {
		return cniApp.sendCniErrorResp("failed to get response from netplugin :" + err.Error())
	}
	defer httpResp.Body.Close()

	switch httpResp.StatusCode {

	case http.StatusOK:
		cniLog.Infof("received http OK reponse from netplugin")
		info, err := ioutil.ReadAll(httpResp.Body)
		if err != nil {
			return cniApp.sendCniErrorResp("failed to read success response from netplugin :" + err.Error())
		}
		return cniApp.sendCniResp(info, cniapi.CniStatusSuccess)

	case http.StatusInternalServerError:
		cniLog.Infof("received http error reponse from netplugin")
		info, err := ioutil.ReadAll(httpResp.Body)
		if err != nil {
			return cniApp.sendCniErrorResp("failed to read error response from netplugin :" + err.Error())
		}
		return cniApp.sendCniResp(info, cniapi.CniStatusErrorUnsupportedField)

	default:
		cniLog.Infof("received unknown error from netplugin")
		return cniApp.sendCniErrorResp("error response from netplugin: " + http.StatusText(httpResp.StatusCode))
	}
}
开发者ID:abhinandanpb,项目名称:netplugin,代码行数:33,代码来源:cniplugin.go

示例9: captureOutputs

func captureOutputs(f func()) (stdout, stderr []byte) {
	oldStdout := os.Stdout
	oldStderr := os.Stderr

	rOut, wOut, _ := os.Pipe()
	rErr, wErr, _ := os.Pipe()

	os.Stdout = wOut
	os.Stderr = wErr

	resetLoggers()
	f()

	outC := make(chan []byte)
	errC := make(chan []byte)

	go func() {
		bytes, _ := ioutil.ReadAll(rOut)
		outC <- bytes

		bytes, _ = ioutil.ReadAll(rErr)
		errC <- bytes
	}()

	wOut.Close()
	wErr.Close()

	stdout = <-outC
	stderr = <-errC

	os.Stdout = oldStdout
	os.Stderr = oldStderr
	return
}
开发者ID:nicregez,项目名称:bosh,代码行数:34,代码来源:logger_test.go

示例10: GetItem

func GetItem(getItemRequest GetItemRequest, userId string,
	userSecert string, region string) (map[string]Attribute, error) {

	query, err := json.Marshal(getItemRequest)
	if err != nil {
		return nil, err
	}

	response, err := makeRequest("http://dynamodb."+region+".amazonaws.com/",
		string(query[:]), "GetItem", userId, userSecert, region)

	if err != nil {
		return nil, err
	}

	defer response.Body.Close()

	if response.StatusCode != 200 {
		content, _ := ioutil.ReadAll(response.Body)
		var errorResponse aws.ErrorStruct
		json.Unmarshal(content, &errorResponse)
		return nil, errors.New("Unable to register device. " + errorResponse.Type + ": " + errorResponse.Message)
	} else {
		content, _ := ioutil.ReadAll(response.Body)
		items := make(map[string]map[string]Attribute)
		json.Unmarshal(content, &items)
		return items["Item"], nil
	}

}
开发者ID:usmanismail,项目名称:gpns,代码行数:30,代码来源:dynamoclient.go

示例11: ScanForItems

func ScanForItems(scanRequest ScanRequest, userId string,
	userSecert string, region string) (*ScanResponse, error) {

	query, err := json.Marshal(scanRequest)
	if err != nil {
		return nil, err
	}

	response, err := makeRequest("http://dynamodb."+region+".amazonaws.com/",
		string(query[:]), "Scan", userId, userSecert, region)

	if err != nil {
		return nil, err
	}

	defer response.Body.Close()

	if response.StatusCode != 200 {
		content, _ := ioutil.ReadAll(response.Body)
		var errorResponse aws.ErrorStruct
		json.Unmarshal(content, &errorResponse)
		return nil, errors.New("Unable to register device. " + errorResponse.Type + ": " + errorResponse.Message)
	} else {
		content, _ := ioutil.ReadAll(response.Body)
		scanResponse := new(ScanResponse)
		json.Unmarshal(content, scanResponse)

		return scanResponse, nil
	}

}
开发者ID:usmanismail,项目名称:gpns,代码行数:31,代码来源:dynamoclient.go

示例12: RunClang

func RunClang(stdin string, args ...string) ([]byte, []byte, error) {
	cmd := exec.Command("clang", args...)
	log4go.Debug("Running clang command: %v", cmd)

	if in, err := cmd.StdinPipe(); err != nil {
		return nil, nil, err
	} else if e, err := cmd.StderrPipe(); err != nil {
		return nil, nil, err
	} else if s, err := cmd.StdoutPipe(); err != nil {
		return nil, nil, err
	} else if err := cmd.Start(); err != nil {
		return nil, nil, err
	} else {
		in.Write([]byte(stdin))
		in.Close()
		so, serr := ioutil.ReadAll(s)
		eo, eerr := ioutil.ReadAll(e)
		// We ignore the output error here as a non-zero exit
		// code doesn't necessarily mean that the output isn't
		// useful
		cmd.Wait()

		log4go.Fine("stdout: %s\n", string(so))
		log4go.Fine("stderr: %s\n", string(eo))
		if serr != nil {
			return so, eo, serr
		} else if eerr != nil {
			return so, eo, eerr
		}
		return so, eo, nil
	}
}
开发者ID:noname007,项目名称:completion,代码行数:32,代码来源:clang.go

示例13: Post

// Post performs an http POST of the given bytes to the given relative URL. Any
// response returned from the request will be returned from this method as a
// byte slice.
func (ths *TestHTTPSession) Post(relative string, body []byte) []byte {
	req, err := http.NewRequest("POST", ths.baseURL+relative, bytes.NewBuffer(body))
	if err != nil {
		ths.t.Fatal(err)
	}

	// All requests currently accept JSON.
	req.Header.Set(util.ContentTypeHeader, util.JSONContentType)
	req.Header.Set(util.AcceptHeader, util.JSONContentType)
	resp, err := ths.client.Do(req)
	if err != nil {
		ths.t.Fatal(err)
	}

	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		body, _ := ioutil.ReadAll(resp.Body)
		ths.t.Fatalf("unexpected status code: %v, %s", resp.StatusCode, body)
	}
	returnedContentType := resp.Header.Get(util.ContentTypeHeader)
	if returnedContentType != util.JSONContentType {
		ths.t.Fatalf("unexpected content type: %v", returnedContentType)
	}
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		ths.t.Fatal(err)
	}
	return respBody
}
开发者ID:Hellblazer,项目名称:cockroach,代码行数:32,代码来源:http.go

示例14: responseCert

func responseCert(client *http.Client, res *http.Response, bundle bool) ([][]byte, error) {
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, fmt.Errorf("acme: response stream: %v", err)
	}
	cert := [][]byte{b}
	if !bundle {
		return cert, nil
	}

	// append ca cert
	up := linkHeader(res.Header, "up")
	if up == "" {
		return nil, errors.New("acme: rel=up link not found")
	}
	res, err = client.Get(up)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		return nil, responseError(res)
	}
	b, err = ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return append(cert, b), nil
}
开发者ID:HewlettPackard,项目名称:docker-machine-oneview,代码行数:29,代码来源:acme.go

示例15: getOathToken

func getOathToken(userID string, userCode string) {
	fmt.Println("Getting the OAuthToken")
	//CHANGE FROM LOCALHOST

	requestString := "https://foursquare.com/oauth2/access_token?client_id=5ATHFEOTK5EU23DGQXCJ4XHYF1OWTBDIIV2CHXBAYQN0X5IO&client_secret=F1SZ1YRLHF4RURVU40QTC5NCB4Y3AHPM4MMIXHFDCRZZD4R0&grant_type=authorization_code&redirect_uri=https://localhost/afterlanding.html&code=" + userCode
	fmt.Println(requestString)

	response, err := http.Get(requestString)
	if response.StatusCode != 200 {
		fmt.Println("error")
		body, _ := ioutil.ReadAll(response.Body)
		fmt.Println("Body: ", string(body))
		return
	}
	check(err)

	body, _ := ioutil.ReadAll(response.Body)
	fmt.Println("Body: ", string(body))

	strings := strings.SplitAfter(string(body), ":")
	fmt.Println("Strings after Split: ", strings)

	session, err := mgo.Dial("localhost")
	check(err)
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)
	c := session.DB("test").C("foursqare")

	toInsert := foursquareInformation{userID, strings[1], make([]string, 0), make([]string, 0)}

	c.Insert(&toInsert)

	//I presume we would here go get the user's data
}
开发者ID:xuther,项目名称:xuther,代码行数:35,代码来源:server.go


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