win32.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2025 BackendServerTemplate Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. //go:build windows
  5. package consolewatcher
  6. import (
  7. "github.com/SongZihuan/BackendServerTemplate/src/config"
  8. "github.com/SongZihuan/BackendServerTemplate/src/logger"
  9. "github.com/SongZihuan/BackendServerTemplate/src/utils/consoleutils"
  10. "github.com/SongZihuan/BackendServerTemplate/src/utils/strconvutils"
  11. "time"
  12. )
  13. // 控制台事件处理函数(回调)
  14. func consoleHandler(exitChannel chan consoleutils.Event, waitExitChannel chan any) func(event uint) bool {
  15. return func(event uint) bool {
  16. switch event {
  17. case consoleutils.CTRL_CLOSE_EVENT.GetCode(), consoleutils.CTRL_LOGOFF_EVENT.GetCode(), consoleutils.CTRL_SHUTDOWN_EVENT.GetCode():
  18. exitChannel <- consoleutils.EventMap[event]
  19. if config.Data().Win32Console.ConsoleCloseRecovery.IsEnable(false) {
  20. logger.Warnf("终端暂时重启,等待程序清理完毕,请勿关闭当前终端!")
  21. logger.Warnf("若不希望重启终端,可在配置文件处关闭。")
  22. err := consoleutils.MakeNewConsole(consoleutils.CodePageUTF8)
  23. if err != nil {
  24. logger.Errorf("win32 make new console failed: %s", err.Error())
  25. }
  26. }
  27. select {
  28. case <-waitExitChannel:
  29. // pass
  30. case <-time.After(4500 * time.Millisecond):
  31. logger.Errorf("Windows Console - 退出清理超时... (%s)", strconvutils.TimeDurationToString(4500*time.Millisecond))
  32. }
  33. return true
  34. case consoleutils.CTRL_C_EVENT.GetCode():
  35. if config.Data().Win32Console.CtrlCExit.IsEnable(true) {
  36. exitChannel <- consoleutils.CTRL_C_EVENT
  37. }
  38. return true
  39. case consoleutils.CTRL_BREAK_EVENT.GetCode():
  40. if config.Data().Win32Console.CtrlBreakExit.IsEnable(true) {
  41. exitChannel <- consoleutils.CTRL_BREAK_EVENT
  42. }
  43. return true
  44. default:
  45. logger.Errorf("未知事件: %d\n", event)
  46. return false
  47. }
  48. }
  49. }
  50. func NewWin32ConsoleExitChannel() (chan consoleutils.Event, chan any, error) {
  51. var exitChannel = make(chan consoleutils.Event)
  52. var waitExitChannel = make(chan any)
  53. if !config.Data().Win32Console.Use {
  54. return exitChannel, waitExitChannel, nil
  55. }
  56. err := consoleutils.SetConsoleCtrlHandler(consoleHandler(exitChannel, waitExitChannel), true)
  57. if err != nil {
  58. return nil, nil, err
  59. }
  60. return exitChannel, waitExitChannel, nil
  61. }