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


Golang ioutil.WriteFile函数代码示例

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


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

示例1: SetUp

func (fix *SimpleToolsFixture) SetUp(c *gc.C, dataDir string) {
	fix.BaseSuite.SetUpTest(c)
	fix.dataDir = dataDir
	fix.initDir = c.MkDir()
	fix.logDir = c.MkDir()
	toolsDir := tools.SharedToolsDir(fix.dataDir, version.Current)
	err := os.MkdirAll(toolsDir, 0755)
	c.Assert(err, gc.IsNil)
	jujudPath := filepath.Join(toolsDir, "jujud")
	err = ioutil.WriteFile(jujudPath, []byte(fakeJujud), 0755)
	c.Assert(err, gc.IsNil)
	toolsPath := filepath.Join(toolsDir, "downloaded-tools.txt")
	testTools := coretools.Tools{Version: version.Current, URL: "http://testing.invalid/tools"}
	data, err := json.Marshal(testTools)
	c.Assert(err, gc.IsNil)
	err = ioutil.WriteFile(toolsPath, data, 0644)
	c.Assert(err, gc.IsNil)
	fix.binDir = c.MkDir()
	fix.origPath = os.Getenv("PATH")
	os.Setenv("PATH", fix.binDir+":"+fix.origPath)
	fix.makeBin(c, "status", `echo "blah stop/waiting"`)
	fix.makeBin(c, "stopped-status", `echo "blah stop/waiting"`)
	fix.makeBin(c, "started-status", `echo "blah start/running, process 666"`)
	fix.makeBin(c, "start", "cp $(which started-status) $(which status)")
	fix.makeBin(c, "stop", "cp $(which stopped-status) $(which status)")
}
开发者ID:rogpeppe,项目名称:juju,代码行数:26,代码来源:simple_test.go

示例2: TestUnionFsDropCache

func TestUnionFsDropCache(t *testing.T) {
	wd, clean := setupUfs(t)
	defer clean()

	err := ioutil.WriteFile(wd+"/ro/file", []byte("bla"), 0644)
	CheckSuccess(err)

	_, err = os.Lstat(wd + "/mnt/.drop_cache")
	CheckSuccess(err)

	names, err := Readdirnames(wd + "/mnt")
	CheckSuccess(err)
	if len(names) != 1 || names[0] != "file" {
		t.Fatal("unexpected names", names)
	}

	err = ioutil.WriteFile(wd+"/ro/file2", []byte("blabla"), 0644)
	names2, err := Readdirnames(wd + "/mnt")
	CheckSuccess(err)
	if len(names2) != len(names) {
		t.Fatal("mismatch", names2)
	}

	err = ioutil.WriteFile(wd+"/mnt/.drop_cache", []byte("does not matter"), 0644)
	CheckSuccess(err)
	names2, err = Readdirnames(wd + "/mnt")
	if len(names2) != 2 {
		t.Fatal("mismatch 2", names2)
	}
}
开发者ID:taruti,项目名称:go-fuse,代码行数:30,代码来源:unionfs_test.go

示例3: TestGetUsesCache

func (s *charmsSuite) TestGetUsesCache(c *gc.C) {
	// Add a fake charm archive in the cache directory.
	cacheDir := filepath.Join(s.DataDir(), "charm-get-cache")
	err := os.MkdirAll(cacheDir, 0755)
	c.Assert(err, jc.ErrorIsNil)

	// Create and save a bundle in it.
	charmDir := testcharms.Repo.ClonedDir(c.MkDir(), "dummy")
	testPath := filepath.Join(charmDir.Path, "utils.js")
	contents := "// blah blah"
	err = ioutil.WriteFile(testPath, []byte(contents), 0755)
	c.Assert(err, jc.ErrorIsNil)
	var buffer bytes.Buffer
	err = charmDir.ArchiveTo(&buffer)
	c.Assert(err, jc.ErrorIsNil)
	charmArchivePath := filepath.Join(
		cacheDir, charm.Quote("local:trusty/django-42")+".zip")
	err = ioutil.WriteFile(charmArchivePath, buffer.Bytes(), 0644)
	c.Assert(err, jc.ErrorIsNil)

	// Ensure the cached contents are properly retrieved.
	uri := s.charmsURI(c, "?url=local:trusty/django-42&file=utils.js")
	resp, err := s.authRequest(c, "GET", uri, "", nil)
	c.Assert(err, jc.ErrorIsNil)
	s.assertGetFileResponse(c, resp, contents, "application/javascript")
}
开发者ID:kakamessi99,项目名称:juju,代码行数:26,代码来源:charms_test.go

