db_opt.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package utility
  2. import (
  3. "encoding/json"
  4. "gadmin/config"
  5. "github.com/sirupsen/logrus"
  6. "io/ioutil"
  7. "math/rand"
  8. "os"
  9. "sync"
  10. "time"
  11. )
  12. func SaveDb(lock *sync.Mutex, val interface{}, fileName string) (err error) {
  13. lock.Lock()
  14. defer lock.Unlock()
  15. content, _ := json.Marshal(val)
  16. // 本地运行时,避免权限问题直接写入库
  17. if config.SysType == "windows" {
  18. if err = ioutil.WriteFile(fileName, content, 0666); err != nil {
  19. logrus.Panic("cannot windows SaveDb, err:" + err.Error())
  20. }
  21. return nil
  22. }
  23. tmpName := RandString(16)
  24. err = ioutil.WriteFile(tmpName, content, 0666) //写入文件(字节数组)
  25. if err != nil {
  26. os.Remove(tmpName)
  27. logrus.Panic("cannot SaveToBak, err:" + err.Error())
  28. } else {
  29. if exist, _ := PathExists(fileName); exist {
  30. if err := os.Remove(fileName); err != nil {
  31. logrus.Panic("cannot remove, err:" + err.Error())
  32. }
  33. }
  34. if err = os.Rename(tmpName, fileName); err != nil {
  35. logrus.Panic("cannot SaveToBak, err:" + err.Error())
  36. }
  37. }
  38. return
  39. }
  40. func LoadDb(lock *sync.Mutex, fileName string, val interface{}) (err error) {
  41. file, err := os.OpenFile(fileName, os.O_RDONLY, 0666)
  42. if err != nil {
  43. return
  44. }
  45. content, err := ioutil.ReadAll(file)
  46. if err != nil {
  47. return
  48. }
  49. err = json.Unmarshal(content, val)
  50. return
  51. }
  52. func RandString(len int) string {
  53. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  54. bytes := make([]byte, len)
  55. for i := 0; i < len; i++ {
  56. b := r.Intn(26) + 65
  57. bytes[i] = byte(b)
  58. }
  59. return string(bytes)
  60. }