// utils package main import ( "fmt" "io" "io/ioutil" "os" "os/user" "path" ) // File locations enum type fileLoc uint8 const ( locHome fileLoc = 0 // in user home dir locTemp fileLoc = 1 // in temp dir ) // File stucture type file struct { path, dir, name string floc fileLoc handle *os.File } func (f *file) init(fname string, loc fileLoc) { // define outside switch scope var dir string var err error // Set file name f.name = fname // Using switch (in case there's going ever to be more file types) switch loc { case locHome: var u *user.User u, err = user.Current() dir = u.HomeDir case locTemp: dir, err = ioutil.TempDir(os.TempDir(), f.name) } // Check for error if err != nil { fmt.Println("Panicking!") panic(fmt.Sprintf("%v", err)) } // Set necessary data f.floc = loc f.dir = dir f.path = path.Join(f.dir, f.name) } func (f *file) Open() { // define outside switch scope var fh *os.File var err error // Different permissions for different locations switch f.floc { case locHome: fh, err = os.Open(h.path) case locTemp: fh, err = os.OpenFile(h.path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600) } // Check for error if err != nil { fmt.Println(err) } // Set handle f.handle = fh } func CopyFile(src, dst string) (int64, error) { sf, err := os.Open(src) if err != nil { return 0, err } defer sf.Close() df, err := os.Create(dst) if err != nil { return 0, err } df.Chmod(0600) defer df.Close() return io.Copy(df, sf) }