示例4: generateSSHKey

func (m *Master) generateSSHKey(user, privateKeyfile, publicKeyfile string) error {
	private, public, err := util.GenerateKey(2048)
	if err != nil {
		return err
	}
	// If private keyfile already exists, we must have only made it halfway
	// through last time, so delete it.
	exists, err := util.FileExists(privateKeyfile)
	if err != nil {
		glog.Errorf("Error detecting if private key exists: %v", err)
	} else if exists {
		glog.Infof("Private key exists, but public key does not")
		if err := os.Remove(privateKeyfile); err != nil {
			glog.Errorf("Failed to remove stale private key: %v", err)
		}
	}
	if err := ioutil.WriteFile(privateKeyfile, util.EncodePrivateKey(private), 0600); err != nil {
		return err
	}
	publicKeyBytes, err := util.EncodePublicKey(public)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(publicKeyfile+".tmp", publicKeyBytes, 0600); err != nil {
		return err
	}
	return os.Rename(publicKeyfile+".tmp", publicKeyfile)
}
开发者ID:gogogocheng,项目名称:kubernetes,代码行数:28,代码来源:master.go

示例5: calculateLayerChecksum

func calculateLayerChecksum(graphDir, id string, ls checksumCalculator) error {
	diffIDFile := filepath.Join(graphDir, id, migrationDiffIDFileName)
	if _, err := os.Lstat(diffIDFile); err == nil {
		return nil
	} else if !os.IsNotExist(err) {
		return err
	}

	parent, err := getParent(filepath.Join(graphDir, id))
	if err != nil {
		return err
	}

	diffID, size, err := ls.ChecksumForGraphID(id, parent, filepath.Join(graphDir, id, tarDataFileName), filepath.Join(graphDir, id, migrationTarDataFileName))
	if err != nil {
		return err
	}

	if err := ioutil.WriteFile(filepath.Join(graphDir, id, migrationSizeFileName), []byte(strconv.Itoa(int(size))), 0600); err != nil {
		return err
	}

	tmpFile := filepath.Join(graphDir, id, migrationDiffIDFileName+".tmp")
	if err := ioutil.WriteFile(tmpFile, []byte(diffID), 0600); err != nil {
		return err
	}

	if err := os.Rename(tmpFile, filepath.Join(graphDir, id, migrationDiffIDFileName)); err != nil {
		return err
	}

	logrus.Infof("calculated checksum for layer %s: %s", id, diffID)
	return nil
}
开发者ID:docker,项目名称:v1.10-migrator,代码行数:34,代码来源:migratev1.go

示例6: TestReadConfigPaths_dir

func TestReadConfigPaths_dir(t *testing.T) {
	td, err := ioutil.TempDir("", "consul")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(td)

	err = ioutil.WriteFile(filepath.Join(td, "a.json"),
		[]byte(`{"node_name": "bar"}`), 0644)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	err = ioutil.WriteFile(filepath.Join(td, "b.json"),
		[]byte(`{"node_name": "baz"}`), 0644)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// A non-json file, shouldn't be read
	err = ioutil.WriteFile(filepath.Join(td, "c"),
		[]byte(`{"node_name": "bad"}`), 0644)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	config, err := ReadConfigPaths([]string{td})
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if config.NodeName != "baz" {
		t.Fatalf("bad: %#v", config)
	}
}
开发者ID:ericpfisher,项目名称:consul,代码行数:35,代码来源:config_test.go

