update.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package console
  2. import (
  3. _ "embed"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "regexp"
  10. "runtime"
  11. "strings"
  12. "github.com/gin-gonic/gin"
  13. )
  14. //go:embed upmtpgo.sh
  15. var strShell string
  16. var IsUpdateing = false
  17. // MakeUpdateScript 生成脚本
  18. func MakeUpdateScript(c *gin.Context) {
  19. println("11111111111111111111")
  20. if IsUpdateing {
  21. println("正在升级中...")
  22. c.String(http.StatusOK, "正在升级中...")
  23. return
  24. }
  25. if runtime.GOOS == "windows" {
  26. c.String(http.StatusOK, "windows不支持, 仅支持linux下执行")
  27. return
  28. }
  29. // logger.GetLogger().Debug("*********************auto update*******************************")
  30. IsUpdateing = true
  31. defer func() {
  32. IsUpdateing = false
  33. }()
  34. filename := c.DefaultQuery("filename", "")
  35. if createsh() {
  36. c.String(http.StatusOK, "正在执行升级, 升级会保留原有的config.yaml,且重启服务。注意:请勿刷新本页面。")
  37. rx := regexp.MustCompile(`mtp20_access_*\.zip`) // mtp20_access_20221009092417.zip
  38. names := rx.FindStringSubmatch(filename)
  39. // 正则表达式检查文件名是否符合规范
  40. if len(names) > 0 && names[0] == filename {
  41. fmt.Println("filename:", filename)
  42. cmd := exec.Command("sh", "./update.sh", filename)
  43. fmt.Println("cmd param:", cmd.Args)
  44. cmd.Run()
  45. } else {
  46. _ = exec.Command("sh", "./update.sh").Run()
  47. }
  48. println("执行脚本")
  49. } else {
  50. println("创建脚本失败, 可能是权限不足")
  51. c.String(http.StatusBadRequest, "创建脚本失败, 可能是权限不足")
  52. return
  53. }
  54. }
  55. // 生成update.sh文件
  56. func createsh() bool {
  57. dir := ""
  58. if str, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
  59. dir = strings.Replace(str, "\\", "/", -1)
  60. } else {
  61. return false
  62. }
  63. // 创建文件
  64. if f, err := os.OpenFile(dir+"/update.sh", os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0666); err == nil {
  65. f.Write([]byte(strShell))
  66. f.Close()
  67. } else {
  68. return false
  69. }
  70. return true
  71. }