本文整理匯總了Golang中io/ioutil.TempFile函數的典型用法代碼示例。如果您正苦於以下問題:Golang TempFile函數的具體用法?Golang TempFile怎麽用?Golang TempFile使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了TempFile函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: encDec
//TODO:
// * Modify lzhuf.c's Encode() so we don't have to use temp files.
// * Handle go errors.
func encDec(data []byte, encode bool) []byte {
// Create temp files
outf, _ := ioutil.TempFile("", "lzhuf")
inf, _ := ioutil.TempFile("", "lzhuf")
defer func() {
outf.Close()
os.Remove(outf.Name())
os.Remove(inf.Name())
}()
// Copy data to in file
io.Copy(inf, bytes.NewBuffer(data))
inf.Sync()
inf.Close()
// Encode/Decode the inf to outf
lzs := C.AllocStruct()
var retval C.int
if encode {
retval = C.Encode(0, C.CString(inf.Name()), C.CString(outf.Name()), lzs, 1)
} else {
retval = C.Decode(0, C.CString(inf.Name()), C.CString(outf.Name()), lzs, 1)
}
C.FreeStruct(lzs)
if retval < 0 {
panic("lzhuf encode/decode error")
}
// Read the compressed/decompressed data from outf
b, _ := ioutil.ReadAll(outf)
return b
}
示例2: build_config
func build_config(
rules string,
c *C) (conf string, cleanup func()) {
var fconf, rconf *os.File
var err error
var conf_test Config
fconf, err = ioutil.TempFile("", "")
if err != nil {
panic(err)
}
rconf, err = ioutil.TempFile("", "")
if err != nil {
panic(err)
}
cleanup = func() {
fconf.Close()
rconf.Close()
}
// Trailing \n is required by go-config issue #3.
fconf.WriteString(
"[Settings]\nloglevel=debug\nrules=" + rconf.Name() + "\n")
fconf.Sync()
rconf.WriteString(rules + "\n")
rconf.Sync()
conf_test, err = NewFileConfig(fconf.Name())
c.Assert(conf_test, Not(Equals), nil)
c.Assert(err, Equals, nil)
conf = fconf.Name()
return
}
示例3: TestConflictingCurrentContext
func TestConflictingCurrentContext(t *testing.T) {
commandLineFile, _ := ioutil.TempFile("", "")
defer os.Remove(commandLineFile.Name())
envVarFile, _ := ioutil.TempFile("", "")
defer os.Remove(envVarFile.Name())
mockCommandLineConfig := clientcmdapi.Config{
CurrentContext: "any-context-value",
}
mockEnvVarConfig := clientcmdapi.Config{
CurrentContext: "a-different-context",
}
WriteToFile(mockCommandLineConfig, commandLineFile.Name())
WriteToFile(mockEnvVarConfig, envVarFile.Name())
loadingRules := ClientConfigLoadingRules{
CommandLinePath: commandLineFile.Name(),
EnvVarPath: envVarFile.Name(),
}
mergedConfig, err := loadingRules.Load()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if mergedConfig.CurrentContext != mockCommandLineConfig.CurrentContext {
t.Errorf("expected %v, got %v", mockCommandLineConfig.CurrentContext, mergedConfig.CurrentContext)
}
}
示例4: TestSameConfigFalse
func TestSameConfigFalse(t *testing.T) {
log.SetLevel("warn")
src, err := ioutil.TempFile("", "src")
defer os.Remove(src.Name())
if err != nil {
t.Errorf(err.Error())
}
_, err = src.WriteString("src")
if err != nil {
t.Errorf(err.Error())
}
dest, err := ioutil.TempFile("", "dest")
defer os.Remove(dest.Name())
if err != nil {
t.Errorf(err.Error())
}
_, err = dest.WriteString("dest")
if err != nil {
t.Errorf(err.Error())
}
status, err := sameConfig(src.Name(), dest.Name())
if err != nil {
t.Errorf(err.Error())
}
if status != false {
t.Errorf("Expected sameConfig(src, dest) to be %v, got %v", false, status)
}
}
示例5: TestMigratingFile
func TestMigratingFile(t *testing.T) {
sourceFile, _ := ioutil.TempFile("", "")
defer os.Remove(sourceFile.Name())
destinationFile, _ := ioutil.TempFile("", "")
// delete the file so that we'll write to it
os.Remove(destinationFile.Name())
WriteToFile(testConfigAlfa, sourceFile.Name())
loadingRules := ClientConfigLoadingRules{
MigrationRules: map[string]string{destinationFile.Name(): sourceFile.Name()},
}
if _, err := loadingRules.Load(); err != nil {
t.Errorf("unexpected error %v", err)
}
// the load should have recreated this file
defer os.Remove(destinationFile.Name())
sourceContent, err := ioutil.ReadFile(sourceFile.Name())
if err != nil {
t.Errorf("unexpected error %v", err)
}
destinationContent, err := ioutil.ReadFile(destinationFile.Name())
if err != nil {
t.Errorf("unexpected error %v", err)
}
if !reflect.DeepEqual(sourceContent, destinationContent) {
t.Errorf("source and destination do not match")
}
}
示例6: TestProvisionerPrepare_Defaults
func TestProvisionerPrepare_Defaults(t *testing.T) {
var p Provisioner
config := testConfig()
err := p.Prepare(config)
if err == nil {
t.Fatalf("should have error")
}
hostkey_file, err := ioutil.TempFile("", "hostkey")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.Remove(hostkey_file.Name())
publickey_file, err := ioutil.TempFile("", "publickey")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.Remove(publickey_file.Name())
playbook_file, err := ioutil.TempFile("", "playbook")
if err != nil {
t.Fatalf("err: %s", err)
}
defer os.Remove(playbook_file.Name())
config["ssh_host_key_file"] = hostkey_file.Name()
config["ssh_authorized_key_file"] = publickey_file.Name()
config["playbook_file"] = playbook_file.Name()
err = p.Prepare(config)
if err != nil {
t.Fatalf("err: %s", err)
}
}
示例7: TestLoadsRelativeRulesPath
func (t *FileConfigTest) TestLoadsRelativeRulesPath(c *C) {
var fconf, rconf *os.File
var err error
var conf Config
fconf, err = ioutil.TempFile("", "")
if err != nil {
panic(err)
}
rconf, err = ioutil.TempFile("", "")
if err != nil {
panic(err)
}
defer (func() {
fconf.Close()
rconf.Close()
})()
path, _ := filepath.Rel(filepath.Dir(fconf.Name()), rconf.Name())
// Trailing \n is required by go-config issue #3.
fconf.WriteString("[Settings]\nloglevel=debug\nrules=" + path + "\n")
fconf.Sync()
conf, err = NewFileConfig(fconf.Name())
c.Assert(conf, Not(Equals), nil)
c.Assert(err, Equals, nil)
}
示例8: createTestCertFiles
func createTestCertFiles(dir string, spec TestCertSpec) (certFilePath, keyFilePath string, err error) {
certPem, keyPem, err := utilcert.GenerateSelfSignedCertKey(spec.host, parseIPList(spec.ips), spec.names)
if err != nil {
return "", "", err
}
certFile, err := ioutil.TempFile(dir, "cert")
if err != nil {
return "", "", err
}
keyFile, err := ioutil.TempFile(dir, "key")
if err != nil {
return "", "", err
}
_, err = certFile.Write(certPem)
if err != nil {
return "", "", err
}
certFile.Close()
_, err = keyFile.Write(keyPem)
if err != nil {
return "", "", err
}
keyFile.Close()
return certFile.Name(), keyFile.Name(), nil
}
示例9: TestMinifySuccess
func TestMinifySuccess(t *testing.T) {
certFile, _ := ioutil.TempFile("", "")
defer os.Remove(certFile.Name())
keyFile, _ := ioutil.TempFile("", "")
defer os.Remove(keyFile.Name())
caFile, _ := ioutil.TempFile("", "")
defer os.Remove(caFile.Name())
mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t)
if err := MinifyConfig(&mutatingConfig); err != nil {
t.Errorf("unexpected error: %v", err)
}
if len(mutatingConfig.Contexts) > 1 {
t.Errorf("unexpected contexts: %v", mutatingConfig.Contexts)
}
if _, exists := mutatingConfig.Contexts["federal-context"]; !exists {
t.Errorf("missing context")
}
if len(mutatingConfig.Clusters) > 1 {
t.Errorf("unexpected clusters: %v", mutatingConfig.Clusters)
}
if _, exists := mutatingConfig.Clusters["cow-cluster"]; !exists {
t.Errorf("missing cluster")
}
if len(mutatingConfig.AuthInfos) > 1 {
t.Errorf("unexpected users: %v", mutatingConfig.AuthInfos)
}
if _, exists := mutatingConfig.AuthInfos["red-user"]; !exists {
t.Errorf("missing user")
}
}
示例10: DumpLogs
// DumpLogs dumps logs from a Backup/Restore/Import/Export job to the console
func (d *SDb) DumpLogs(taskType string, job *models.Job, service *models.Service) error {
logrus.Printf("Retrieving %s logs for job %s...", service.Label, job.ID)
tempURL, err := d.TempLogsURL(job.ID, service.ID)
if err != nil {
return err
}
dir, err := ioutil.TempDir("", "")
if err != nil {
return err
}
encrFile, err := ioutil.TempFile(dir, "")
if err != nil {
return err
}
resp, err := http.Get(tempURL.URL)
if err != nil {
return err
}
defer resp.Body.Close()
io.Copy(encrFile, resp.Body)
encrFile.Close()
plainFile, err := ioutil.TempFile(dir, "")
if err != nil {
return err
}
// do we have to close this before calling DecryptFile?
// or can two processes have a file open simultaneously?
plainFile.Close()
if taskType == "backup" {
logsKey := job.Backup.KeyLogs
if logsKey == "" {
logsKey = job.Backup.Key
}
err := d.Crypto.DecryptFile(encrFile.Name(), logsKey, job.Backup.IV, plainFile.Name())
if err != nil {
return err
}
} else if taskType == "restore" {
logsKey := job.Restore.KeyLogs
if logsKey == "" {
logsKey = job.Restore.Key
}
err := d.Crypto.DecryptFile(encrFile.Name(), logsKey, job.Restore.IV, plainFile.Name())
if err != nil {
return err
}
}
logrus.Printf("-------------------------- Begin %s logs --------------------------", service.Label)
plainFile, _ = os.Open(plainFile.Name())
io.Copy(os.Stdout, plainFile)
plainFile.Close()
logrus.Printf("--------------------------- End %s logs ---------------------------", service.Label)
os.Remove(encrFile.Name())
os.Remove(plainFile.Name())
os.Remove(dir)
return nil
}
示例11: TestExpandInjectedFiles
func TestExpandInjectedFiles(t *testing.T) {
tmp, err := ioutil.TempDir("", "s2i-test-")
tmpNested, err := ioutil.TempDir(tmp, "nested")
if err != nil {
t.Errorf("Unable to create temp directory: %v", err)
}
defer os.RemoveAll(tmp)
list := api.VolumeList{{Source: tmp, Destination: "/foo"}}
f1, _ := ioutil.TempFile(tmp, "foo")
f2, _ := ioutil.TempFile(tmpNested, "bar")
files, err := ExpandInjectedFiles(list)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
expected := []string{"/foo/" + filepath.Base(f1.Name()), filepath.Join("/foo", filepath.Base(tmpNested), filepath.Base(f2.Name()))}
for _, exp := range expected {
found := false
for _, f := range files {
if f == exp {
found = true
}
}
if !found {
t.Errorf("Expected %q in resulting file list, got %+v", exp, files)
}
}
}
示例12: Bundle
// Bundle stuff...
// BUG(echu): need to figure out how to handle conflicts in bundle names
func (ctx *Context) Bundle(bundlePath string) error {
log.Printf("==> Creating bundle from '%s'", bundlePath)
defer log.Printf("<== Bundling complete.")
log.Printf(" | Parsing bundle config.")
bundleConfig, err := ParseBundleFromDir(bundlePath)
if err != nil {
return err
}
log.Printf(" %v", bundleConfig)
log.Printf(" | Making temp file for python wrapper")
wrapper, err := ioutil.TempFile(bundlePath, "plumber")
defer removeTempFile(wrapper)
if err != nil {
return err
}
log.Printf(" Created '%s'", wrapper.Name())
templateCtx := templateContext{
Wrapper: path.Base(wrapper.Name()),
Plumber: bundleConfig,
}
log.Printf(" | Writing wrapper.")
tmpl, err := template.New("wrapper").Parse(wrapperTemplate)
if err != nil {
return err
}
if err := tmpl.Execute(wrapper, templateCtx); err != nil {
return err
}
log.Printf(" Done.")
log.Printf(" | Making temp file for Dockerfile")
dockerfile, err := ioutil.TempFile(bundlePath, "plumber")
defer removeTempFile(dockerfile)
if err != nil {
return err
}
log.Printf(" Created '%s'", dockerfile.Name())
log.Printf(" | Writing Dockerfile.")
tmpl, err = template.New("dockerfile").Parse(dockerfileTemplate)
if err != nil {
return err
}
if err := tmpl.Execute(dockerfile, templateCtx); err != nil {
return err
}
log.Printf(" Done.")
log.Printf(" | Building container.")
err = shell.RunAndLog(ctx.DockerCmd, "build", "--pull", "-t", ctx.GetImage(bundleConfig.Name), "-f", dockerfile.Name(), bundlePath)
if err != nil {
return err
}
log.Printf(" Container '%s' built.", ctx.GetImage(bundleConfig.Name))
return nil
}
示例13: makeFineDmndDB
func makeFineDmndDB(seqBuf *bytes.Buffer) (string, error) {
tmpSeqFile, err := ioutil.TempFile(".", "fine-sequences-")
if err != nil {
return "", fmt.Errorf("Could not create temporary sequence file: %s\n", err)
}
err = ioutil.WriteFile(tmpSeqFile.Name(), seqBuf.Bytes(), 0666)
if err != nil {
return "", fmt.Errorf("Could not write to temporary sequence file: %s\n", err)
}
tmpDmndFile, err := ioutil.TempFile(".", "fine-dmnd-db-")
if err != nil {
return "", fmt.Errorf("Could not create temporary diamond file: %s\n", err)
}
cmd := exec.Command(
flagDmnd,
"makedb",
"--in", tmpSeqFile.Name(),
"-d", tmpDmndFile.Name())
err = mica.Exec(cmd)
if err != nil {
return "", fmt.Errorf("Could not create fine diamond database: %s\n", err)
}
err = os.RemoveAll(tmpSeqFile.Name())
if err != nil {
return "", fmt.Errorf("Could not remove temporary sequence file: %s\n", err)
}
return tmpDmndFile.Name(), nil
}
示例14: VerifyDetachedSignature
// VerifyDetachedSignature verifies combination of signature and cleartext using gpgv
func (g *GpgVerifier) VerifyDetachedSignature(signature, cleartext io.Reader) error {
args := g.argsKeyrings()
sigf, err := ioutil.TempFile("", "aptly-gpg")
if err != nil {
return err
}
defer os.Remove(sigf.Name())
defer sigf.Close()
_, err = io.Copy(sigf, signature)
if err != nil {
return err
}
clearf, err := ioutil.TempFile("", "aptly-gpg")
if err != nil {
return err
}
defer os.Remove(clearf.Name())
defer clearf.Close()
_, err = io.Copy(clearf, cleartext)
if err != nil {
return err
}
args = append(args, sigf.Name(), clearf.Name())
return g.runGpgv(args, "detached signature")
}
示例15: helpDiff
func helpDiff(a, b string) (string, error) {
atmp, err := ioutil.TempFile("", "help-diff")
if err != nil {
return "", err
}
btmp, err := ioutil.TempFile("", "help-diff")
if err != nil {
return "", err
}
if _, err := io.WriteString(atmp, a); err != nil {
return "", err
}
if _, err := io.WriteString(btmp, b); err != nil {
return "", err
}
ret, err := exec.Command("diff", "-u", "-d", "--label", "got", atmp.Name(), "--label", "expected", btmp.Name()).Output()
os.Remove(atmp.Name())
os.Remove(btmp.Name())
if err.Error() == "exit status 1" {
return string(ret), nil
}
return string(ret), err
}