update.go 1.7 KB

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