| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- // 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)
- }
|