file.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package utils
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "os"
  8. )
  9. func GetVersion() (string, error) {
  10. data, err := os.ReadFile(PackConfPath)
  11. if err != nil {
  12. fmt.Println(err)
  13. return "", errors.New("读取文件失败")
  14. }
  15. packConf := make(map[string]interface{})
  16. err = json.Unmarshal(data, &packConf)
  17. if err != nil {
  18. fmt.Println(err)
  19. return "", errors.New("解析文件失败")
  20. }
  21. if _, ok := packConf["version"]; !ok {
  22. return "", errors.New("没有版本信息")
  23. }
  24. return packConf["version"].(string), nil
  25. }
  26. func ReadConfig() (*Uploader, error) {
  27. conf, err := os.Open(ConfigPath)
  28. if err != nil {
  29. fmt.Println(err)
  30. return nil, errors.New("打开文件失败")
  31. }
  32. reader := bufio.NewReader(conf)
  33. decoder := json.NewDecoder(reader)
  34. config := &Uploader{}
  35. err = decoder.Decode(config)
  36. if err != nil {
  37. return nil, errors.New("解析失败")
  38. }
  39. return config, nil
  40. }
  41. func ReadAppConfig() (*App, error) {
  42. conf, err := os.Open(AppConfPath)
  43. if err != nil {
  44. fmt.Println(err)
  45. return nil, errors.New("打开文件失败")
  46. }
  47. reader := bufio.NewReader(conf)
  48. decoder := json.NewDecoder(reader)
  49. appConf := &App{}
  50. err = decoder.Decode(appConf)
  51. if err != nil {
  52. return nil, errors.New("解析失败")
  53. }
  54. return appConf, nil
  55. }
  56. func WriteAppConfig(config *App, dest string) error {
  57. data, err := json.MarshalIndent(config, "", " ")
  58. if err != nil {
  59. fmt.Println(err)
  60. return errors.New("json marshal err")
  61. }
  62. err = os.WriteFile(dest, data, 0777)
  63. if err != nil {
  64. fmt.Println(err)
  65. return errors.New("写入配置文件出错")
  66. }
  67. return nil
  68. }