utils.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // utils
  2. package main
  3. import (
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "os/user"
  9. "path"
  10. )
  11. // File locations enum
  12. type fileLoc uint8
  13. const (
  14. locHome fileLoc = 0 // in user home dir
  15. locTemp fileLoc = 1 // in temp dir
  16. )
  17. // File stucture
  18. type file struct {
  19. path, dir, name string
  20. floc fileLoc
  21. handle *os.File
  22. }
  23. func (f *file) init(fname string, loc fileLoc) {
  24. // define outside switch scope
  25. var dir string
  26. var err error
  27. // Set file name
  28. f.name = fname
  29. // Using switch (in case there's going ever to be more file types)
  30. switch loc {
  31. case locHome:
  32. var u *user.User
  33. u, err = user.Current()
  34. dir = u.HomeDir
  35. case locTemp:
  36. dir, err = ioutil.TempDir(os.TempDir(), f.name)
  37. }
  38. // Check for error
  39. if err != nil {
  40. fmt.Println("Panicking!")
  41. panic(fmt.Sprintf("%v", err))
  42. }
  43. // Set necessary data
  44. f.floc = loc
  45. f.dir = dir
  46. f.path = path.Join(f.dir, f.name)
  47. }
  48. func (f *file) Open() {
  49. // define outside switch scope
  50. var fh *os.File
  51. var err error
  52. // Different permissions for different locations
  53. switch f.floc {
  54. case locHome:
  55. fh, err = os.Open(h.path)
  56. case locTemp:
  57. fh, err = os.OpenFile(h.path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
  58. }
  59. // Check for error
  60. if err != nil {
  61. fmt.Println(err)
  62. }
  63. // Set handle
  64. f.handle = fh
  65. }
  66. func CopyFile(src, dst string) (int64, error) {
  67. sf, err := os.Open(src)
  68. if err != nil {
  69. return 0, err
  70. }
  71. defer sf.Close()
  72. df, err := os.Create(dst)
  73. if err != nil {
  74. return 0, err
  75. }
  76. df.Chmod(0600)
  77. defer df.Close()
  78. return io.Copy(df, sf)
  79. }