code refactor

This commit is contained in:
MaysWind
2025-08-04 20:43:33 +08:00
parent d35e127b9e
commit 84523d8b8a
18 changed files with 163 additions and 95 deletions
+2 -2
View File
@@ -81,13 +81,13 @@ func sendTestMail(c *core.CliContext) error {
return err return err
} }
if !config.EnableSMTP || mail.Container.Current == nil { if !config.EnableSMTP {
return errs.ErrSMTPServerNotEnabled return errs.ErrSMTPServerNotEnabled
} }
toAddress := c.String("to") toAddress := c.String("to")
err = mail.Container.Current.SendMail(&mail.MailMessage{ err = mail.Container.SendMail(&mail.MailMessage{
To: toAddress, To: toAddress,
Subject: "ezBookkeeping test e-mail", Subject: "ezBookkeeping test e-mail",
Body: "This is a test e-mail", Body: "This is a test e-mail",
+1 -1
View File
@@ -79,7 +79,7 @@ func startWebServer(c *core.CliContext) error {
return err return err
} }
serverInfo := fmt.Sprintf("current server id is %d, current instance id is %d", requestid.Container.Current.GetCurrentServerUniqId(), requestid.Container.Current.GetCurrentInstanceUniqId()) serverInfo := fmt.Sprintf("current server id is %d, current instance id is %d", requestid.Container.GetCurrentServerUniqId(), requestid.Container.GetCurrentInstanceUniqId())
uuidServerInfo := "" uuidServerInfo := ""
if config.UuidGeneratorType == settings.InternalUuidGeneratorType { if config.UuidGeneratorType == settings.InternalUuidGeneratorType {
uuidServerInfo = fmt.Sprintf(", current uuid server id is %d", config.UuidServerId) uuidServerInfo = fmt.Sprintf(", current uuid server id is %d", config.UuidServerId)
+10 -10
View File
@@ -23,7 +23,7 @@ type ApiUsingConfig struct {
// CurrentConfig returns the current config // CurrentConfig returns the current config
func (a *ApiUsingConfig) CurrentConfig() *settings.Config { func (a *ApiUsingConfig) CurrentConfig() *settings.Config {
return a.container.Current return a.container.GetCurrentConfig()
} }
// GetTransactionPictureInfoResponse returns the view-object of transaction picture basic info according to the transaction picture model // GetTransactionPictureInfoResponse returns the view-object of transaction picture basic info according to the transaction picture model
@@ -53,15 +53,15 @@ func (a *ApiUsingConfig) GetAfterRegisterNotificationContent(userLanguage string
language = clientLanguage language = clientLanguage
} }
if !a.container.Current.AfterRegisterNotification.Enabled { if !a.CurrentConfig().AfterRegisterNotification.Enabled {
return "" return ""
} }
if multiLanguageContent, exists := a.container.Current.AfterRegisterNotification.MultiLanguageContent[language]; exists { if multiLanguageContent, exists := a.CurrentConfig().AfterRegisterNotification.MultiLanguageContent[language]; exists {
return multiLanguageContent return multiLanguageContent
} }
return a.container.Current.AfterRegisterNotification.DefaultContent return a.CurrentConfig().AfterRegisterNotification.DefaultContent
} }
// GetAfterLoginNotificationContent returns the notification content displayed each time users log in // GetAfterLoginNotificationContent returns the notification content displayed each time users log in
@@ -72,15 +72,15 @@ func (a *ApiUsingConfig) GetAfterLoginNotificationContent(userLanguage string, c
language = clientLanguage language = clientLanguage
} }
if !a.container.Current.AfterLoginNotification.Enabled { if !a.CurrentConfig().AfterLoginNotification.Enabled {
return "" return ""
} }
if multiLanguageContent, exists := a.container.Current.AfterLoginNotification.MultiLanguageContent[language]; exists { if multiLanguageContent, exists := a.CurrentConfig().AfterLoginNotification.MultiLanguageContent[language]; exists {
return multiLanguageContent return multiLanguageContent
} }
return a.container.Current.AfterLoginNotification.DefaultContent return a.CurrentConfig().AfterLoginNotification.DefaultContent
} }
// GetAfterOpenNotificationContent returns the notification content displayed each time users open the app // GetAfterOpenNotificationContent returns the notification content displayed each time users open the app
@@ -91,15 +91,15 @@ func (a *ApiUsingConfig) GetAfterOpenNotificationContent(userLanguage string, cl
language = clientLanguage language = clientLanguage
} }
if !a.container.Current.AfterOpenNotification.Enabled { if !a.CurrentConfig().AfterOpenNotification.Enabled {
return "" return ""
} }
if multiLanguageContent, exists := a.container.Current.AfterOpenNotification.MultiLanguageContent[language]; exists { if multiLanguageContent, exists := a.CurrentConfig().AfterOpenNotification.MultiLanguageContent[language]; exists {
return multiLanguageContent return multiLanguageContent
} }
return a.container.Current.AfterOpenNotification.DefaultContent return a.CurrentConfig().AfterOpenNotification.DefaultContent
} }
// ApiUsingDuplicateChecker represents an api that need to use duplicate checker // ApiUsingDuplicateChecker represents an api that need to use duplicate checker
+1 -7
View File
@@ -30,13 +30,7 @@ var (
// LatestExchangeRateHandler returns latest exchange rate data // LatestExchangeRateHandler returns latest exchange rate data
func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.WebContext) (any, *errs.Error) { func (a *ExchangeRatesApi) LatestExchangeRateHandler(c *core.WebContext) (any, *errs.Error) {
dataSource := exchangerates.Container.Current exchangeRateResponse, err := exchangerates.Container.GetLatestExchangeRates(c, c.GetCurrentUid(), a.CurrentConfig())
if dataSource == nil {
return nil, errs.ErrInvalidExchangeRatesDataSource
}
exchangeRateResponse, err := dataSource.GetLatestExchangeRates(c, c.GetCurrentUid(), a.container.Current)
if err != nil { if err != nil {
return nil, errs.Or(err, errs.ErrOperationFailed) return nil, errs.Or(err, errs.ErrOperationFailed)
+9 -5
View File
@@ -9,7 +9,7 @@ import (
// AvatarProviderContainer contains the current user avatar provider // AvatarProviderContainer contains the current user avatar provider
type AvatarProviderContainer struct { type AvatarProviderContainer struct {
Current AvatarProvider current AvatarProvider
} }
// Initialize a user avatar provider container singleton instance // Initialize a user avatar provider container singleton instance
@@ -20,13 +20,13 @@ var (
// InitializeAvatarProvider initializes the current user avatar provider according to the config // InitializeAvatarProvider initializes the current user avatar provider according to the config
func InitializeAvatarProvider(config *settings.Config) error { func InitializeAvatarProvider(config *settings.Config) error {
if config.AvatarProvider == core.USER_AVATAR_PROVIDER_INTERNAL { if config.AvatarProvider == core.USER_AVATAR_PROVIDER_INTERNAL {
Container.Current = NewInternalStorageAvatarProvider(config) Container.current = NewInternalStorageAvatarProvider(config)
return nil return nil
} else if config.AvatarProvider == core.USER_AVATAR_PROVIDER_GRAVATAR { } else if config.AvatarProvider == core.USER_AVATAR_PROVIDER_GRAVATAR {
Container.Current = NewGravatarAvatarProvider() Container.current = NewGravatarAvatarProvider()
return nil return nil
} else if config.AvatarProvider == "" { } else if config.AvatarProvider == "" {
Container.Current = NewNullAvatarProvider() Container.current = NewNullAvatarProvider()
return nil return nil
} }
@@ -35,5 +35,9 @@ func InitializeAvatarProvider(config *settings.Config) error {
// GetAvatarUrl returns the avatar url by the current user avatar provider // GetAvatarUrl returns the avatar url by the current user avatar provider
func (p *AvatarProviderContainer) GetAvatarUrl(user *models.User) string { func (p *AvatarProviderContainer) GetAvatarUrl(user *models.User) string {
return p.Current.GetAvatarUrl(user) if p.current == nil {
return ""
}
return p.current.GetAvatarUrl(user)
} }
+1 -1
View File
@@ -9,5 +9,5 @@ type CliUsingConfig struct {
// CurrentConfig returns the current config // CurrentConfig returns the current config
func (l *CliUsingConfig) CurrentConfig() *settings.Config { func (l *CliUsingConfig) CurrentConfig() *settings.Config {
return l.container.Current return l.container.GetCurrentConfig()
} }
+1 -1
View File
@@ -95,7 +95,7 @@ func TestCronJobSchedulerContainerRepeatRun(t *testing.T) {
InMemoryDuplicateCheckerCleanupIntervalDuration: 60 * time.Second, InMemoryDuplicateCheckerCleanupIntervalDuration: 60 * time.Second,
}) })
duplicatechecker.Container.Current = checker duplicatechecker.SetDuplicateChecker(checker)
container := &CronJobSchedulerContainer{ container := &CronJobSchedulerContainer{
allJobsMap: make(map[string]*CronJob), allJobsMap: make(map[string]*CronJob),
+1 -1
View File
@@ -22,7 +22,7 @@ func (j *CronJob) doRun() {
start := time.Now() start := time.Now()
c := core.NewCronJobContext(j.Name, j.Period.GetInterval()) c := core.NewCronJobContext(j.Name, j.Period.GetInterval())
if duplicatechecker.Container.Current != nil { if duplicatechecker.Container.IsEnabled() {
localAddr, err := utils.GetLocalIPAddressesString() localAddr, err := utils.GetLocalIPAddressesString()
if err != nil { if err != nil {
@@ -9,7 +9,7 @@ import (
// DuplicateCheckerContainer contains the current duplicate checker // DuplicateCheckerContainer contains the current duplicate checker
type DuplicateCheckerContainer struct { type DuplicateCheckerContainer struct {
Current DuplicateChecker current DuplicateChecker
} }
// Initialize a duplicate checker container singleton instance // Initialize a duplicate checker container singleton instance
@@ -21,7 +21,7 @@ var (
func InitializeDuplicateChecker(config *settings.Config) error { func InitializeDuplicateChecker(config *settings.Config) error {
if config.DuplicateCheckerType == settings.InMemoryDuplicateCheckerType { if config.DuplicateCheckerType == settings.InMemoryDuplicateCheckerType {
checker, err := NewInMemoryDuplicateChecker(config) checker, err := NewInMemoryDuplicateChecker(config)
Container.Current = checker Container.current = checker
return err return err
} }
@@ -29,37 +29,75 @@ func InitializeDuplicateChecker(config *settings.Config) error {
return errs.ErrInvalidDuplicateCheckerType return errs.ErrInvalidDuplicateCheckerType
} }
// SetDuplicateChecker sets the current duplicate checker
func SetDuplicateChecker(checker DuplicateChecker) {
Container.current = checker
}
// IsEnabled returns whether the duplicate checker is enabled
func (c *DuplicateCheckerContainer) IsEnabled() bool {
return c.current != nil
}
// GetSubmissionRemark returns whether the same submission has been processed and related remark by the current duplicate checker // GetSubmissionRemark returns whether the same submission has been processed and related remark by the current duplicate checker
func (c *DuplicateCheckerContainer) GetSubmissionRemark(checkerType DuplicateCheckerType, uid int64, identification string) (bool, string) { func (c *DuplicateCheckerContainer) GetSubmissionRemark(checkerType DuplicateCheckerType, uid int64, identification string) (bool, string) {
return c.Current.GetSubmissionRemark(checkerType, uid, identification) if c.current == nil {
return false, ""
}
return c.current.GetSubmissionRemark(checkerType, uid, identification)
} }
// SetSubmissionRemark saves the identification and remark by the current duplicate checker // SetSubmissionRemark saves the identification and remark by the current duplicate checker
func (c *DuplicateCheckerContainer) SetSubmissionRemark(checkerType DuplicateCheckerType, uid int64, identification string, remark string) { func (c *DuplicateCheckerContainer) SetSubmissionRemark(checkerType DuplicateCheckerType, uid int64, identification string, remark string) {
c.Current.SetSubmissionRemark(checkerType, uid, identification, remark) if c.current == nil {
return
}
c.current.SetSubmissionRemark(checkerType, uid, identification, remark)
} }
// RemoveSubmissionRemark removes the identification and remark by the current duplicate checker // RemoveSubmissionRemark removes the identification and remark by the current duplicate checker
func (c *DuplicateCheckerContainer) RemoveSubmissionRemark(checkerType DuplicateCheckerType, uid int64, identification string) { func (c *DuplicateCheckerContainer) RemoveSubmissionRemark(checkerType DuplicateCheckerType, uid int64, identification string) {
c.Current.RemoveSubmissionRemark(checkerType, uid, identification) if c.current == nil {
return
}
c.current.RemoveSubmissionRemark(checkerType, uid, identification)
} }
// GetOrSetCronJobRunningInfo returns the running info when the cron job is running or saves the running info by the current duplicate checker // GetOrSetCronJobRunningInfo returns the running info when the cron job is running or saves the running info by the current duplicate checker
func (c *DuplicateCheckerContainer) GetOrSetCronJobRunningInfo(jobName string, runningInfo string, runningInterval time.Duration) (bool, string) { func (c *DuplicateCheckerContainer) GetOrSetCronJobRunningInfo(jobName string, runningInfo string, runningInterval time.Duration) (bool, string) {
return c.Current.GetOrSetCronJobRunningInfo(jobName, runningInfo, runningInterval) if c.current == nil {
return false, ""
}
return c.current.GetOrSetCronJobRunningInfo(jobName, runningInfo, runningInterval)
} }
// RemoveCronJobRunningInfo removes the running info of the cron job by the current duplicate checker // RemoveCronJobRunningInfo removes the running info of the cron job by the current duplicate checker
func (c *DuplicateCheckerContainer) RemoveCronJobRunningInfo(jobName string) { func (c *DuplicateCheckerContainer) RemoveCronJobRunningInfo(jobName string) {
c.Current.RemoveCronJobRunningInfo(jobName) if c.current == nil {
return
}
c.current.RemoveCronJobRunningInfo(jobName)
} }
// GetFailureCount returns the failure count of the specified failure key // GetFailureCount returns the failure count of the specified failure key
func (c *DuplicateCheckerContainer) GetFailureCount(failureKey string) uint32 { func (c *DuplicateCheckerContainer) GetFailureCount(failureKey string) uint32 {
return c.Current.GetFailureCount(failureKey) if c.current == nil {
return 0
}
return c.current.GetFailureCount(failureKey)
} }
// IncreaseFailureCount increases the failure count of the specified failure key // IncreaseFailureCount increases the failure count of the specified failure key
func (c *DuplicateCheckerContainer) IncreaseFailureCount(failureKey string) uint32 { func (c *DuplicateCheckerContainer) IncreaseFailureCount(failureKey string) uint32 {
return c.Current.IncreaseFailureCount(failureKey) if c.current == nil {
return 0
}
return c.current.IncreaseFailureCount(failureKey)
} }
@@ -1,13 +1,15 @@
package exchangerates package exchangerates
import ( import (
"github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/errs" "github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/models"
"github.com/mayswind/ezbookkeeping/pkg/settings" "github.com/mayswind/ezbookkeeping/pkg/settings"
) )
// ExchangeRatesDataSourceContainer contains the current exchange rates data source // ExchangeRatesDataSourceContainer contains the current exchange rates data source
type ExchangeRatesDataSourceContainer struct { type ExchangeRatesDataSourceContainer struct {
Current ExchangeRatesDataSource current ExchangeRatesDataSource
} }
// Initialize a exchange rates data source container singleton instance // Initialize a exchange rates data source container singleton instance
@@ -18,60 +20,69 @@ var (
// InitializeExchangeRatesDataSource initializes the current exchange rates data source according to the config // InitializeExchangeRatesDataSource initializes the current exchange rates data source according to the config
func InitializeExchangeRatesDataSource(config *settings.Config) error { func InitializeExchangeRatesDataSource(config *settings.Config) error {
if config.ExchangeRatesDataSource == settings.ReserveBankOfAustraliaDataSource { if config.ExchangeRatesDataSource == settings.ReserveBankOfAustraliaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&ReserveBankOfAustraliaDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&ReserveBankOfAustraliaDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.BankOfCanadaDataSource { } else if config.ExchangeRatesDataSource == settings.BankOfCanadaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&BankOfCanadaDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&BankOfCanadaDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.CzechNationalBankDataSource { } else if config.ExchangeRatesDataSource == settings.CzechNationalBankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&CzechNationalBankDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&CzechNationalBankDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.DanmarksNationalbankDataSource { } else if config.ExchangeRatesDataSource == settings.DanmarksNationalbankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&DanmarksNationalbankDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&DanmarksNationalbankDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.EuroCentralBankDataSource { } else if config.ExchangeRatesDataSource == settings.EuroCentralBankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&EuroCentralBankDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&EuroCentralBankDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.NationalBankOfGeorgiaDataSource { } else if config.ExchangeRatesDataSource == settings.NationalBankOfGeorgiaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NationalBankOfGeorgiaDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&NationalBankOfGeorgiaDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.CentralBankOfHungaryDataSource { } else if config.ExchangeRatesDataSource == settings.CentralBankOfHungaryDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&CentralBankOfHungaryDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&CentralBankOfHungaryDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.BankOfIsraelDataSource { } else if config.ExchangeRatesDataSource == settings.BankOfIsraelDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&BankOfIsraelDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&BankOfIsraelDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.CentralBankOfMyanmarDataSource { } else if config.ExchangeRatesDataSource == settings.CentralBankOfMyanmarDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&CentralBankOfMyanmarDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&CentralBankOfMyanmarDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.NorgesBankDataSource { } else if config.ExchangeRatesDataSource == settings.NorgesBankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NorgesBankDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&NorgesBankDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.NationalBankOfPolandDataSource { } else if config.ExchangeRatesDataSource == settings.NationalBankOfPolandDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NationalBankOfPolandDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&NationalBankOfPolandDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.NationalBankOfRomaniaDataSource { } else if config.ExchangeRatesDataSource == settings.NationalBankOfRomaniaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NationalBankOfRomaniaDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&NationalBankOfRomaniaDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.BankOfRussiaDataSource { } else if config.ExchangeRatesDataSource == settings.BankOfRussiaDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&BankOfRussiaDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&BankOfRussiaDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.SwissNationalBankDataSource { } else if config.ExchangeRatesDataSource == settings.SwissNationalBankDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&SwissNationalBankDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&SwissNationalBankDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.NationalBankOfUkraineDataSource { } else if config.ExchangeRatesDataSource == settings.NationalBankOfUkraineDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&NationalBankOfUkraineDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&NationalBankOfUkraineDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.CentralBankOfUzbekistanDataSource { } else if config.ExchangeRatesDataSource == settings.CentralBankOfUzbekistanDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&CentralBankOfUzbekistanDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&CentralBankOfUzbekistanDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.InternationalMonetaryFundDataSource { } else if config.ExchangeRatesDataSource == settings.InternationalMonetaryFundDataSource {
Container.Current = newCommonHttpExchangeRatesDataSource(&InternationalMonetaryFundDataSource{}) Container.current = newCommonHttpExchangeRatesDataSource(&InternationalMonetaryFundDataSource{})
return nil return nil
} else if config.ExchangeRatesDataSource == settings.UserCustomExchangeRatesDataSource { } else if config.ExchangeRatesDataSource == settings.UserCustomExchangeRatesDataSource {
Container.Current = newUserCustomExchangeRatesDataSource() Container.current = newUserCustomExchangeRatesDataSource()
return nil return nil
} }
return errs.ErrInvalidExchangeRatesDataSource return errs.ErrInvalidExchangeRatesDataSource
} }
// GetLatestExchangeRates returns the latest exchange rates data from the current exchange rates data source
func (e *ExchangeRatesDataSourceContainer) GetLatestExchangeRates(c core.Context, uid int64, currentConfig *settings.Config) (*models.LatestExchangeRateResponse, error) {
if Container.current == nil {
return nil, errs.ErrInvalidExchangeRatesDataSource
}
return e.current.GetLatestExchangeRates(c, uid, currentConfig)
}
@@ -326,15 +326,12 @@ func executeLatestExchangeRateHandler(t *testing.T, dataSourceType string) *mode
err := InitializeExchangeRatesDataSource(config) err := InitializeExchangeRatesDataSource(config)
assert.Nil(t, err) assert.Nil(t, err)
dataSource := Container.Current
assert.NotNil(t, dataSource)
ginContext, _ := gin.CreateTestContext(httptest.NewRecorder()) ginContext, _ := gin.CreateTestContext(httptest.NewRecorder())
context := &core.WebContext{ context := &core.WebContext{
Context: ginContext, Context: ginContext,
} }
exchangeRateResponse, err := dataSource.GetLatestExchangeRates(context, context.GetCurrentUid(), config) exchangeRateResponse, err := Container.GetLatestExchangeRates(context, context.GetCurrentUid(), config)
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, exchangeRateResponse) assert.NotNil(t, exchangeRateResponse)
+10 -5
View File
@@ -1,12 +1,13 @@
package mail package mail
import ( import (
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/settings" "github.com/mayswind/ezbookkeeping/pkg/settings"
) )
// MailerContainer contains the current mailer // MailerContainer contains the current mailer
type MailerContainer struct { type MailerContainer struct {
Current Mailer current Mailer
} }
// Initialize a mailer container singleton instance // Initialize a mailer container singleton instance
@@ -17,7 +18,7 @@ var (
// InitializeMailer initializes the current mailer according to the config // InitializeMailer initializes the current mailer according to the config
func InitializeMailer(config *settings.Config) error { func InitializeMailer(config *settings.Config) error {
if !config.EnableSMTP { if !config.EnableSMTP {
Container.Current = nil Container.current = nil
return nil return nil
} }
@@ -27,11 +28,15 @@ func InitializeMailer(config *settings.Config) error {
return err return err
} }
Container.Current = mailer Container.current = mailer
return nil return nil
} }
// SendMail sends an email according to argument // SendMail sends an email according to argument
func (u *MailerContainer) SendMail(message *MailMessage) error { func (m *MailerContainer) SendMail(message *MailMessage) error {
return u.Current.SendMail(message) if m.current == nil {
return errs.ErrSMTPServerNotEnabled
}
return m.current.SendMail(message)
} }
@@ -68,13 +68,7 @@ func (h *mcpQueryLatestExchangeRatesToolHandler) Handle(c *core.WebContext, call
return nil, nil, errs.ErrIncompleteOrIncorrectSubmission return nil, nil, errs.ErrIncompleteOrIncorrectSubmission
} }
dataSource := exchangerates.Container.Current exchangeRateResponse, err := exchangerates.Container.GetLatestExchangeRates(c, user.Uid, currentConfig)
if dataSource == nil {
return nil, nil, errs.ErrInvalidExchangeRatesDataSource
}
exchangeRateResponse, err := dataSource.GetLatestExchangeRates(c, user.Uid, currentConfig)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
+1 -6
View File
@@ -11,12 +11,7 @@ const requestIdHeader = "X-Request-ID"
// RequestId generates a new request id and add it to context and response header // RequestId generates a new request id and add it to context and response header
func RequestId(config *settings.Config) core.MiddlewareHandlerFunc { func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
return func(c *core.WebContext) { return func(c *core.WebContext) {
if requestid.Container.Current == nil { requestId := requestid.Container.GenerateRequestId(c.ClientIP(), c.ClientPort())
c.Next()
return
}
requestId := requestid.Container.Current.GenerateRequestId(c.ClientIP(), c.ClientPort())
c.SetContextId(requestId) c.SetContextId(requestId)
if config.EnableRequestIdHeader { if config.EnableRequestIdHeader {
+26 -4
View File
@@ -7,7 +7,7 @@ import (
// RequestIdContainer contains the current request id generator // RequestIdContainer contains the current request id generator
type RequestIdContainer struct { type RequestIdContainer struct {
Current RequestIdGenerator current RequestIdGenerator
} }
// Initialize a request id container singleton instance // Initialize a request id container singleton instance
@@ -23,11 +23,33 @@ func InitializeRequestIdGenerator(c core.Context, config *settings.Config) error
return err return err
} }
Container.Current = generator Container.current = generator
return nil return nil
} }
// GenerateRequestId returns a new request id by the current request id generator // GenerateRequestId returns a new request id by the current request id generator
func (u *RequestIdContainer) GenerateRequestId(clientIpAddr string, clientPort uint16) string { func (r *RequestIdContainer) GenerateRequestId(clientIpAddr string, clientPort uint16) string {
return u.Current.GenerateRequestId(clientIpAddr, clientPort) if r.current == nil {
return ""
}
return r.current.GenerateRequestId(clientIpAddr, clientPort)
}
// GetCurrentServerUniqId returns current server unique id
func (r *RequestIdContainer) GetCurrentServerUniqId() uint16 {
if r.current == nil {
return 0
}
return r.current.GetCurrentServerUniqId()
}
// GetCurrentInstanceUniqId returns current application instance unique id
func (r *RequestIdContainer) GetCurrentInstanceUniqId() uint16 {
if r.current == nil {
return 0
}
return r.current.GetCurrentInstanceUniqId()
} }
+2 -7
View File
@@ -6,7 +6,6 @@ import (
"github.com/mayswind/ezbookkeeping/pkg/core" "github.com/mayswind/ezbookkeeping/pkg/core"
"github.com/mayswind/ezbookkeeping/pkg/datastore" "github.com/mayswind/ezbookkeeping/pkg/datastore"
"github.com/mayswind/ezbookkeeping/pkg/errs"
"github.com/mayswind/ezbookkeeping/pkg/mail" "github.com/mayswind/ezbookkeeping/pkg/mail"
"github.com/mayswind/ezbookkeeping/pkg/settings" "github.com/mayswind/ezbookkeeping/pkg/settings"
"github.com/mayswind/ezbookkeeping/pkg/storage" "github.com/mayswind/ezbookkeeping/pkg/storage"
@@ -61,7 +60,7 @@ type ServiceUsingConfig struct {
// CurrentConfig returns the current config // CurrentConfig returns the current config
func (s *ServiceUsingConfig) CurrentConfig() *settings.Config { func (s *ServiceUsingConfig) CurrentConfig() *settings.Config {
return s.container.Current return s.container.GetCurrentConfig()
} }
// ServiceUsingMailer represents a service that need to use mailer // ServiceUsingMailer represents a service that need to use mailer
@@ -71,11 +70,7 @@ type ServiceUsingMailer struct {
// SendMail sends an email according to argument // SendMail sends an email according to argument
func (s *ServiceUsingMailer) SendMail(message *mail.MailMessage) error { func (s *ServiceUsingMailer) SendMail(message *mail.MailMessage) error {
if s.container.Current == nil { return s.container.SendMail(message)
return errs.ErrSMTPServerNotEnabled
}
return s.container.Current.SendMail(message)
} }
// ServiceUsingUuid represents a service that need to use uuid // ServiceUsingUuid represents a service that need to use uuid
+7 -2
View File
@@ -2,7 +2,7 @@ package settings
// ConfigContainer contains the current setting config // ConfigContainer contains the current setting config
type ConfigContainer struct { type ConfigContainer struct {
Current *Config current *Config
} }
// Initialize a config container singleton instance // Initialize a config container singleton instance
@@ -15,5 +15,10 @@ var (
// SetCurrentConfig sets the current config by a given config // SetCurrentConfig sets the current config by a given config
func SetCurrentConfig(config *Config) { func SetCurrentConfig(config *Config) {
Container.Current = config Container.current = config
}
// GetCurrentConfig returns the current config
func (c *ConfigContainer) GetCurrentConfig() *Config {
return c.current
} }
+12 -4
View File
@@ -7,7 +7,7 @@ import (
// UuidContainer contains the current uuid generator // UuidContainer contains the current uuid generator
type UuidContainer struct { type UuidContainer struct {
Current UuidGenerator current UuidGenerator
} }
// Initialize a uuid container singleton instance // Initialize a uuid container singleton instance
@@ -19,7 +19,7 @@ var (
func InitializeUuidGenerator(config *settings.Config) error { func InitializeUuidGenerator(config *settings.Config) error {
if config.UuidGeneratorType == settings.InternalUuidGeneratorType { if config.UuidGeneratorType == settings.InternalUuidGeneratorType {
generator, err := NewInternalUuidGenerator(config) generator, err := NewInternalUuidGenerator(config)
Container.Current = generator Container.current = generator
return err return err
} }
@@ -29,10 +29,18 @@ func InitializeUuidGenerator(config *settings.Config) error {
// GenerateUuid returns a new uuid by the current uuid generator // GenerateUuid returns a new uuid by the current uuid generator
func (u *UuidContainer) GenerateUuid(uuidType UuidType) int64 { func (u *UuidContainer) GenerateUuid(uuidType UuidType) int64 {
return u.Current.GenerateUuid(uuidType) if u.current == nil {
return 0
}
return u.current.GenerateUuid(uuidType)
} }
// GenerateUuids returns new uuids by the current uuid generator // GenerateUuids returns new uuids by the current uuid generator
func (u *UuidContainer) GenerateUuids(uuidType UuidType, count uint16) []int64 { func (u *UuidContainer) GenerateUuids(uuidType UuidType, count uint16) []int64 {
return u.Current.GenerateUuids(uuidType, count) if u.current == nil {
return nil
}
return u.current.GenerateUuids(uuidType, count)
} }