filetack.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package utils
  2. import (
  3. "encoding/gob"
  4. "os"
  5. )
  6. type FileTack[T any] struct {
  7. Value T
  8. FilePath string
  9. }
  10. func NewFileTack[T any](filePath string) (*FileTack[T], error) {
  11. file, err := os.Open(filePath)
  12. if err != nil {
  13. return nil, err
  14. }
  15. defer func() {
  16. _ = file.Close()
  17. }()
  18. var value T
  19. decoder := gob.NewDecoder(file)
  20. err = decoder.Decode(&value)
  21. if err != nil {
  22. return nil, err
  23. }
  24. return NewFileTackWithValue(filePath, value), nil
  25. }
  26. func NewFileTackWithDefault[T any](filePath string, defaultVal T) (*FileTack[T], error) {
  27. if !IsExists(filePath) {
  28. return NewFileTackWithValue(filePath, defaultVal), nil
  29. }
  30. return NewFileTack[T](filePath)
  31. }
  32. func NewFileTackWithValue[T any](filePath string, value T) *FileTack[T] {
  33. return &FileTack[T]{
  34. Value: value,
  35. FilePath: filePath,
  36. }
  37. }
  38. func (f *FileTack[T]) Save() error {
  39. file, err := os.Create(f.FilePath)
  40. if err != nil {
  41. return err
  42. }
  43. defer func() {
  44. _ = file.Close()
  45. }()
  46. encoder := gob.NewEncoder(file)
  47. err = encoder.Encode(f.Value)
  48. if err != nil {
  49. return err
  50. }
  51. return nil
  52. }