示例7: TestPreallocFilesWriteErrors

func (s *preallocSuite) TestPreallocFilesWriteErrors(c *gc.C) {
	dir := c.MkDir()
	prefix := filepath.Join(dir, "test.")
	err := ioutil.WriteFile(prefix+"0", nil, 0644)
	c.Assert(err, gc.IsNil)
	err = ioutil.WriteFile(prefix+"1", nil, 0644)
	c.Assert(err, gc.IsNil)

	var called int
	s.PatchValue(mongo.PreallocFile, func(filename string, size int) (bool, error) {
		var created bool
		var err error
		called++
		if called == 2 {
			created = true
			err = fmt.Errorf("failed to zero test.1")
		}
		return created, err
	})

	err = mongo.PreallocFiles(prefix, 4096, 8192)
	c.Assert(err, gc.ErrorMatches, "failed to zero test.1")

	// test.0 still exists because we said we didn't
	// create it (i.e. it already existed)
	_, err = os.Stat(prefix + "0")
	c.Assert(err, gc.IsNil)

	// test.1 no longer exists because we said we created
	// it, but then failed to write to it.
	_, err = os.Stat(prefix + "1")
	c.Assert(err, jc.Satisfies, os.IsNotExist)
}
开发者ID:jiasir,项目名称:juju,代码行数:33,代码来源:prealloc_test.go

示例8: TestOverwriteRename

func TestOverwriteRename(t *testing.T) {
	tc := NewTestCase(t)
	defer tc.Cleanup()

	t.Log("Testing rename overwrite.")

	sd := tc.mnt + "/testOverwriteRename"
	err := os.MkdirAll(sd, 0755)
	if err != nil {
		t.Fatalf("MkdirAll failed: %v", err)
	}

	d := sd + "/dest"
	err = ioutil.WriteFile(d, []byte("blabla"), 0644)
	if err != nil {
		t.Fatalf("WriteFile failed: %v", err)
	}

	s := sd + "/src"
	err = ioutil.WriteFile(s, []byte("blabla"), 0644)
	if err != nil {
		t.Fatalf("WriteFile failed: %v", err)
	}

	err = os.Rename(s, d)
	if err != nil {
		t.Fatalf("Rename failed: %v", err)
	}
}
开发者ID:seacoastboy,项目名称:go-fuse,代码行数:29,代码来源:loopback_test.go

示例9: NewConfig

func NewConfig() *Config {
	var runControllerScript string = `
sshd_run=$(which sshd)
$sshd_run -D&

munged_run=$(which munged)
$munged_run -F&

slurm_env_config_run=$(which 'slurm-env-config')
$slurm_env_config_run >> /etc/slurm.conf

slurmctl_run=$(which /usr/sbin/slurmctld)
$slurmctl_run -D -v&
wait
`

	var runNodeScript string = `
sshd_run=$(which sshd)
$sshd_run -D&

munged_run=$(which munged)
$munged_run -F&

slurm_env_config_run=$(which 'slurm-env-config')
$slurm_env_config_run >> /etc/slurm.conf

slurmctl_run=$(which /usr/sbin/slurmd)
$slurmctl_run -D -v&
wait
`
	config := &Config{
		CLI: newCli(),
		Dir: newConfDir(),
	}

	controllerScriptPath := filepath.Join(config.Dir, "run_controller.sh")
	err := ioutil.WriteFile(controllerScriptPath, []byte(runControllerScript), 0755)
	if err != nil {
		log.Fatal("failed to write run_controller.sh: ", err)
	}

	nodeScriptPath := filepath.Join(config.Dir, "run_node.sh")
	err = ioutil.WriteFile(nodeScriptPath, []byte(runNodeScript), 0755)
	if err != nil {
		log.Fatal("failed to write run_node.sh: ", err)
	}

	u, err := user.Current()
	if err != nil {
		log.Fatal("failed to get current user: ", err)
	}
	config.User = u.Username
	config.GID = u.Gid

	config.PWD, err = os.Getwd()
	if err != nil {
		log.Fatal("failed to get current working directory: ", err)
	}
	return config
}
开发者ID:JohannWeging,项目名称:covey,代码行数:60,代码来源:conf.go

