Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

In this example we are going to create a temporary file in an existing directory and store it there. This is useful if you want to get rid of this file once you are done with it. You can also create a temporary folder. See other usages here.


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
}