From 4a4ed4baa81208c5ae11c818f808fd9de60a87f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=BB=8B=E6=B6=A6?= <807046079@qq.com> Date: Tue, 12 Nov 2024 23:25:27 +0800 Subject: [PATCH] feat: dynamic root directory and path --- docs/beforeDocsMake/renameModel/main.go | 7 ++-- global/constant/constant.go | 50 ++++++++++++++++++++----- global/cron/enter.go | 6 +-- global/nats/manager/dlq.go | 12 ++++-- global/nats/manager/enter.go | 3 +- global/nats/manager/event.go | 10 +++-- global/nats/manager/task.go | 10 +++-- initialize/initialize.go | 5 +-- initialize/logger.go | 8 ++-- initialize/nats.go | 2 - model/product/enter.go | 6 ++- service/product/bill/reader.go | 8 ++-- service/template/enter.go | 4 +- service/thirdparty/email.go | 14 ++++--- 14 files changed, 99 insertions(+), 46 deletions(-) diff --git a/docs/beforeDocsMake/renameModel/main.go b/docs/beforeDocsMake/renameModel/main.go index e0987785..cf678229 100644 --- a/docs/beforeDocsMake/renameModel/main.go +++ b/docs/beforeDocsMake/renameModel/main.go @@ -2,7 +2,6 @@ package main import ( "bufio" - "github.com/ZiRunHua/LeapLedger/global/constant" "go/ast" "go/parser" "go/token" @@ -10,11 +9,13 @@ import ( "os" "path/filepath" "strings" + + "github.com/ZiRunHua/LeapLedger/global/constant" ) func main() { - handleDir(constant.WORK_PATH + "/api/request/") - handleDir(constant.WORK_PATH + "/api/response/") + handleDir(filepath.Clean(constant.RootDir + "/api/request/")) + handleDir(filepath.Clean(constant.RootDir + "/api/response/")) } func handleDir(path string) { _ = filepath.Walk( diff --git a/global/constant/constant.go b/global/constant/constant.go index 385ff918..e55ca95c 100644 --- a/global/constant/constant.go +++ b/global/constant/constant.go @@ -1,19 +1,26 @@ package constant -type ServerMode string - -var Debug, Production ServerMode = "debug", "production" +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" +) -const WORK_PATH = "/go/LeapLedger" -const RUNTIME_DATA_PATH = WORK_PATH + "/runtime/data" +type ServerMode string -const LOG_PATH = WORK_PATH + "/log" -const DATA_PATH = WORK_PATH + "/data" +const Debug, Production ServerMode = "debug", "production" -var ExampleAccountJsonPath = DATA_PATH + "/template/account/example.json" +var ( + RootDir = getRootDir() + LogPath = filepath.Join(RootDir, "log") + DataPath = filepath.Join(RootDir, "data") + ExampleAccountJsonPath = filepath.Clean(DataPath + "/template/account/example.json") +) // IncomeExpense 收支类型 -type IncomeExpense string //@name IncomeExpense `example:"expense" enums:"income,expense" swaggertype:"string"` +type IncomeExpense string // @name IncomeExpense `example:"expense" enums:"income,expense" swaggertype:"string"` const ( Income IncomeExpense = "income" @@ -82,3 +89,28 @@ const ( // nats type Subject string + +func getRootDir() string { + // `os.Getwd()` is avoided here because, during tests, the working directory is set to the test file’s directory. + // This command retrieves the module's root directory instead. + // Source of `go list` usage: https://stackoverflow.com/a/75943840/23658318 + rootDir, err := exec.Command("go", "list", "-m", "-f", "{{.Dir}}").Output() + if err == nil { + return strings.TrimSpace(string(rootDir)) + } + // If `go list` fails, it may indicate the absence of a Go environment. + // In such cases, this suggests we are not in a test environment, so fall back to `os.Getwd()` to set `RootDir`. + workDir, err := os.Getwd() + if err != nil { + panic(err) + } + // Validate that the directory exists + _, err = os.Stat(workDir) + if err != nil { + if os.IsNotExist(err) { + panic(fmt.Sprintf("Path:%s does not exists", workDir)) + } + panic(err) + } + return workDir +} diff --git a/global/cron/enter.go b/global/cron/enter.go index f8194e56..4b1f6d6c 100644 --- a/global/cron/enter.go +++ b/global/cron/enter.go @@ -2,6 +2,7 @@ package cron import ( "context" + "path/filepath" "github.com/ZiRunHua/LeapLedger/global" "github.com/ZiRunHua/LeapLedger/global/constant" @@ -10,10 +11,9 @@ import ( "go.uber.org/zap" ) -const logPath = constant.LOG_PATH + "/cron.log" - var ( - logger *zap.Logger + logPath = filepath.Join(constant.LogPath, "cron.log") + logger *zap.Logger Scheduler = initialize.Scheduler ) diff --git a/global/nats/manager/dlq.go b/global/nats/manager/dlq.go index 9b6105a6..5f2b5071 100644 --- a/global/nats/manager/dlq.go +++ b/global/nats/manager/dlq.go @@ -4,6 +4,7 @@ package manager import ( "errors" "fmt" + "path/filepath" "github.com/ZiRunHua/LeapLedger/util/dataTool" natsServer "github.com/nats-io/nats-server/v2/server" @@ -25,9 +26,14 @@ type DlqManager interface { RepublishBatch(batch int, ctx context.Context) (int, error) } -const dlqName = "dlq" -const dlqPrefix = "dlq" -const dlqLogPath = natsLogPath + "dlq.log" +const ( + dlqName = "dlq" + dlqPrefix = "dlq" +) + +var ( + dlqLogPath = filepath.Join(natsLogPath, "dlq.log") +) type dlqManager struct { DlqManager diff --git a/global/nats/manager/enter.go b/global/nats/manager/enter.go index 7df8bdee..2d62a05e 100644 --- a/global/nats/manager/enter.go +++ b/global/nats/manager/enter.go @@ -1,6 +1,7 @@ package manager import ( + "path/filepath" "runtime/debug" "github.com/ZiRunHua/LeapLedger/global" @@ -25,7 +26,7 @@ var ( DlqManage DlqManager ) -const natsLogPath = constant.LOG_PATH + "/nats/" +var natsLogPath = filepath.Join(constant.LogPath, "nats") var ( taskLogger *zap.Logger diff --git a/global/nats/manager/event.go b/global/nats/manager/event.go index b119fcfa..64e28e4f 100644 --- a/global/nats/manager/event.go +++ b/global/nats/manager/event.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "path/filepath" "runtime" "time" @@ -26,9 +27,12 @@ type EventManager interface { } const ( - natsEventName = "event" - natsEventPrefix = "event" - natsEventLogPath = natsLogPath + "event.log" + natsEventName = "event" + natsEventPrefix = "event" +) + +var ( + natsEventLogPath = filepath.Join(natsLogPath, "event.log") ) type Event string diff --git a/global/nats/manager/task.go b/global/nats/manager/task.go index 9c7dc8d9..df19a3ba 100644 --- a/global/nats/manager/task.go +++ b/global/nats/manager/task.go @@ -2,6 +2,7 @@ package manager import ( "fmt" + "path/filepath" "runtime" "time" @@ -20,9 +21,12 @@ type TaskManager interface { } const ( - natsTaskName = "task" - natsTaskPrefix = "task" - natsTaskLogPath = natsLogPath + "task.log" + natsTaskName = "task" + natsTaskPrefix = "task" +) + +var ( + natsTaskLogPath = filepath.Join(natsLogPath, "task.log") ) type Task string diff --git a/initialize/initialize.go b/initialize/initialize.go index 187d69d8..641f966a 100644 --- a/initialize/initialize.go +++ b/initialize/initialize.go @@ -3,6 +3,7 @@ package initialize import ( "context" "os" + "path/filepath" "time" "github.com/ZiRunHua/LeapLedger/global/constant" @@ -61,14 +62,12 @@ func init() { } } -const _configDirectoryPath = constant.WORK_PATH - func initConfig() error { configFileName := os.Getenv("CONFIG_FILE_NAME") if len(configFileName) == 0 { configFileName = "config.yaml" } - configPath := _configDirectoryPath + "/" + configFileName + configPath := filepath.Join(constant.RootDir, configFileName) yamlFile, err := os.ReadFile(configPath) if err != nil { return err diff --git a/initialize/logger.go b/initialize/logger.go index 7de5bc54..c6a6170b 100644 --- a/initialize/logger.go +++ b/initialize/logger.go @@ -13,10 +13,10 @@ type _logger struct { encoder zapcore.Encoder } -const ( - _requestLogPath = constant.WORK_PATH + "/log/request.log" - _errorLogPath = constant.WORK_PATH + "/log/error.log" - _panicLogPath = constant.WORK_PATH + "/log/panic.log" +var ( + _requestLogPath = filepath.Join(constant.RootDir, "log", "request.log") + _errorLogPath = filepath.Join(constant.RootDir, "log", "error.log") + _panicLogPath = filepath.Join(constant.RootDir, "log", "panic.log") ) func (l *_logger) do() error { diff --git a/initialize/nats.go b/initialize/nats.go index e36877a9..980d03ba 100644 --- a/initialize/nats.go +++ b/initialize/nats.go @@ -15,8 +15,6 @@ type _nats struct { // NatsDb is used to record and retry failure messages // Enabled in consumer server -const nastStoreDir = constant.RUNTIME_DATA_PATH + "/nats" - func (n *_nats) do() error { err := n.init() if err != nil { diff --git a/model/product/enter.go b/model/product/enter.go index 333fbbcd..c844ef71 100644 --- a/model/product/enter.go +++ b/model/product/enter.go @@ -2,16 +2,18 @@ package productModel import ( "context" + "os" + "path/filepath" + "github.com/ZiRunHua/LeapLedger/global/constant" "github.com/ZiRunHua/LeapLedger/global/cus" "github.com/ZiRunHua/LeapLedger/global/db" "github.com/ZiRunHua/LeapLedger/util/fileTool" "gorm.io/gorm" "gorm.io/gorm/logger" - "os" ) -var initSqlFile = constant.DATA_PATH + "/database/product.sql" +var initSqlFile = filepath.Clean(constant.DataPath + "/database/product.sql") func init() { // table diff --git a/service/product/bill/reader.go b/service/product/bill/reader.go index 2d504999..3e4ce2b6 100644 --- a/service/product/bill/reader.go +++ b/service/product/bill/reader.go @@ -10,6 +10,7 @@ package bill import ( "context" + "path/filepath" "strings" "github.com/ZiRunHua/LeapLedger/global" @@ -22,9 +23,10 @@ import ( "go.uber.org/zap" ) -const logPath = constant.LOG_PATH + "/service/product/bill.log" - -var logger *zap.Logger +var ( + logPath = filepath.Clean(constant.LogPath + "/service/product/bill.log") + logger *zap.Logger +) func init() { var err error diff --git a/service/template/enter.go b/service/template/enter.go index 249f3b58..18f5b3ca 100644 --- a/service/template/enter.go +++ b/service/template/enter.go @@ -3,6 +3,7 @@ package templateService import ( "context" "errors" + "path/filepath" "github.com/ZiRunHua/LeapLedger/global" "github.com/ZiRunHua/LeapLedger/global/constant" @@ -48,7 +49,8 @@ var ( func init() { var err error - if errorLog, err = global.Config.Logger.New(constant.LOG_PATH + "/service/template/error.log"); err != nil { + logPath := filepath.Clean(constant.LogPath + "/service/template/error.log") + if errorLog, err = global.Config.Logger.New(logPath); err != nil { panic(err) } diff --git a/service/thirdparty/email.go b/service/thirdparty/email.go index 1fa82cdc..2443dead 100644 --- a/service/thirdparty/email.go +++ b/service/thirdparty/email.go @@ -3,28 +3,30 @@ package thirdpartyService import ( "bytes" "fmt" + "os" + "path/filepath" + "time" + "github.com/ZiRunHua/LeapLedger/global" "github.com/ZiRunHua/LeapLedger/global/constant" userModel "github.com/ZiRunHua/LeapLedger/model/user" commonService "github.com/ZiRunHua/LeapLedger/service/common" "github.com/ZiRunHua/LeapLedger/util/rand" "github.com/pkg/errors" - "os" - "time" ) var emailTemplate map[constant.Notification][]byte var emailTemplateFilePath = map[constant.Notification]string{ - constant.NotificationOfCaptcha: "/template/email/captcha.html", - constant.NotificationOfRegistrationSuccess: "/template/email/registerSuccess.html", - constant.NotificationOfUpdatePassword: "/template/email/updatePassword.html", + constant.NotificationOfCaptcha: filepath.Clean("/template/email/captcha.html"), + constant.NotificationOfRegistrationSuccess: filepath.Clean("/template/email/registerSuccess.html"), + constant.NotificationOfUpdatePassword: filepath.Clean("/template/email/updatePassword.html"), } func init() { emailTemplate = make(map[constant.Notification][]byte, len(emailTemplateFilePath)) var err error for notification, path := range emailTemplateFilePath { - if emailTemplate[notification], err = os.ReadFile(constant.DATA_PATH + path); err != nil { + if emailTemplate[notification], err = os.ReadFile(filepath.Clean(constant.DataPath + path)); err != nil { panic(err) } }