用Golang创建一个临时文件夹和文件的实例

416 阅读1分钟

在这个例子中,我们将在一个现有的目录中创建一个临时文件,并将其存储在那里。如果你想在用完这个文件后把它弄走,这很有用。你也可以创建一个临时文件夹。请看这里的其他用法。

main.go

package main

import (
	"log"
)

func main() {
	str := NewStorage()
	if err := str.Write([]byte("Hello World!")); err != nil {
		log.Fatalln(err)
	}

	path, err := str.Store("tmp/", ".txt")
	if err != nil {
		log.Fatalln(err)
	}

	log.Println(path)

	// Result
	// tmp/606364987.txt
}

storage.go

package main

import (
	"bytes"
	"io/ioutil"
)

type Storage struct {
	*bytes.Buffer
}

func NewStorage() *Storage {
	return &Storage{
		&bytes.Buffer{},
	}
}

// Write appends each data chunk to the current buffer.
func (s *Storage) Write(chunk []byte) error {
	_, err := s.Buffer.Write(chunk)

	return err
}

// Store creates a new globally unique temporary file and stores in a specific
// directory. Given that this is a "temporary" file, you should handle removing
// the file. E.g. defer os.Remove(tmp.Name())
func (s *Storage) Store(dir, ext string) (string, error) {
	tmp, err := ioutil.TempFile(dir, "*"+ext)
	if err != nil {
		return "", err
	}
	defer tmp.Close()

	if _, err := tmp.Write(s.Buffer.Bytes()); err != nil {
		return "", err
	}

	return tmp.Name(), nil
}