index.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package util
  2. import (
  3. "context"
  4. "log"
  5. "os"
  6. "os/signal"
  7. "path/filepath"
  8. "runtime"
  9. "strings"
  10. "syscall"
  11. )
  12. var Null = struct{}{}
  13. func Clone[T any](x T) *T {
  14. return &x
  15. }
  16. func initFatalLog() *os.File {
  17. fatal_log_dir := "./fatal"
  18. if _fatal_log := os.Getenv("M7S_FATAL_LOG"); _fatal_log != "" {
  19. fatal_log_dir = _fatal_log
  20. }
  21. os.MkdirAll(fatal_log_dir, 0766)
  22. fatal_log := filepath.Join(fatal_log_dir, "latest.log")
  23. info, err := os.Stat(fatal_log)
  24. if err == nil && info.Size() != 0 {
  25. os.Rename(fatal_log, filepath.Join(fatal_log_dir, info.ModTime().Format("2006-01-02 15:04:05")+".log"))
  26. }
  27. logFile, err := os.OpenFile(fatal_log, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
  28. if err != nil {
  29. log.Println("服务启动出错", "打开异常日志文件失败", err)
  30. return nil
  31. }
  32. return logFile
  33. }
  34. func CurrentDir(path ...string) string {
  35. if _, currentFilePath, _, _ := runtime.Caller(1); len(path) == 0 {
  36. return filepath.Dir(currentFilePath)
  37. } else {
  38. return filepath.Join(filepath.Dir(currentFilePath), filepath.Join(path...))
  39. }
  40. }
  41. // 检查文件或目录是否存在
  42. // 如果由 filename 指定的文件或目录存在则返回 true,否则返回 false
  43. func Exist(filename string) bool {
  44. _, err := os.Stat(filename)
  45. return err == nil || os.IsExist(err)
  46. }
  47. func ConvertNum[F Integer, T Integer](from F, to T) T {
  48. return T(from)
  49. }
  50. // Bit1 检查字节中的某一位是否为1 |0|1|2|3|4|5|6|7|
  51. func Bit1(b byte, index int) bool {
  52. return b&(1<<(7-index)) != 0
  53. }
  54. func WaitTerm(cancel context.CancelFunc) {
  55. sigc := make(chan os.Signal, 1)
  56. signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
  57. defer signal.Stop(sigc)
  58. <-sigc
  59. cancel()
  60. }
  61. // 判断目录是否是基础目录的子目录
  62. func IsSubdir(baseDir, joinedDir string) bool {
  63. rel, err := filepath.Rel(baseDir, joinedDir)
  64. if err != nil {
  65. return false
  66. }
  67. return !strings.HasPrefix(rel, "..") && !strings.HasPrefix(rel, "/")
  68. }
  69. func Conditoinal[T any](cond bool, t, f T) T {
  70. if cond {
  71. return t
  72. } else {
  73. return f
  74. }
  75. }