示例10: TestDelRename

// Flaky test, due to rename race condition.
func TestDelRename(t *testing.T) {
	tc := NewTestCase(t)
	defer tc.Cleanup()

	t.Log("Testing del+rename.")

	sd := tc.mnt + "/testDelRename"
	err := os.MkdirAll(sd, 0755)
	CheckSuccess(err)

	d := sd + "/dest"
	err = ioutil.WriteFile(d, []byte("blabla"), 0644)
	CheckSuccess(err)

	f, err := os.Open(d)
	CheckSuccess(err)
	defer f.Close()

	err = os.Remove(d)
	CheckSuccess(err)

	s := sd + "/src"
	err = ioutil.WriteFile(s, []byte("blabla"), 0644)
	CheckSuccess(err)

	err = os.Rename(s, d)
	CheckSuccess(err)
}
开发者ID:niltonkummer,项目名称:go-fuse,代码行数:29,代码来源:loopback_test.go

示例11: TestUninstall

func TestUninstall(t *testing.T) {
	fakeSB := runit.FakeServiceBuilder()
	defer fakeSB.Cleanup()
	serviceBuilder := &fakeSB.ServiceBuilder

	testPodDir, err := ioutil.TempDir("", "testPodDir")
	Assert(t).IsNil(err, "Got an unexpected error creating a temp directory")
	pod := Pod{
		Id:             "testPod",
		path:           testPodDir,
		ServiceBuilder: serviceBuilder,
	}
	manifest := getTestPodManifest(t)
	manifestContent, err := manifest.Marshal()
	Assert(t).IsNil(err, "couldn't get manifest bytes")
	err = ioutil.WriteFile(pod.currentPodManifestPath(), manifestContent, 0744)
	Assert(t).IsNil(err, "should have written current manifest")

	serviceBuilderFilePath := filepath.Join(serviceBuilder.ConfigRoot, "testPod.yaml")
	err = ioutil.WriteFile(serviceBuilderFilePath, []byte("stuff"), 0744)
	Assert(t).IsNil(err, "Error writing fake servicebuilder file")

	err = pod.Uninstall()
	Assert(t).IsNil(err, "Error uninstalling pod")
	_, err = os.Stat(serviceBuilderFilePath)
	Assert(t).IsTrue(os.IsNotExist(err), "Expected file to not exist after uninstall")
	_, err = os.Stat(pod.currentPodManifestPath())
	Assert(t).IsTrue(os.IsNotExist(err), "Expected file to not exist after uninstall")
}
开发者ID:tomzhang,项目名称:p2,代码行数:29,代码来源:pod_test.go

示例12: PatchExecutable

// PatchExecutable creates an executable called 'execName' in a new test
// directory and that directory is added to the path.
func PatchExecutable(c *gc.C, patcher CleanupPatcher, execName, script string, exitCodes ...int) {
	dir := c.MkDir()
	patcher.PatchEnvironment("PATH", joinPathLists(dir, os.Getenv("PATH")))
	var filename string
	switch runtime.GOOS {
	case "windows":
		filename = filepath.Join(dir, execName+".bat")
	default:
		filename = filepath.Join(dir, execName)
	}
	os.Remove(filename + ".out")
	err := ioutil.WriteFile(filename, []byte(script), 0755)
	c.Assert(err, gc.IsNil)

	if len(exitCodes) > 0 {
		filename = execName + ".exitcodes"
		codes := make([]string, len(exitCodes))
		for i, code := range exitCodes {
			codes[i] = strconv.Itoa(code)
		}
		s := strings.Join(codes, ";") + ";"
		err = ioutil.WriteFile(filename, []byte(s), 0644)
		c.Assert(err, gc.IsNil)
		patcher.AddCleanup(func(*gc.C) {
			os.Remove(filename)
		})
	}
}
开发者ID:fabricematrat,项目名称:testing,代码行数:30,代码来源:cmd.go

示例13: SetUp

func (fix *SimpleToolsFixture) SetUp(c *gc.C, dataDir string) {
	fix.dataDir = dataDir
	fix.logDir = c.MkDir()
	current := version.Binary{
		Number: version.Current,
		Arch:   arch.HostArch(),
		Series: series.HostSeries(),
	}
	toolsDir := tools.SharedToolsDir(fix.dataDir, current)
	err := os.MkdirAll(toolsDir, 0755)
	c.Assert(err, jc.ErrorIsNil)
	jujudPath := filepath.Join(toolsDir, "jujud")
	err = ioutil.WriteFile(jujudPath, []byte(fakeJujud), 0755)
	c.Assert(err, jc.ErrorIsNil)
	toolsPath := filepath.Join(toolsDir, "downloaded-tools.txt")
	testTools := coretools.Tools{Version: current, URL: "http://testing.invalid/tools"}
	data, err := json.Marshal(testTools)
	c.Assert(err, jc.ErrorIsNil)
	err = ioutil.WriteFile(toolsPath, data, 0644)
	c.Assert(err, jc.ErrorIsNil)
	fix.binDir = c.MkDir()
	fix.origPath = os.Getenv("PATH")
	os.Setenv("PATH", fix.binDir+":"+fix.origPath)
	fix.makeBin(c, "status", `echo "blah stop/waiting"`)
	fix.makeBin(c, "stopped-status", `echo "blah stop/waiting"`)
	fix.makeBin(c, "started-status", `echo "blah start/running, process 666"`)
	fix.makeBin(c, "start", "cp $(which started-status) $(which status)")
	fix.makeBin(c, "stop", "cp $(which stopped-status) $(which status)")

	fix.data = svctesting.NewFakeServiceData()
}
开发者ID:imoapps,项目名称:juju,代码行数:31,代码来源:simple_test.go

示例14: materialize

func materialize(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

	log.Println("[materialize]")

	rq := new(protocol.NetworkMaterializationRequest)
	err := protocol.Unpack(r.Body, rq)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Header().Set("Content-Type", "application/json")
		d := protocol.Diagnostic{"error", "malformed json"}
		w.Write(protocol.PackWire(d))
		return
	}

	err, em := embed(&rq.Net, rq.Mapper)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Header().Set("Content-Type", "application/json")
		d := protocol.Diagnostic{"error", fmt.Sprintf("materialization: %s", err)}
		w.Write(protocol.PackWire(d))
		return
	}

	xpdir := "/marina/xp/" + rq.Net.Name
	os.MkdirAll(xpdir, 0755)
	ioutil.WriteFile(xpdir+"/net.json", protocol.PackLegible(rq.Net), 0644)
	ioutil.WriteFile(xpdir+"/map.json", protocol.PackLegible(em), 0644)

}
开发者ID:rcgoodfellow,项目名称:marina,代码行数:29,代码来源:main.go

示例15: BackupAndSaveConf

// Copy existing index configuration to backup, then save the latest index configuration.
func (col *Col) BackupAndSaveConf() error {
	if col.Config == nil {
		return nil
	}
	// Read existing file content and copy to backup
	oldConfig, err := ioutil.ReadFile(col.ConfigFileName)
	if err != nil {
		return err
	}
	if err = ioutil.WriteFile(col.ConfBackupFileName, []byte(oldConfig), 0600); err != nil {
		return err
	}
	if col.Config == nil {
		return nil
	}
	// Marshal index configuration into file
	newConfig, err := json.Marshal(col.Config)
	if err != nil {
		return err
	}
	if err = ioutil.WriteFile(col.ConfigFileName, newConfig, 0600); err != nil {
		return err
	}
	return nil
}
开发者ID:petitbon,项目名称:tiedot,代码行数:26,代码来源:col.go


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