code refactor
This commit is contained in:
+1
-1
@@ -62,7 +62,7 @@ func startWebServer(c *cli.Context) error {
|
|||||||
|
|
||||||
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.Current.GetCurrentServerUniqId(), requestid.Container.Current.GetCurrentInstanceUniqId())
|
||||||
uuidServerInfo := ""
|
uuidServerInfo := ""
|
||||||
if config.UuidGeneratorType == settings.UUID_GENERATOR_TYPE_INTERNAL {
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,13 +9,13 @@ import (
|
|||||||
"github.com/mayswind/lab/cmd"
|
"github.com/mayswind/lab/cmd"
|
||||||
)
|
)
|
||||||
|
|
||||||
const LAB_VERSION = "0.1.0"
|
const labVersion = "0.1.0"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
app := &cli.App{
|
app := &cli.App{
|
||||||
Name: "lab",
|
Name: "lab",
|
||||||
Usage: "A lightweight account book app hosted by yourself.",
|
Usage: "A lightweight account book app hosted by yourself.",
|
||||||
Version: LAB_VERSION,
|
Version: labVersion,
|
||||||
Commands: []*cli.Command{
|
Commands: []*cli.Command{
|
||||||
cmd.WebServer,
|
cmd.WebServer,
|
||||||
cmd.Database,
|
cmd.Database,
|
||||||
|
|||||||
+3
-3
@@ -53,7 +53,7 @@ func (a *AccountsApi) AccountListHandler(c *core.Context) (interface{}, *errs.Er
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if userAccountResp.ParentId <= models.ACCOUNT_PARENT_ID_LEVEL_ONE {
|
if userAccountResp.ParentId <= models.LevelOneAccountParentId {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ func (a *AccountsApi) AccountListHandler(c *core.Context) (interface{}, *errs.Er
|
|||||||
userFinalAccountResps := make(models.AccountInfoResponseSlice, 0, len(userAllAccountResps))
|
userFinalAccountResps := make(models.AccountInfoResponseSlice, 0, len(userAllAccountResps))
|
||||||
|
|
||||||
for i := 0; i < len(userAllAccountResps); i++ {
|
for i := 0; i < len(userAllAccountResps); i++ {
|
||||||
if userAllAccountResps[i].ParentId == models.ACCOUNT_PARENT_ID_LEVEL_ONE && (!accountListReq.VisibleOnly || !userAllAccountResps[i].Hidden) {
|
if userAllAccountResps[i].ParentId == models.LevelOneAccountParentId && (!accountListReq.VisibleOnly || !userAllAccountResps[i].Hidden) {
|
||||||
sort.Sort(userAllAccountResps[i].SubAccounts)
|
sort.Sort(userAllAccountResps[i].SubAccounts)
|
||||||
userFinalAccountResps = append(userFinalAccountResps, userAllAccountResps[i])
|
userFinalAccountResps = append(userFinalAccountResps, userAllAccountResps[i])
|
||||||
}
|
}
|
||||||
@@ -142,7 +142,7 @@ func (a *AccountsApi) AccountCreateHandler(c *core.Context) (interface{}, *errs.
|
|||||||
return nil, errs.ErrAccountHaveNoSubAccount
|
return nil, errs.ErrAccountHaveNoSubAccount
|
||||||
}
|
}
|
||||||
|
|
||||||
if accountCreateReq.Currency != validators.PARENT_ACCOUNT_CURRENCY_PLACEHODLER {
|
if accountCreateReq.Currency != validators.ParentAccountCurrencyPlaceholder {
|
||||||
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] parent account cannot set currency")
|
log.WarnfWithRequestId(c, "[accounts.AccountCreateHandler] parent account cannot set currency")
|
||||||
return nil, errs.ErrParentAccountCannotSetCurrency
|
return nil, errs.ErrParentAccountCannotSetCurrency
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -335,7 +335,7 @@ func (a *TransactionCategoriesApi) getTransactionCategoryListByTypeResponse(cate
|
|||||||
for i := 0; i < len(categoryResps); i++ {
|
for i := 0; i < len(categoryResps); i++ {
|
||||||
categoryResp := categoryResps[i]
|
categoryResp := categoryResps[i]
|
||||||
|
|
||||||
if categoryResp.ParentId <= models.TRANSACTION_PARENT_ID_LEVEL_ONE {
|
if categoryResp.ParentId <= models.LevelOneTransactionParentId {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -351,7 +351,7 @@ func (a *TransactionCategoriesApi) getTransactionCategoryListByTypeResponse(cate
|
|||||||
finalCategoryResps := make(models.TransactionCategoryInfoResponseSlice, 0)
|
finalCategoryResps := make(models.TransactionCategoryInfoResponseSlice, 0)
|
||||||
|
|
||||||
for i := 0; i < len(categoryResps); i++ {
|
for i := 0; i < len(categoryResps); i++ {
|
||||||
if parentId <= 0 && categoryResps[i].ParentId == models.TRANSACTION_PARENT_ID_LEVEL_ONE {
|
if parentId <= 0 && categoryResps[i].ParentId == models.LevelOneTransactionParentId {
|
||||||
sort.Sort(categoryResps[i].SubCategories)
|
sort.Sort(categoryResps[i].SubCategories)
|
||||||
finalCategoryResps = append(finalCategoryResps, categoryResps[i])
|
finalCategoryResps = append(finalCategoryResps, categoryResps[i])
|
||||||
} else if parentId > 0 && categoryResps[i].ParentId == parentId {
|
} else if parentId > 0 && categoryResps[i].ParentId == parentId {
|
||||||
|
|||||||
+9
-9
@@ -8,9 +8,9 @@ import (
|
|||||||
"github.com/mayswind/lab/pkg/errs"
|
"github.com/mayswind/lab/pkg/errs"
|
||||||
)
|
)
|
||||||
|
|
||||||
const FIELD_REQUEST_ID_KEY = "REQUEST_ID"
|
const requestIdFieldKey = "REQUEST_ID"
|
||||||
const FIELD_TOKEN_CLAIMS_KEY = "TOKEN_CLAIMS"
|
const tokenClaimsFieldKey = "TOKEN_CLAIMS"
|
||||||
const FIELD_RESPONSE_ERROR = "RESPONSE_ERROR"
|
const responseErrorFieldKey = "RESPONSE_ERROR"
|
||||||
|
|
||||||
type Context struct {
|
type Context struct {
|
||||||
*gin.Context
|
*gin.Context
|
||||||
@@ -18,11 +18,11 @@ type Context struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) SetRequestId(requestId string) {
|
func (c *Context) SetRequestId(requestId string) {
|
||||||
c.Set(FIELD_REQUEST_ID_KEY, requestId)
|
c.Set(requestIdFieldKey, requestId)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) GetRequestId() string {
|
func (c *Context) GetRequestId() string {
|
||||||
requestId, exists := c.Get(FIELD_REQUEST_ID_KEY)
|
requestId, exists := c.Get(requestIdFieldKey)
|
||||||
|
|
||||||
if !exists {
|
if !exists {
|
||||||
return ""
|
return ""
|
||||||
@@ -32,11 +32,11 @@ func (c *Context) GetRequestId() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) SetTokenClaims(claims *UserTokenClaims) {
|
func (c *Context) SetTokenClaims(claims *UserTokenClaims) {
|
||||||
c.Set(FIELD_TOKEN_CLAIMS_KEY, claims)
|
c.Set(tokenClaimsFieldKey, claims)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) GetTokenClaims() *UserTokenClaims {
|
func (c *Context) GetTokenClaims() *UserTokenClaims {
|
||||||
claims, exists := c.Get(FIELD_TOKEN_CLAIMS_KEY)
|
claims, exists := c.Get(tokenClaimsFieldKey)
|
||||||
|
|
||||||
if !exists {
|
if !exists {
|
||||||
return nil
|
return nil
|
||||||
@@ -62,11 +62,11 @@ func (c *Context) GetCurrentUid() int64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) SetResponseError(error *errs.Error) {
|
func (c *Context) SetResponseError(error *errs.Error) {
|
||||||
c.Set(FIELD_RESPONSE_ERROR, error)
|
c.Set(responseErrorFieldKey, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) GetResponseError() *errs.Error {
|
func (c *Context) GetResponseError() *errs.Error {
|
||||||
err, exists := c.Get(FIELD_RESPONSE_ERROR)
|
err, exists := c.Get(responseErrorFieldKey)
|
||||||
|
|
||||||
if !exists {
|
if !exists {
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ func initializeDatabase(dbConfig *settings.DatabaseConfig) (*Database, error) {
|
|||||||
var connStr string
|
var connStr string
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
if dbConfig.DatabaseType == settings.DBTYPE_SQLITE3 {
|
if dbConfig.DatabaseType == settings.Sqlite3DbType {
|
||||||
if _, err = os.Stat(dbConfig.DatabasePath); err != nil {
|
if _, err = os.Stat(dbConfig.DatabasePath); err != nil {
|
||||||
file, err := os.Create(dbConfig.DatabasePath)
|
file, err := os.Create(dbConfig.DatabasePath)
|
||||||
|
|
||||||
@@ -72,11 +72,11 @@ func initializeDatabase(dbConfig *settings.DatabaseConfig) (*Database, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if dbConfig.DatabaseType == settings.DBTYPE_MYSQL {
|
if dbConfig.DatabaseType == settings.MySqlDbType {
|
||||||
connStr, err = getMysqlConnectionString(dbConfig)
|
connStr, err = getMysqlConnectionString(dbConfig)
|
||||||
} else if dbConfig.DatabaseType == settings.DBTYPE_POSTGRES {
|
} else if dbConfig.DatabaseType == settings.PostgresDbType {
|
||||||
connStr, err = getPostgresConnectionString(dbConfig)
|
connStr, err = getPostgresConnectionString(dbConfig)
|
||||||
} else if dbConfig.DatabaseType == settings.DBTYPE_SQLITE3 {
|
} else if dbConfig.DatabaseType == settings.Sqlite3DbType {
|
||||||
connStr, err = getSqlite3ConnectionString(dbConfig)
|
connStr, err = getSqlite3ConnectionString(dbConfig)
|
||||||
} else {
|
} else {
|
||||||
return nil, errs.ErrDatabaseTypeInvalid
|
return nil, errs.ErrDatabaseTypeInvalid
|
||||||
|
|||||||
+13
-13
@@ -4,17 +4,17 @@ import "net/http"
|
|||||||
|
|
||||||
// Error codes related to accounts
|
// Error codes related to accounts
|
||||||
var (
|
var (
|
||||||
ErrAccountIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 0, http.StatusBadRequest, "account id is invalid")
|
ErrAccountIdInvalid = NewNormalError(NormalSubcategoryAccount, 0, http.StatusBadRequest, "account id is invalid")
|
||||||
ErrAccountNotFound = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 1, http.StatusBadRequest, "account not found")
|
ErrAccountNotFound = NewNormalError(NormalSubcategoryAccount, 1, http.StatusBadRequest, "account not found")
|
||||||
ErrAccountTypeInvalid = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 2, http.StatusBadRequest, "account type is invalid")
|
ErrAccountTypeInvalid = NewNormalError(NormalSubcategoryAccount, 2, http.StatusBadRequest, "account type is invalid")
|
||||||
ErrAccountHaveNoSubAccount = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 3, http.StatusBadRequest, "account must have at least one sub account")
|
ErrAccountHaveNoSubAccount = NewNormalError(NormalSubcategoryAccount, 3, http.StatusBadRequest, "account must have at least one sub account")
|
||||||
ErrAccountCannotHaveSubAccounts = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 4, http.StatusBadRequest, "account cannot have sub accounts")
|
ErrAccountCannotHaveSubAccounts = NewNormalError(NormalSubcategoryAccount, 4, http.StatusBadRequest, "account cannot have sub accounts")
|
||||||
ErrParentAccountCannotSetCurrency = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 5, http.StatusBadRequest, "parent account cannot set currency")
|
ErrParentAccountCannotSetCurrency = NewNormalError(NormalSubcategoryAccount, 5, http.StatusBadRequest, "parent account cannot set currency")
|
||||||
ErrParentAccountCannotSetBalance = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 6, http.StatusBadRequest, "parent account cannot set balance")
|
ErrParentAccountCannotSetBalance = NewNormalError(NormalSubcategoryAccount, 6, http.StatusBadRequest, "parent account cannot set balance")
|
||||||
ErrSubAccountCategoryNotEqualsToParent = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 7, http.StatusBadRequest, "sub account category not equals to parent")
|
ErrSubAccountCategoryNotEqualsToParent = NewNormalError(NormalSubcategoryAccount, 7, http.StatusBadRequest, "sub account category not equals to parent")
|
||||||
ErrSubAccountTypeInvalid = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 8, http.StatusBadRequest, "sub account type invalid")
|
ErrSubAccountTypeInvalid = NewNormalError(NormalSubcategoryAccount, 8, http.StatusBadRequest, "sub account type invalid")
|
||||||
ErrCannotAddOrDeleteSubAccountsWhenModify = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 9, http.StatusBadRequest, "cannot add or delete sub accounts when modify account")
|
ErrCannotAddOrDeleteSubAccountsWhenModify = NewNormalError(NormalSubcategoryAccount, 9, http.StatusBadRequest, "cannot add or delete sub accounts when modify account")
|
||||||
ErrSourceAccountNotFound = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 10, http.StatusBadRequest, "source account not found")
|
ErrSourceAccountNotFound = NewNormalError(NormalSubcategoryAccount, 10, http.StatusBadRequest, "source account not found")
|
||||||
ErrDestinationAccountNotFound = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 11, http.StatusBadRequest, "destination account not found")
|
ErrDestinationAccountNotFound = NewNormalError(NormalSubcategoryAccount, 11, http.StatusBadRequest, "destination account not found")
|
||||||
ErrAccountInUseCannotBeDeleted = NewNormalError(NORMAL_SUBCATEGORY_ACCOUNT, 12, http.StatusBadRequest, "account is in use and cannot be deleted")
|
ErrAccountInUseCannotBeDeleted = NewNormalError(NormalSubcategoryAccount, 12, http.StatusBadRequest, "account is in use and cannot be deleted")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import (
|
|||||||
|
|
||||||
// Error codes related to database
|
// Error codes related to database
|
||||||
var (
|
var (
|
||||||
ErrDatabaseTypeInvalid = NewSystemError(SYSTEM_SUBCATEGORY_DATABASE, 0, http.StatusInternalServerError, "database type is invalid")
|
ErrDatabaseTypeInvalid = NewSystemError(SystemSubcategoryDatabase, 0, http.StatusInternalServerError, "database type is invalid")
|
||||||
ErrDatabaseHostInvalid = NewSystemError(SYSTEM_SUBCATEGORY_DATABASE, 1, http.StatusInternalServerError, "database host is invalid")
|
ErrDatabaseHostInvalid = NewSystemError(SystemSubcategoryDatabase, 1, http.StatusInternalServerError, "database host is invalid")
|
||||||
ErrDatabaseIsNull = NewSystemError(SYSTEM_SUBCATEGORY_DATABASE, 2, http.StatusInternalServerError, "database cannot be null")
|
ErrDatabaseIsNull = NewSystemError(SystemSubcategoryDatabase, 2, http.StatusInternalServerError, "database cannot be null")
|
||||||
ErrDatabaseOperationFailed = NewSystemError(SYSTEM_SUBCATEGORY_DATABASE, 3, http.StatusInternalServerError, "database operation failed")
|
ErrDatabaseOperationFailed = NewSystemError(SystemSubcategoryDatabase, 3, http.StatusInternalServerError, "database operation failed")
|
||||||
)
|
)
|
||||||
|
|||||||
+11
-11
@@ -11,21 +11,21 @@ const (
|
|||||||
|
|
||||||
// Sub categories of system error
|
// Sub categories of system error
|
||||||
const (
|
const (
|
||||||
SYSTEM_SUBCATEGORY_DEFAULT = 0
|
SystemSubcategoryDefault = 0
|
||||||
SYSTEM_SUBCATEGORY_SETTING = 1
|
SystemSubcategorySetting = 1
|
||||||
SYSTEM_SUBCATEGORY_DATABASE = 2
|
SystemSubcategoryDatabase = 2
|
||||||
)
|
)
|
||||||
|
|
||||||
// Sub categories of normal error
|
// Sub categories of normal error
|
||||||
const (
|
const (
|
||||||
NORMAL_SUBCATEGORY_GLOBAL = 0
|
NormalSubcategoryGlobal = 0
|
||||||
NORMAL_SUBCATEGORY_USER = 1
|
NormalSubcategoryUser = 1
|
||||||
NORMAL_SUBCATEGORY_TOKEN = 2
|
NormalSubcategoryToken = 2
|
||||||
NORMAL_SUBCATEGORY_TWOFACTOR = 3
|
NormalSubcategoryTwofactor = 3
|
||||||
NORMAL_SUBCATEGORY_ACCOUNT = 4
|
NormalSubcategoryAccount = 4
|
||||||
NORMAL_SUBCATEGORY_TRANSACTION = 5
|
NormalSubcategoryTransaction = 5
|
||||||
NORMAL_SUBCATEGORY_CATEGORY = 6
|
NormalSubcategoryCategory = 6
|
||||||
NORMAL_SUBCATEGORY_TAG = 7
|
NormalSubcategoryTag = 7
|
||||||
)
|
)
|
||||||
|
|
||||||
// Error represents the specific error returned to user
|
// Error represents the specific error returned to user
|
||||||
|
|||||||
+8
-8
@@ -7,14 +7,14 @@ import (
|
|||||||
|
|
||||||
// General error codes
|
// General error codes
|
||||||
var (
|
var (
|
||||||
ErrIncompleteOrIncorrectSubmission = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 0, http.StatusBadRequest, "incomplete or incorrect submission")
|
ErrIncompleteOrIncorrectSubmission = NewNormalError(NormalSubcategoryGlobal, 0, http.StatusBadRequest, "incomplete or incorrect submission")
|
||||||
ErrOperationFailed = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 1, http.StatusInternalServerError, "operation failed")
|
ErrOperationFailed = NewNormalError(NormalSubcategoryGlobal, 1, http.StatusInternalServerError, "operation failed")
|
||||||
ErrRequestIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 2, http.StatusInternalServerError, "request id is invalid")
|
ErrRequestIdInvalid = NewNormalError(NormalSubcategoryGlobal, 2, http.StatusInternalServerError, "request id is invalid")
|
||||||
ErrCiphertextInvalid = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 3, http.StatusInternalServerError, "ciphertext is invalid")
|
ErrCiphertextInvalid = NewNormalError(NormalSubcategoryGlobal, 3, http.StatusInternalServerError, "ciphertext is invalid")
|
||||||
ErrNothingWillBeUpdated = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 4, http.StatusBadRequest, "nothing will be updated")
|
ErrNothingWillBeUpdated = NewNormalError(NormalSubcategoryGlobal, 4, http.StatusBadRequest, "nothing will be updated")
|
||||||
ErrFailedToRequestRemoteApi = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 5, http.StatusBadRequest, "failed to request third party api")
|
ErrFailedToRequestRemoteApi = NewNormalError(NormalSubcategoryGlobal, 5, http.StatusBadRequest, "failed to request third party api")
|
||||||
ErrPageIndexInvalid = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 6, http.StatusBadRequest, "page index is invalid")
|
ErrPageIndexInvalid = NewNormalError(NormalSubcategoryGlobal, 6, http.StatusBadRequest, "page index is invalid")
|
||||||
ErrPageCountInvalid = NewNormalError(NORMAL_SUBCATEGORY_GLOBAL, 7, http.StatusBadRequest, "page count is invalid")
|
ErrPageCountInvalid = NewNormalError(NormalSubcategoryGlobal, 7, http.StatusBadRequest, "page count is invalid")
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetParameterInvalidMessage returns specific error message for invalid parameter error
|
// GetParameterInvalidMessage returns specific error message for invalid parameter error
|
||||||
|
|||||||
+4
-4
@@ -4,8 +4,8 @@ import "net/http"
|
|||||||
|
|
||||||
// Error codes related to settings
|
// Error codes related to settings
|
||||||
var (
|
var (
|
||||||
ErrInvalidProtocol = NewSystemError(SYSTEM_SUBCATEGORY_SETTING, 0, http.StatusInternalServerError, "invalid server protocol")
|
ErrInvalidProtocol = NewSystemError(SystemSubcategorySetting, 0, http.StatusInternalServerError, "invalid server protocol")
|
||||||
ErrInvalidLogMode = NewSystemError(SYSTEM_SUBCATEGORY_SETTING, 1, http.StatusInternalServerError, "invalid log mode")
|
ErrInvalidLogMode = NewSystemError(SystemSubcategorySetting, 1, http.StatusInternalServerError, "invalid log mode")
|
||||||
ErrGettingLocalAddress = NewSystemError(SYSTEM_SUBCATEGORY_SETTING, 2, http.StatusInternalServerError, "failed to get local address")
|
ErrGettingLocalAddress = NewSystemError(SystemSubcategorySetting, 2, http.StatusInternalServerError, "failed to get local address")
|
||||||
ErrInvalidUuidMode = NewSystemError(SYSTEM_SUBCATEGORY_SETTING, 3, http.StatusInternalServerError, "invalid uuid mode")
|
ErrInvalidUuidMode = NewSystemError(SystemSubcategorySetting, 3, http.StatusInternalServerError, "invalid uuid mode")
|
||||||
)
|
)
|
||||||
|
|||||||
+4
-4
@@ -4,8 +4,8 @@ import "net/http"
|
|||||||
|
|
||||||
// Error codes related to transaction categories
|
// Error codes related to transaction categories
|
||||||
var (
|
var (
|
||||||
ErrSystemError = NewSystemError(SYSTEM_SUBCATEGORY_DEFAULT, 0, http.StatusInternalServerError, "system error")
|
ErrSystemError = NewSystemError(SystemSubcategoryDefault, 0, http.StatusInternalServerError, "system error")
|
||||||
ErrApiNotFound = NewSystemError(SYSTEM_SUBCATEGORY_DEFAULT, 1, http.StatusNotFound, "api not found")
|
ErrApiNotFound = NewSystemError(SystemSubcategoryDefault, 1, http.StatusNotFound, "api not found")
|
||||||
ErrMethodNotAllowed = NewSystemError(SYSTEM_SUBCATEGORY_DEFAULT, 2, http.StatusMethodNotAllowed, "method not allowed")
|
ErrMethodNotAllowed = NewSystemError(SystemSubcategoryDefault, 2, http.StatusMethodNotAllowed, "method not allowed")
|
||||||
ErrNotImplemented = NewSystemError(SYSTEM_SUBCATEGORY_DEFAULT, 3, http.StatusNotImplemented, "not implemented")
|
ErrNotImplemented = NewSystemError(SystemSubcategoryDefault, 3, http.StatusNotImplemented, "not implemented")
|
||||||
)
|
)
|
||||||
|
|||||||
+12
-12
@@ -6,16 +6,16 @@ import (
|
|||||||
|
|
||||||
// Error codes related to tokens
|
// Error codes related to tokens
|
||||||
var (
|
var (
|
||||||
ErrTokenGenerating = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 0, http.StatusInternalServerError, "failed to generate token")
|
ErrTokenGenerating = NewNormalError(NormalSubcategoryToken, 0, http.StatusInternalServerError, "failed to generate token")
|
||||||
ErrUnauthorizedAccess = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 1, http.StatusUnauthorized, "unauthorized access")
|
ErrUnauthorizedAccess = NewNormalError(NormalSubcategoryToken, 1, http.StatusUnauthorized, "unauthorized access")
|
||||||
ErrCurrentInvalidToken = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 2, http.StatusUnauthorized, "current token is invalid")
|
ErrCurrentInvalidToken = NewNormalError(NormalSubcategoryToken, 2, http.StatusUnauthorized, "current token is invalid")
|
||||||
ErrCurrentTokenExpired = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 3, http.StatusUnauthorized, "current token is expired")
|
ErrCurrentTokenExpired = NewNormalError(NormalSubcategoryToken, 3, http.StatusUnauthorized, "current token is expired")
|
||||||
ErrCurrentInvalidTokenType = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 4, http.StatusUnauthorized, "current token type is invalid")
|
ErrCurrentInvalidTokenType = NewNormalError(NormalSubcategoryToken, 4, http.StatusUnauthorized, "current token type is invalid")
|
||||||
ErrCurrentTokenRequire2FA = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 5, http.StatusUnauthorized, "current token requires two factor authorization")
|
ErrCurrentTokenRequire2FA = NewNormalError(NormalSubcategoryToken, 5, http.StatusUnauthorized, "current token requires two factor authorization")
|
||||||
ErrCurrentTokenNotRequire2FA = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 6, http.StatusUnauthorized, "current token does not require two factor authorization")
|
ErrCurrentTokenNotRequire2FA = NewNormalError(NormalSubcategoryToken, 6, http.StatusUnauthorized, "current token does not require two factor authorization")
|
||||||
ErrInvalidToken = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 7, http.StatusBadRequest, "token is invalid")
|
ErrInvalidToken = NewNormalError(NormalSubcategoryToken, 7, http.StatusBadRequest, "token is invalid")
|
||||||
ErrInvalidTokenId = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 8, http.StatusBadRequest, "token id is invalid")
|
ErrInvalidTokenId = NewNormalError(NormalSubcategoryToken, 8, http.StatusBadRequest, "token id is invalid")
|
||||||
ErrInvalidUserTokenId = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 9, http.StatusBadRequest, "user token id is invalid")
|
ErrInvalidUserTokenId = NewNormalError(NormalSubcategoryToken, 9, http.StatusBadRequest, "user token id is invalid")
|
||||||
ErrTokenRecordNotFound = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 10, http.StatusBadRequest, "token is not found")
|
ErrTokenRecordNotFound = NewNormalError(NormalSubcategoryToken, 10, http.StatusBadRequest, "token is not found")
|
||||||
ErrTokenExpired = NewNormalError(NORMAL_SUBCATEGORY_TOKEN, 11, http.StatusBadRequest, "token is expired")
|
ErrTokenExpired = NewNormalError(NormalSubcategoryToken, 11, http.StatusBadRequest, "token is expired")
|
||||||
)
|
)
|
||||||
|
|||||||
+13
-13
@@ -4,17 +4,17 @@ import "net/http"
|
|||||||
|
|
||||||
// Error codes related to transaction
|
// Error codes related to transaction
|
||||||
var (
|
var (
|
||||||
ErrTransactionIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 0, http.StatusBadRequest, "transaction id is invalid")
|
ErrTransactionIdInvalid = NewNormalError(NormalSubcategoryTransaction, 0, http.StatusBadRequest, "transaction id is invalid")
|
||||||
ErrTransactionNotFound = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 1, http.StatusBadRequest, "transaction not found")
|
ErrTransactionNotFound = NewNormalError(NormalSubcategoryTransaction, 1, http.StatusBadRequest, "transaction not found")
|
||||||
ErrTransactionTypeInvalid = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 2, http.StatusBadRequest, "transaction type is invalid")
|
ErrTransactionTypeInvalid = NewNormalError(NormalSubcategoryTransaction, 2, http.StatusBadRequest, "transaction type is invalid")
|
||||||
ErrTransactionSourceAndDestinationIdNotEqual = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 3, http.StatusBadRequest, "transaction source and destination account id not equal")
|
ErrTransactionSourceAndDestinationIdNotEqual = NewNormalError(NormalSubcategoryTransaction, 3, http.StatusBadRequest, "transaction source and destination account id not equal")
|
||||||
ErrTransactionSourceAndDestinationIdCannotBeEqual = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 4, http.StatusBadRequest, "transaction source and destination account id cannot be equal")
|
ErrTransactionSourceAndDestinationIdCannotBeEqual = NewNormalError(NormalSubcategoryTransaction, 4, http.StatusBadRequest, "transaction source and destination account id cannot be equal")
|
||||||
ErrTransactionSourceAndDestinationAmountNotEqual = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 5, http.StatusBadRequest, "transaction source and destination amount not equal")
|
ErrTransactionSourceAndDestinationAmountNotEqual = NewNormalError(NormalSubcategoryTransaction, 5, http.StatusBadRequest, "transaction source and destination amount not equal")
|
||||||
ErrTooMuchTransactionInOneSecond = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 6, http.StatusBadRequest, "too much transaction in one second")
|
ErrTooMuchTransactionInOneSecond = NewNormalError(NormalSubcategoryTransaction, 6, http.StatusBadRequest, "too much transaction in one second")
|
||||||
ErrBalanceModificationTransactionCannotSetCategory = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 7, http.StatusBadRequest, "balance modification transaction cannot set category")
|
ErrBalanceModificationTransactionCannotSetCategory = NewNormalError(NormalSubcategoryTransaction, 7, http.StatusBadRequest, "balance modification transaction cannot set category")
|
||||||
ErrBalanceModificationTransactionCannotChangeAccountId = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 8, http.StatusBadRequest, "balance modification transaction cannot change account id")
|
ErrBalanceModificationTransactionCannotChangeAccountId = NewNormalError(NormalSubcategoryTransaction, 8, http.StatusBadRequest, "balance modification transaction cannot change account id")
|
||||||
ErrBalanceModificationTransactionCannotAddWhenNotEmpty = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 9, http.StatusBadRequest, "balance modification transaction cannot add when other transaction exists")
|
ErrBalanceModificationTransactionCannotAddWhenNotEmpty = NewNormalError(NormalSubcategoryTransaction, 9, http.StatusBadRequest, "balance modification transaction cannot add when other transaction exists")
|
||||||
ErrCannotAddTransactionToHiddenAccount = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 10, http.StatusBadRequest, "cannot add transaction to hidden account")
|
ErrCannotAddTransactionToHiddenAccount = NewNormalError(NormalSubcategoryTransaction, 10, http.StatusBadRequest, "cannot add transaction to hidden account")
|
||||||
ErrCannotModifyTransactionInHiddenAccount = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 11, http.StatusBadRequest, "cannot modify transaction of hidden account")
|
ErrCannotModifyTransactionInHiddenAccount = NewNormalError(NormalSubcategoryTransaction, 11, http.StatusBadRequest, "cannot modify transaction of hidden account")
|
||||||
ErrCannotDeleteTransactionInHiddenAccount = NewNormalError(NORMAL_SUBCATEGORY_TRANSACTION, 12, http.StatusBadRequest, "cannot delete transaction in hidden account")
|
ErrCannotDeleteTransactionInHiddenAccount = NewNormalError(NormalSubcategoryTransaction, 12, http.StatusBadRequest, "cannot delete transaction in hidden account")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ import "net/http"
|
|||||||
|
|
||||||
// Error codes related to transaction categories
|
// Error codes related to transaction categories
|
||||||
var (
|
var (
|
||||||
ErrTransactionCategoryIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 0, http.StatusBadRequest, "transaction category id is invalid")
|
ErrTransactionCategoryIdInvalid = NewNormalError(NormalSubcategoryCategory, 0, http.StatusBadRequest, "transaction category id is invalid")
|
||||||
ErrTransactionCategoryNotFound = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 1, http.StatusBadRequest, "transaction category not found")
|
ErrTransactionCategoryNotFound = NewNormalError(NormalSubcategoryCategory, 1, http.StatusBadRequest, "transaction category not found")
|
||||||
ErrTransactionCategoryTypeInvalid = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 2, http.StatusBadRequest, "transaction category type is invalid")
|
ErrTransactionCategoryTypeInvalid = NewNormalError(NormalSubcategoryCategory, 2, http.StatusBadRequest, "transaction category type is invalid")
|
||||||
ErrParentTransactionCategoryNotFound = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 3, http.StatusBadRequest, "parent transaction category not found")
|
ErrParentTransactionCategoryNotFound = NewNormalError(NormalSubcategoryCategory, 3, http.StatusBadRequest, "parent transaction category not found")
|
||||||
ErrCannotAddToSecondaryTransactionCategory = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 4, http.StatusBadRequest, "cannot add to secondary transaction category")
|
ErrCannotAddToSecondaryTransactionCategory = NewNormalError(NormalSubcategoryCategory, 4, http.StatusBadRequest, "cannot add to secondary transaction category")
|
||||||
ErrCannotUsePrimaryCategoryForTransaction = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 5, http.StatusBadRequest, "cannot use primary category for transaction category")
|
ErrCannotUsePrimaryCategoryForTransaction = NewNormalError(NormalSubcategoryCategory, 5, http.StatusBadRequest, "cannot use primary category for transaction category")
|
||||||
ErrTransactionCategoryInUseCannotBeDeleted = NewNormalError(NORMAL_SUBCATEGORY_CATEGORY, 6, http.StatusBadRequest, "transaction category is in use and cannot be deleted")
|
ErrTransactionCategoryInUseCannotBeDeleted = NewNormalError(NormalSubcategoryCategory, 6, http.StatusBadRequest, "transaction category is in use and cannot be deleted")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import "net/http"
|
|||||||
|
|
||||||
// Error codes related to transaction tags
|
// Error codes related to transaction tags
|
||||||
var (
|
var (
|
||||||
ErrTransactionTagIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_TAG, 0, http.StatusBadRequest, "transaction tag id is invalid")
|
ErrTransactionTagIdInvalid = NewNormalError(NormalSubcategoryTag, 0, http.StatusBadRequest, "transaction tag id is invalid")
|
||||||
ErrTransactionTagNotFound = NewNormalError(NORMAL_SUBCATEGORY_TAG, 1, http.StatusBadRequest, "transaction tag not found")
|
ErrTransactionTagNotFound = NewNormalError(NormalSubcategoryTag, 1, http.StatusBadRequest, "transaction tag not found")
|
||||||
ErrTransactionTagNameIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_TAG, 2, http.StatusBadRequest, "transaction tag name is empty")
|
ErrTransactionTagNameIsEmpty = NewNormalError(NormalSubcategoryTag, 2, http.StatusBadRequest, "transaction tag name is empty")
|
||||||
ErrTransactionTagNameAlreadyExists = NewNormalError(NORMAL_SUBCATEGORY_TAG, 3, http.StatusBadRequest, "transaction tag name already exists")
|
ErrTransactionTagNameAlreadyExists = NewNormalError(NormalSubcategoryTag, 3, http.StatusBadRequest, "transaction tag name already exists")
|
||||||
ErrTransactionTagInUseCannotBeDeleted = NewNormalError(NORMAL_SUBCATEGORY_TAG, 4, http.StatusBadRequest, "transaction tag is in use and cannot be deleted")
|
ErrTransactionTagInUseCannotBeDeleted = NewNormalError(NormalSubcategoryTag, 4, http.StatusBadRequest, "transaction tag is in use and cannot be deleted")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import "net/http"
|
|||||||
|
|
||||||
// Error codes related to two factor authorization
|
// Error codes related to two factor authorization
|
||||||
var (
|
var (
|
||||||
ErrPasscodeInvalid = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 0, http.StatusUnauthorized, "passcode is invalid")
|
ErrPasscodeInvalid = NewNormalError(NormalSubcategoryTwofactor, 0, http.StatusUnauthorized, "passcode is invalid")
|
||||||
ErrTwoFactorRecoveryCodeInvalid = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 1, http.StatusUnauthorized, "two factor backup code is invalid")
|
ErrTwoFactorRecoveryCodeInvalid = NewNormalError(NormalSubcategoryTwofactor, 1, http.StatusUnauthorized, "two factor backup code is invalid")
|
||||||
ErrTwoFactorRecoveryCodeNotExist = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 2, http.StatusUnauthorized, "two factor backup code does not exist")
|
ErrTwoFactorRecoveryCodeNotExist = NewNormalError(NormalSubcategoryTwofactor, 2, http.StatusUnauthorized, "two factor backup code does not exist")
|
||||||
ErrTwoFactorIsNotEnabled = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 3, http.StatusBadRequest, "two factor is not enabled")
|
ErrTwoFactorIsNotEnabled = NewNormalError(NormalSubcategoryTwofactor, 3, http.StatusBadRequest, "two factor is not enabled")
|
||||||
ErrTwoFactorAlreadyEnabled = NewNormalError(NORMAL_SUBCATEGORY_TWOFACTOR, 4, http.StatusBadRequest, "two factor has already been enabled")
|
ErrTwoFactorAlreadyEnabled = NewNormalError(NormalSubcategoryTwofactor, 4, http.StatusBadRequest, "two factor has already been enabled")
|
||||||
)
|
)
|
||||||
|
|||||||
+11
-11
@@ -6,15 +6,15 @@ import (
|
|||||||
|
|
||||||
// Error codes related to users
|
// Error codes related to users
|
||||||
var (
|
var (
|
||||||
ErrLoginNameInvalid = NewNormalError(NORMAL_SUBCATEGORY_USER, 0, http.StatusUnauthorized, "login name is invalid")
|
ErrLoginNameInvalid = NewNormalError(NormalSubcategoryUser, 0, http.StatusUnauthorized, "login name is invalid")
|
||||||
ErrLoginNameOrPasswordInvalid = NewNormalError(NORMAL_SUBCATEGORY_USER, 1, http.StatusUnauthorized, "login name or password is invalid")
|
ErrLoginNameOrPasswordInvalid = NewNormalError(NormalSubcategoryUser, 1, http.StatusUnauthorized, "login name or password is invalid")
|
||||||
ErrLoginNameOrPasswordWrong = NewNormalError(NORMAL_SUBCATEGORY_USER, 2, http.StatusUnauthorized, "login name or password is wrong")
|
ErrLoginNameOrPasswordWrong = NewNormalError(NormalSubcategoryUser, 2, http.StatusUnauthorized, "login name or password is wrong")
|
||||||
ErrUserIdInvalid = NewNormalError(NORMAL_SUBCATEGORY_USER, 3, http.StatusBadRequest, "user id is invalid")
|
ErrUserIdInvalid = NewNormalError(NormalSubcategoryUser, 3, http.StatusBadRequest, "user id is invalid")
|
||||||
ErrUsernameIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_USER, 4, http.StatusBadRequest, "username is empty")
|
ErrUsernameIsEmpty = NewNormalError(NormalSubcategoryUser, 4, http.StatusBadRequest, "username is empty")
|
||||||
ErrEmailIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_USER, 5, http.StatusBadRequest, "email is empty")
|
ErrEmailIsEmpty = NewNormalError(NormalSubcategoryUser, 5, http.StatusBadRequest, "email is empty")
|
||||||
ErrPasswordIsEmpty = NewNormalError(NORMAL_SUBCATEGORY_USER, 6, http.StatusBadRequest, "password is empty")
|
ErrPasswordIsEmpty = NewNormalError(NormalSubcategoryUser, 6, http.StatusBadRequest, "password is empty")
|
||||||
ErrUserNotFound = NewNormalError(NORMAL_SUBCATEGORY_USER, 7, http.StatusBadRequest, "user not found")
|
ErrUserNotFound = NewNormalError(NormalSubcategoryUser, 7, http.StatusBadRequest, "user not found")
|
||||||
ErrUserPasswordWrong = NewNormalError(NORMAL_SUBCATEGORY_USER, 8, http.StatusBadRequest, "password is wrong")
|
ErrUserPasswordWrong = NewNormalError(NormalSubcategoryUser, 8, http.StatusBadRequest, "password is wrong")
|
||||||
ErrUsernameAlreadyExists = NewNormalError(NORMAL_SUBCATEGORY_USER, 9, http.StatusBadRequest, "username already exists")
|
ErrUsernameAlreadyExists = NewNormalError(NormalSubcategoryUser, 9, http.StatusBadRequest, "username already exists")
|
||||||
ErrUserEmailAlreadyExists = NewNormalError(NORMAL_SUBCATEGORY_USER, 10, http.StatusBadRequest, "email already exists")
|
ErrUserEmailAlreadyExists = NewNormalError(NormalSubcategoryUser, 10, http.StatusBadRequest, "email already exists")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -41,13 +41,13 @@ func (f *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
|
|||||||
|
|
||||||
b.WriteString(entry.Message)
|
b.WriteString(entry.Message)
|
||||||
|
|
||||||
if requestId, exists := entry.Data[LOG_FIELD_REQUEST_ID]; exists {
|
if requestId, exists := entry.Data[logFieldRequestId]; exists {
|
||||||
b.WriteString(fmt.Sprintf(", r=%s", requestId))
|
b.WriteString(fmt.Sprintf(", r=%s", requestId))
|
||||||
}
|
}
|
||||||
|
|
||||||
b.WriteString("\n")
|
b.WriteString("\n")
|
||||||
|
|
||||||
if extra, exists := entry.Data[LOG_FIELD_EXTRA]; exists {
|
if extra, exists := entry.Data[logFieldExtra]; exists {
|
||||||
b.WriteString(extra.(string))
|
b.WriteString(extra.(string))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+8
-8
@@ -12,8 +12,8 @@ import (
|
|||||||
"github.com/mayswind/lab/pkg/settings"
|
"github.com/mayswind/lab/pkg/settings"
|
||||||
)
|
)
|
||||||
|
|
||||||
const LOG_FIELD_REQUEST_ID = "REQUEST_ID"
|
const logFieldRequestId = "REQUEST_ID"
|
||||||
const LOG_FIELD_EXTRA = "EXTRA"
|
const logFieldExtra = "EXTRA"
|
||||||
|
|
||||||
var bootLogger = logrus.New()
|
var bootLogger = logrus.New()
|
||||||
var defaultLogger = logrus.New()
|
var defaultLogger = logrus.New()
|
||||||
@@ -97,7 +97,7 @@ func Debugf(format string, args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func DebugfWithRequestId(c *core.Context, format string, args ...interface{}) {
|
func DebugfWithRequestId(c *core.Context, format string, args ...interface{}) {
|
||||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Debugf(getFinalLog(format, args...))
|
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Debugf(getFinalLog(format, args...))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Infof(format string, args ...interface{}) {
|
func Infof(format string, args ...interface{}) {
|
||||||
@@ -105,7 +105,7 @@ func Infof(format string, args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func InfofWithRequestId(c *core.Context, format string, args ...interface{}) {
|
func InfofWithRequestId(c *core.Context, format string, args ...interface{}) {
|
||||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Infof(getFinalLog(format, args...))
|
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Infof(getFinalLog(format, args...))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Warnf(format string, args ...interface{}) {
|
func Warnf(format string, args ...interface{}) {
|
||||||
@@ -113,7 +113,7 @@ func Warnf(format string, args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func WarnfWithRequestId(c *core.Context, format string, args ...interface{}) {
|
func WarnfWithRequestId(c *core.Context, format string, args ...interface{}) {
|
||||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Warnf(getFinalLog(format, args...))
|
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Warnf(getFinalLog(format, args...))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Errorf(format string, args ...interface{}) {
|
func Errorf(format string, args ...interface{}) {
|
||||||
@@ -121,11 +121,11 @@ func Errorf(format string, args ...interface{}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ErrorfWithRequestId(c *core.Context, format string, args ...interface{}) {
|
func ErrorfWithRequestId(c *core.Context, format string, args ...interface{}) {
|
||||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Errorf(getFinalLog(format, args...))
|
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).Errorf(getFinalLog(format, args...))
|
||||||
}
|
}
|
||||||
|
|
||||||
func ErrorfWithRequestIdAndExtra(c *core.Context, extraString string, format string, args ...interface{}) {
|
func ErrorfWithRequestIdAndExtra(c *core.Context, extraString string, format string, args ...interface{}) {
|
||||||
defaultLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).WithField(LOG_FIELD_EXTRA, extraString).Errorf(getFinalLog(format, args...))
|
defaultLogger.WithField(logFieldRequestId, c.GetRequestId()).WithField(logFieldExtra, extraString).Errorf(getFinalLog(format, args...))
|
||||||
}
|
}
|
||||||
|
|
||||||
func BootInfof(format string, args ...interface{}) {
|
func BootInfof(format string, args ...interface{}) {
|
||||||
@@ -148,7 +148,7 @@ func BootErrorf(format string, args ...interface{}) {
|
|||||||
|
|
||||||
func Requestf(c *core.Context, format string, args ...interface{}) {
|
func Requestf(c *core.Context, format string, args ...interface{}) {
|
||||||
if requestLogger != nil {
|
if requestLogger != nil {
|
||||||
requestLogger.WithField(LOG_FIELD_REQUEST_ID, c.GetRequestId()).Infof(getFinalLog(format, args...))
|
requestLogger.WithField(logFieldRequestId, c.GetRequestId()).Infof(getFinalLog(format, args...))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
"github.com/mayswind/lab/pkg/settings"
|
"github.com/mayswind/lab/pkg/settings"
|
||||||
)
|
)
|
||||||
|
|
||||||
const REQUEST_ID_HEADER = "X-Request-ID"
|
const requestIdHeader = "X-Request-ID"
|
||||||
|
|
||||||
func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
|
func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
|
||||||
return func(c *core.Context) {
|
return func(c *core.Context) {
|
||||||
@@ -19,7 +19,7 @@ func RequestId(config *settings.Config) core.MiddlewareHandlerFunc {
|
|||||||
c.SetRequestId(requestId)
|
c.SetRequestId(requestId)
|
||||||
|
|
||||||
if config.EnableRequestIdHeader {
|
if config.EnableRequestIdHeader {
|
||||||
c.Header(REQUEST_ID_HEADER, requestId)
|
c.Header(requestIdHeader, requestId)
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Next()
|
c.Next()
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"github.com/mayswind/lab/pkg/settings"
|
"github.com/mayswind/lab/pkg/settings"
|
||||||
)
|
)
|
||||||
|
|
||||||
const SETTINGS_COOKIE_NAME = "ACP_SETTINGS"
|
const settingsCookieName = "ACP_SETTINGS"
|
||||||
|
|
||||||
func ServerSettingsCookie(config *settings.Config) core.MiddlewareHandlerFunc {
|
func ServerSettingsCookie(config *settings.Config) core.MiddlewareHandlerFunc {
|
||||||
return func(c *core.Context) {
|
return func(c *core.Context) {
|
||||||
@@ -17,7 +17,7 @@ func ServerSettingsCookie(config *settings.Config) core.MiddlewareHandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bundledSettings := strings.Join(settingsArr, "_")
|
bundledSettings := strings.Join(settingsArr, "_")
|
||||||
c.SetCookie(SETTINGS_COOKIE_NAME, bundledSettings, config.TokenExpiredTime, "", "", false, false)
|
c.SetCookie(settingsCookieName, bundledSettings, config.TokenExpiredTime, "", "", false, false)
|
||||||
|
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package models
|
package models
|
||||||
|
|
||||||
// Level-One Account
|
// LevelOneAccountParentId represents the parent id of level-one account
|
||||||
const ACCOUNT_PARENT_ID_LEVEL_ONE = 0
|
const LevelOneAccountParentId = 0
|
||||||
|
|
||||||
// AccountCategory represents account category
|
// AccountCategory represents account category
|
||||||
type AccountCategory byte
|
type AccountCategory byte
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ package models
|
|||||||
|
|
||||||
import "github.com/mayswind/lab/pkg/core"
|
import "github.com/mayswind/lab/pkg/core"
|
||||||
|
|
||||||
// The maximum size of user agent stored in database
|
// TokenMaxUserAgentLength represents the maximum size of user agent stored in database
|
||||||
const TOKEN_USER_AGENT_MAX_LENGTH = 255
|
const TokenMaxUserAgentLength = 255
|
||||||
|
|
||||||
// TokenRecord represents token data stored in database
|
// TokenRecord represents token data stored in database
|
||||||
type TokenRecord struct {
|
type TokenRecord struct {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package models
|
package models
|
||||||
|
|
||||||
// Level-One Transaction Category
|
// LevelOneTransactionParentId represents the parent id of level-one transaction category
|
||||||
const TRANSACTION_PARENT_ID_LEVEL_ONE = 0
|
const LevelOneTransactionParentId = 0
|
||||||
|
|
||||||
// TransactionCategoryType represents transaction category type
|
// TransactionCategoryType represents transaction category type
|
||||||
type TransactionCategoryType byte
|
type TransactionCategoryType byte
|
||||||
|
|||||||
@@ -19,15 +19,15 @@ import (
|
|||||||
|
|
||||||
// Length and mask of all information in request id
|
// Length and mask of all information in request id
|
||||||
const (
|
const (
|
||||||
REQUEST_ID_LENGTH = 36
|
requestIdLength = 36
|
||||||
SECONDS_TODAY_BITS = 17
|
secondsTodayBits = 17
|
||||||
SECONDS_TODAY_BITS_MASK = (1 << SECONDS_TODAY_BITS) - 1
|
secondsTodayBitsMask = (1 << secondsTodayBits) - 1
|
||||||
RANDOM_NUMBER_BITS = 15
|
randomNumberBits = 15
|
||||||
RANDOM_NUMBER_BITS_MASK = (1 << RANDOM_NUMBER_BITS) - 1
|
randomNumberBitsMask = (1 << randomNumberBits) - 1
|
||||||
REQ_SEQ_NUMBER_BITS = 31
|
reqSeqNumberBits = 31
|
||||||
REQ_SEQ_NUMBER_BITS_MASK = (1 << REQ_SEQ_NUMBER_BITS) - 1
|
reqSeqNumberBitsMask = (1 << reqSeqNumberBits) - 1
|
||||||
CLIENT_IPV6_BIT = 1
|
clientIpv6Bit = 1
|
||||||
CLIENT_IPV6_BIT_MASK = 1
|
clientIpv6BitMask = 1
|
||||||
)
|
)
|
||||||
|
|
||||||
// RequestIdInfo represents a struct which has all information in request id
|
// RequestIdInfo represents a struct which has all information in request id
|
||||||
@@ -102,7 +102,7 @@ func getInstanceUniqId(config *settings.Config) uint16 {
|
|||||||
|
|
||||||
// ParseRequestIdInfo returns a info struct which contains all information in request id
|
// ParseRequestIdInfo returns a info struct which contains all information in request id
|
||||||
func (r *DefaultRequestIdGenerator) ParseRequestIdInfo(requestId string) (*RequestIdInfo, error) {
|
func (r *DefaultRequestIdGenerator) ParseRequestIdInfo(requestId string) (*RequestIdInfo, error) {
|
||||||
if requestId == "" || len(requestId) != REQUEST_ID_LENGTH {
|
if requestId == "" || len(requestId) != requestIdLength {
|
||||||
return nil, errs.ErrRequestIdInvalid
|
return nil, errs.ErrRequestIdInvalid
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,17 +147,17 @@ func (r *DefaultRequestIdGenerator) getRequestId(serverUniqId uint16, instanceUn
|
|||||||
// 128bits = serverUniqId(16bits) + instanceUniqId(16bits) + secondsElapsedToday(17bits) + randomNumber(15bits) + sequentialNumber(31bits) + clientIpv6Flag(1bit) + clientIp(32bits)
|
// 128bits = serverUniqId(16bits) + instanceUniqId(16bits) + secondsElapsedToday(17bits) + randomNumber(15bits) + sequentialNumber(31bits) + clientIpv6Flag(1bit) + clientIp(32bits)
|
||||||
|
|
||||||
secondsElapsedToday := r.getSecondsElapsedToday()
|
secondsElapsedToday := r.getSecondsElapsedToday()
|
||||||
secondsLow17bits := uint32(secondsElapsedToday & SECONDS_TODAY_BITS_MASK)
|
secondsLow17bits := uint32(secondsElapsedToday & secondsTodayBitsMask)
|
||||||
|
|
||||||
randomNumber, _ := utils.GetRandomInteger(math.MaxInt16)
|
randomNumber, _ := utils.GetRandomInteger(math.MaxInt16)
|
||||||
randomNumberLow15bits := uint32(randomNumber & RANDOM_NUMBER_BITS_MASK)
|
randomNumberLow15bits := uint32(randomNumber & randomNumberBitsMask)
|
||||||
|
|
||||||
secondsAndRandomNumber := (secondsLow17bits << RANDOM_NUMBER_BITS) | randomNumberLow15bits
|
secondsAndRandomNumber := (secondsLow17bits << randomNumberBits) | randomNumberLow15bits
|
||||||
|
|
||||||
seqId := atomic.AddUint32(&r.requestSeqId, 1)
|
seqId := atomic.AddUint32(&r.requestSeqId, 1)
|
||||||
seqIdLow31bits := seqId & REQ_SEQ_NUMBER_BITS_MASK
|
seqIdLow31bits := seqId & reqSeqNumberBitsMask
|
||||||
|
|
||||||
seqIdAndClientIpv6Flag := (seqIdLow31bits << CLIENT_IPV6_BIT) | (clientIpv6Flag & CLIENT_IPV6_BIT_MASK)
|
seqIdAndClientIpv6Flag := (seqIdLow31bits << clientIpv6Bit) | (clientIpv6Flag & clientIpv6BitMask)
|
||||||
|
|
||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
_ = binary.Write(buf, binary.BigEndian, serverUniqId)
|
_ = binary.Write(buf, binary.BigEndian, serverUniqId)
|
||||||
@@ -208,11 +208,11 @@ func (r *DefaultRequestIdGenerator) parseRequestIdInfo(data []byte) *RequestIdIn
|
|||||||
_ = binary.Read(buf, binary.BigEndian, &seqIdAndClientIpv6Flag)
|
_ = binary.Read(buf, binary.BigEndian, &seqIdAndClientIpv6Flag)
|
||||||
_ = binary.Read(buf, binary.BigEndian, &clientIp)
|
_ = binary.Read(buf, binary.BigEndian, &clientIp)
|
||||||
|
|
||||||
secondsElapsedToday := (secondsAndRandomNumber >> RANDOM_NUMBER_BITS) & SECONDS_TODAY_BITS_MASK
|
secondsElapsedToday := (secondsAndRandomNumber >> randomNumberBits) & secondsTodayBitsMask
|
||||||
randomNumber := (secondsAndRandomNumber & RANDOM_NUMBER_BITS_MASK)
|
randomNumber := (secondsAndRandomNumber & randomNumberBitsMask)
|
||||||
|
|
||||||
seqId := (seqIdAndClientIpv6Flag >> CLIENT_IPV6_BIT) & REQ_SEQ_NUMBER_BITS_MASK
|
seqId := (seqIdAndClientIpv6Flag >> clientIpv6Bit) & reqSeqNumberBitsMask
|
||||||
isClientIpv6Flag := (seqIdAndClientIpv6Flag & CLIENT_IPV6_BIT_MASK)
|
isClientIpv6Flag := (seqIdAndClientIpv6Flag & clientIpv6BitMask)
|
||||||
isClientIpv6 := false
|
isClientIpv6 := false
|
||||||
|
|
||||||
if isClientIpv6Flag == 1 {
|
if isClientIpv6Flag == 1 {
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ func (s *AccountService) GetMaxDisplayOrder(uid int64, category models.AccountCa
|
|||||||
}
|
}
|
||||||
|
|
||||||
account := &models.Account{}
|
account := &models.Account{}
|
||||||
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_account_id", "display_order").Where("uid=? AND deleted=? AND parent_account_id=? AND category=?", uid, false, models.ACCOUNT_PARENT_ID_LEVEL_ONE, category).OrderBy("display_order desc").Limit(1).Get(account)
|
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_account_id", "display_order").Where("uid=? AND deleted=? AND parent_account_id=? AND category=?", uid, false, models.LevelOneAccountParentId, category).OrderBy("display_order desc").Limit(1).Get(account)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
|
|||||||
@@ -314,8 +314,8 @@ func (s *TokenService) getUserAgent(ctx *core.Context) string {
|
|||||||
userAgent = ctx.Request.UserAgent()
|
userAgent = ctx.Request.UserAgent()
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(userAgent) > models.TOKEN_USER_AGENT_MAX_LENGTH {
|
if len(userAgent) > models.TokenMaxUserAgentLength {
|
||||||
userAgent = utils.SubString(userAgent, 0, models.TOKEN_USER_AGENT_MAX_LENGTH)
|
userAgent = utils.SubString(userAgent, 0, models.TokenMaxUserAgentLength)
|
||||||
}
|
}
|
||||||
|
|
||||||
return userAgent
|
return userAgent
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ func (s *TransactionCategoryService) GetMaxDisplayOrder(uid int64, categoryType
|
|||||||
}
|
}
|
||||||
|
|
||||||
category := &models.TransactionCategory{}
|
category := &models.TransactionCategory{}
|
||||||
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_category_id", "display_order").Where("uid=? AND deleted=? AND type=? AND parent_category_id=?", uid, false, categoryType, models.TRANSACTION_PARENT_ID_LEVEL_ONE).OrderBy("display_order desc").Limit(1).Get(category)
|
has, err := s.UserDataDB(uid).Cols("uid", "deleted", "parent_category_id", "display_order").Where("uid=? AND deleted=? AND type=? AND parent_category_id=?", uid, false, categoryType, models.LevelOneTransactionParentId).OrderBy("display_order desc").Limit(1).Get(category)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
|
|||||||
@@ -16,10 +16,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
TWOFACTOR_PERIOD uint = 30 // seconds
|
twoFactorPeriod uint = 30 // seconds
|
||||||
TWOFACTOR_SECRET_SIZE uint = 20 // bytes
|
twoFactorSecretSize uint = 20 // bytes
|
||||||
TWOFACTOR_RECOVERY_CODE_COUNT int = 10
|
twoFactorRecoveryCodeCount int = 10
|
||||||
TWOFACTOR_RECOVERY_CODE_LENGTH int = 10 // bytes
|
twoFactorRecoveryCodeLength int = 10 // bytes
|
||||||
)
|
)
|
||||||
|
|
||||||
type TwoFactorAuthorizationService struct {
|
type TwoFactorAuthorizationService struct {
|
||||||
@@ -73,8 +73,8 @@ func (s *TwoFactorAuthorizationService) GenerateTwoFactorSecret(user *models.Use
|
|||||||
key, err := totp.Generate(totp.GenerateOpts{
|
key, err := totp.Generate(totp.GenerateOpts{
|
||||||
Issuer: s.CurrentConfig().AppName,
|
Issuer: s.CurrentConfig().AppName,
|
||||||
AccountName: user.Username,
|
AccountName: user.Username,
|
||||||
Period: TWOFACTOR_PERIOD,
|
Period: twoFactorPeriod,
|
||||||
SecretSize: TWOFACTOR_SECRET_SIZE,
|
SecretSize: twoFactorSecretSize,
|
||||||
})
|
})
|
||||||
|
|
||||||
return key, err
|
return key, err
|
||||||
@@ -147,10 +147,10 @@ func (s *TwoFactorAuthorizationService) GetAndUseUserTwoFactorRecoveryCode(uid i
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *TwoFactorAuthorizationService) GenerateTwoFactorRecoveryCodes() ([]string, error) {
|
func (s *TwoFactorAuthorizationService) GenerateTwoFactorRecoveryCodes() ([]string, error) {
|
||||||
recoveryCodes := make([]string, TWOFACTOR_RECOVERY_CODE_COUNT)
|
recoveryCodes := make([]string, twoFactorRecoveryCodeCount)
|
||||||
|
|
||||||
for i := 0; i < TWOFACTOR_RECOVERY_CODE_COUNT; i++ {
|
for i := 0; i < twoFactorRecoveryCodeCount; i++ {
|
||||||
recoveryCode, err := utils.GetRandomNumberOrLetter(TWOFACTOR_RECOVERY_CODE_LENGTH)
|
recoveryCode, err := utils.GetRandomNumberOrLetter(twoFactorRecoveryCodeLength)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
+47
-47
@@ -14,10 +14,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
LAB_WORK_DIR = "LAB_WORK_DIR"
|
labWorkDirEnvName = "LAB_WORK_DIR"
|
||||||
LAB_ENVIRONMENT_KEY_PREFIX = "LAB"
|
labEnvNamePrefix = "LAB"
|
||||||
DEFAULT_CONFIG_PATH = "/conf/lab.ini"
|
defaultConfigPath = "/conf/lab.ini"
|
||||||
DEFAULT_STATIC_ROOT_PATH = "public"
|
defaultStaticRootPath = "public"
|
||||||
)
|
)
|
||||||
|
|
||||||
type SystemMode string
|
type SystemMode string
|
||||||
@@ -45,34 +45,34 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
DBTYPE_MYSQL string = "mysql"
|
MySqlDbType string = "mysql"
|
||||||
DBTYPE_POSTGRES string = "postgres"
|
PostgresDbType string = "postgres"
|
||||||
DBTYPE_SQLITE3 string = "sqlite3"
|
Sqlite3DbType string = "sqlite3"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
UUID_GENERATOR_TYPE_INTERNAL string = "internal"
|
InternalUuidGeneratorType string = "internal"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
DEFAULT_APP_NAME string = "lab"
|
defaultAppName string = "lab"
|
||||||
|
|
||||||
DEFAULT_HTTP_ADDR string = "0.0.0.0"
|
defaultHttpAddr string = "0.0.0.0"
|
||||||
DEFAULT_HTTP_PORT int = 8080
|
defaultHttpPort int = 8080
|
||||||
DEFAULT_DOMAIN string = "localhost"
|
defaultDomain string = "localhost"
|
||||||
|
|
||||||
DEFAULT_DATABASE_HOST string = "127.0.0.1:3306"
|
defaultDatabaseHost string = "127.0.0.1:3306"
|
||||||
DEFAULT_DATABASE_NAME string = "lab"
|
defaultDatabaseName string = "lab"
|
||||||
DEFAULT_DATABASE_MAX_IDLE_CONN int = 2
|
defaultDatabaseMaxIdleConn int = 2
|
||||||
DEFAULT_DATABASE_MAX_OPEN_CONN int = 0
|
defaultDatabaseMaxOpenConn int = 0
|
||||||
DEFAULT_DATABASE_CONN_MAX_LIFETIME int = 14400
|
defaultDatabaseConnMaxLifetime int = 14400
|
||||||
|
|
||||||
DEFAULT_LOG_MODE string = "console"
|
defaultLogMode string = "console"
|
||||||
DEFAULT_LOG_LEVEL Level = LOGLEVEL_INFO
|
defaultLoglevel Level = LOGLEVEL_INFO
|
||||||
|
|
||||||
DEFAULT_SECRET_KEY string = "lab"
|
defaultSecretKey string = "lab"
|
||||||
DEFAULT_TOKEN_EXPIRED_TIME int = 604800 // 7 days
|
defaultTokenExpiredTime int = 604800 // 7 days
|
||||||
DEFAULT_TEMPORARY_TOKEN_EXPIRED_TIME int = 300 // 5 minutes
|
defaultTemporaryTokenExpiredTime int = 300 // 5 minutes
|
||||||
)
|
)
|
||||||
|
|
||||||
type DatabaseConfig struct {
|
type DatabaseConfig struct {
|
||||||
@@ -213,7 +213,7 @@ func GetDefaultConfigFilePath() (string, error) {
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
cfgFilePath := filepath.Join(workingPath, DEFAULT_CONFIG_PATH)
|
cfgFilePath := filepath.Join(workingPath, defaultConfigPath)
|
||||||
_, err = os.Stat(cfgFilePath)
|
_, err = os.Stat(cfgFilePath)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -224,7 +224,7 @@ func GetDefaultConfigFilePath() (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func loadGlobalConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
func loadGlobalConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||||
config.AppName = getConfigItemStringValue(configFile, sectionName, "app_name", DEFAULT_APP_NAME)
|
config.AppName = getConfigItemStringValue(configFile, sectionName, "app_name", defaultAppName)
|
||||||
config.Mode = MODE_PRODUCTION
|
config.Mode = MODE_PRODUCTION
|
||||||
|
|
||||||
if getConfigItemStringValue(configFile, sectionName, "mode") == "development" {
|
if getConfigItemStringValue(configFile, sectionName, "mode") == "development" {
|
||||||
@@ -238,13 +238,13 @@ func loadServerConfiguration(config *Config, configFile *ini.File, sectionName s
|
|||||||
if getConfigItemStringValue(configFile, sectionName, "protocol") == "http" {
|
if getConfigItemStringValue(configFile, sectionName, "protocol") == "http" {
|
||||||
config.Protocol = SCHEME_HTTP
|
config.Protocol = SCHEME_HTTP
|
||||||
|
|
||||||
config.HttpAddr = getConfigItemStringValue(configFile, sectionName, "http_addr", DEFAULT_HTTP_ADDR)
|
config.HttpAddr = getConfigItemStringValue(configFile, sectionName, "http_addr", defaultHttpAddr)
|
||||||
config.HttpPort = getConfigItemIntValue(configFile, sectionName, "http_port", DEFAULT_HTTP_PORT)
|
config.HttpPort = getConfigItemIntValue(configFile, sectionName, "http_port", defaultHttpPort)
|
||||||
} else if getConfigItemStringValue(configFile, sectionName, "protocol") == "https" {
|
} else if getConfigItemStringValue(configFile, sectionName, "protocol") == "https" {
|
||||||
config.Protocol = SCHEME_HTTPS
|
config.Protocol = SCHEME_HTTPS
|
||||||
|
|
||||||
config.HttpAddr = getConfigItemStringValue(configFile, sectionName, "http_addr", DEFAULT_HTTP_ADDR)
|
config.HttpAddr = getConfigItemStringValue(configFile, sectionName, "http_addr", defaultHttpAddr)
|
||||||
config.HttpPort = getConfigItemIntValue(configFile, sectionName, "http_port", DEFAULT_HTTP_PORT)
|
config.HttpPort = getConfigItemIntValue(configFile, sectionName, "http_port", defaultHttpPort)
|
||||||
|
|
||||||
config.CertFile = getConfigItemStringValue(configFile, sectionName, "cert_file")
|
config.CertFile = getConfigItemStringValue(configFile, sectionName, "cert_file")
|
||||||
config.CertKeyFile = getConfigItemStringValue(configFile, sectionName, "cert_key_file")
|
config.CertKeyFile = getConfigItemStringValue(configFile, sectionName, "cert_key_file")
|
||||||
@@ -256,14 +256,14 @@ func loadServerConfiguration(config *Config, configFile *ini.File, sectionName s
|
|||||||
return errs.ErrInvalidProtocol
|
return errs.ErrInvalidProtocol
|
||||||
}
|
}
|
||||||
|
|
||||||
config.Domain = getConfigItemStringValue(configFile, sectionName, "domain", DEFAULT_DOMAIN)
|
config.Domain = getConfigItemStringValue(configFile, sectionName, "domain", defaultDomain)
|
||||||
config.RootUrl = getConfigItemStringValue(configFile, sectionName, "root_url", fmt.Sprintf("%s://%s:%d/", string(config.Protocol), config.Domain, config.HttpPort))
|
config.RootUrl = getConfigItemStringValue(configFile, sectionName, "root_url", fmt.Sprintf("%s://%s:%d/", string(config.Protocol), config.Domain, config.HttpPort))
|
||||||
|
|
||||||
if config.RootUrl[len(config.RootUrl)-1] != '/' {
|
if config.RootUrl[len(config.RootUrl)-1] != '/' {
|
||||||
config.RootUrl += "/"
|
config.RootUrl += "/"
|
||||||
}
|
}
|
||||||
|
|
||||||
staticRootPath := getConfigItemStringValue(configFile, sectionName, "static_root_path", DEFAULT_STATIC_ROOT_PATH)
|
staticRootPath := getConfigItemStringValue(configFile, sectionName, "static_root_path", defaultStaticRootPath)
|
||||||
finalStaticRootPath, err := getFinalPath(config.WorkingPath, staticRootPath)
|
finalStaticRootPath, err := getFinalPath(config.WorkingPath, staticRootPath)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -281,25 +281,25 @@ func loadServerConfiguration(config *Config, configFile *ini.File, sectionName s
|
|||||||
func loadDatabaseConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
func loadDatabaseConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||||
dbConfig := &DatabaseConfig{}
|
dbConfig := &DatabaseConfig{}
|
||||||
|
|
||||||
dbConfig.DatabaseType = getConfigItemStringValue(configFile, sectionName, "type", DBTYPE_MYSQL)
|
dbConfig.DatabaseType = getConfigItemStringValue(configFile, sectionName, "type", MySqlDbType)
|
||||||
dbConfig.DatabaseHost = getConfigItemStringValue(configFile, sectionName, "host", DEFAULT_DATABASE_HOST)
|
dbConfig.DatabaseHost = getConfigItemStringValue(configFile, sectionName, "host", defaultDatabaseHost)
|
||||||
dbConfig.DatabaseName = getConfigItemStringValue(configFile, sectionName, "name", DEFAULT_DATABASE_NAME)
|
dbConfig.DatabaseName = getConfigItemStringValue(configFile, sectionName, "name", defaultDatabaseName)
|
||||||
dbConfig.DatabaseUser = getConfigItemStringValue(configFile, sectionName, "user")
|
dbConfig.DatabaseUser = getConfigItemStringValue(configFile, sectionName, "user")
|
||||||
dbConfig.DatabasePassword = getConfigItemStringValue(configFile, sectionName, "passwd")
|
dbConfig.DatabasePassword = getConfigItemStringValue(configFile, sectionName, "passwd")
|
||||||
|
|
||||||
if dbConfig.DatabaseType == DBTYPE_POSTGRES {
|
if dbConfig.DatabaseType == PostgresDbType {
|
||||||
dbConfig.DatabaseSSLMode = getConfigItemStringValue(configFile, sectionName, "ssl_mode")
|
dbConfig.DatabaseSSLMode = getConfigItemStringValue(configFile, sectionName, "ssl_mode")
|
||||||
}
|
}
|
||||||
|
|
||||||
if dbConfig.DatabaseType == DBTYPE_SQLITE3 {
|
if dbConfig.DatabaseType == Sqlite3DbType {
|
||||||
staticDBPath := getConfigItemStringValue(configFile, sectionName, "db_path")
|
staticDBPath := getConfigItemStringValue(configFile, sectionName, "db_path")
|
||||||
finalStaticDBPath, _ := getFinalPath(config.WorkingPath, staticDBPath)
|
finalStaticDBPath, _ := getFinalPath(config.WorkingPath, staticDBPath)
|
||||||
dbConfig.DatabasePath = finalStaticDBPath
|
dbConfig.DatabasePath = finalStaticDBPath
|
||||||
}
|
}
|
||||||
|
|
||||||
dbConfig.MaxIdleConnection = getConfigItemIntValue(configFile, sectionName, "max_idle_conn", DEFAULT_DATABASE_MAX_IDLE_CONN)
|
dbConfig.MaxIdleConnection = getConfigItemIntValue(configFile, sectionName, "max_idle_conn", defaultDatabaseMaxIdleConn)
|
||||||
dbConfig.MaxOpenConnection = getConfigItemIntValue(configFile, sectionName, "max_open_conn", DEFAULT_DATABASE_MAX_OPEN_CONN)
|
dbConfig.MaxOpenConnection = getConfigItemIntValue(configFile, sectionName, "max_open_conn", defaultDatabaseMaxOpenConn)
|
||||||
dbConfig.ConnectionMaxLifeTime = getConfigItemIntValue(configFile, sectionName, "conn_max_lifetime", DEFAULT_DATABASE_CONN_MAX_LIFETIME)
|
dbConfig.ConnectionMaxLifeTime = getConfigItemIntValue(configFile, sectionName, "conn_max_lifetime", defaultDatabaseConnMaxLifetime)
|
||||||
|
|
||||||
config.DatabaseConfig = dbConfig
|
config.DatabaseConfig = dbConfig
|
||||||
config.EnableQueryLog = getConfigItemBoolValue(configFile, sectionName, "log_query", false)
|
config.EnableQueryLog = getConfigItemBoolValue(configFile, sectionName, "log_query", false)
|
||||||
@@ -309,7 +309,7 @@ func loadDatabaseConfiguration(config *Config, configFile *ini.File, sectionName
|
|||||||
}
|
}
|
||||||
|
|
||||||
func loadLogConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
func loadLogConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||||
config.LogModes = strings.Split(getConfigItemStringValue(configFile, sectionName, "mode", DEFAULT_LOG_MODE), " ")
|
config.LogModes = strings.Split(getConfigItemStringValue(configFile, sectionName, "mode", defaultLogMode), " ")
|
||||||
|
|
||||||
for i := 0; i < len(config.LogModes); i++ {
|
for i := 0; i < len(config.LogModes); i++ {
|
||||||
logMode := config.LogModes[i]
|
logMode := config.LogModes[i]
|
||||||
@@ -323,7 +323,7 @@ func loadLogConfiguration(config *Config, configFile *ini.File, sectionName stri
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
config.LogLevel = getLogLevel(getConfigItemStringValue(configFile, sectionName, "level"), DEFAULT_LOG_LEVEL)
|
config.LogLevel = getLogLevel(getConfigItemStringValue(configFile, sectionName, "level"), defaultLoglevel)
|
||||||
|
|
||||||
if config.EnableFileLog {
|
if config.EnableFileLog {
|
||||||
config.FileLogPath = getConfigItemStringValue(configFile, sectionName, "log_path")
|
config.FileLogPath = getConfigItemStringValue(configFile, sectionName, "log_path")
|
||||||
@@ -333,8 +333,8 @@ func loadLogConfiguration(config *Config, configFile *ini.File, sectionName stri
|
|||||||
}
|
}
|
||||||
|
|
||||||
func loadUuidConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
func loadUuidConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||||
if getConfigItemStringValue(configFile, sectionName, "generator_type") == UUID_GENERATOR_TYPE_INTERNAL {
|
if getConfigItemStringValue(configFile, sectionName, "generator_type") == InternalUuidGeneratorType {
|
||||||
config.UuidGeneratorType = UUID_GENERATOR_TYPE_INTERNAL
|
config.UuidGeneratorType = InternalUuidGeneratorType
|
||||||
} else {
|
} else {
|
||||||
return errs.ErrInvalidUuidMode
|
return errs.ErrInvalidUuidMode
|
||||||
}
|
}
|
||||||
@@ -345,13 +345,13 @@ func loadUuidConfiguration(config *Config, configFile *ini.File, sectionName str
|
|||||||
}
|
}
|
||||||
|
|
||||||
func loadSecurityConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
func loadSecurityConfiguration(config *Config, configFile *ini.File, sectionName string) error {
|
||||||
config.SecretKey = getConfigItemStringValue(configFile, sectionName, "secret_key", DEFAULT_SECRET_KEY)
|
config.SecretKey = getConfigItemStringValue(configFile, sectionName, "secret_key", defaultSecretKey)
|
||||||
config.EnableTwoFactor = getConfigItemBoolValue(configFile, sectionName, "enable_two_factor", true)
|
config.EnableTwoFactor = getConfigItemBoolValue(configFile, sectionName, "enable_two_factor", true)
|
||||||
|
|
||||||
config.TokenExpiredTime = getConfigItemIntValue(configFile, sectionName, "token_expired_time", DEFAULT_TOKEN_EXPIRED_TIME)
|
config.TokenExpiredTime = getConfigItemIntValue(configFile, sectionName, "token_expired_time", defaultTokenExpiredTime)
|
||||||
config.TokenExpiredTimeDuration = time.Duration(config.TokenExpiredTime) * time.Second
|
config.TokenExpiredTimeDuration = time.Duration(config.TokenExpiredTime) * time.Second
|
||||||
|
|
||||||
config.TemporaryTokenExpiredTime = getConfigItemIntValue(configFile, sectionName, "temporary_token_expired_time", DEFAULT_TEMPORARY_TOKEN_EXPIRED_TIME)
|
config.TemporaryTokenExpiredTime = getConfigItemIntValue(configFile, sectionName, "temporary_token_expired_time", defaultTemporaryTokenExpiredTime)
|
||||||
config.TemporaryTokenExpiredTimeDuration = time.Duration(config.TemporaryTokenExpiredTime) * time.Second
|
config.TemporaryTokenExpiredTimeDuration = time.Duration(config.TemporaryTokenExpiredTime) * time.Second
|
||||||
|
|
||||||
config.EnableRequestIdHeader = getConfigItemBoolValue(configFile, sectionName, "request_id_header", true)
|
config.EnableRequestIdHeader = getConfigItemBoolValue(configFile, sectionName, "request_id_header", true)
|
||||||
@@ -366,7 +366,7 @@ func loadUserConfiguration(config *Config, configFile *ini.File, sectionName str
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getWorkingPath() (string, error) {
|
func getWorkingPath() (string, error) {
|
||||||
workingPath := os.Getenv(LAB_WORK_DIR)
|
workingPath := os.Getenv(labWorkDirEnvName)
|
||||||
|
|
||||||
if workingPath != "" {
|
if workingPath != "" {
|
||||||
return workingPath, nil
|
return workingPath, nil
|
||||||
@@ -445,7 +445,7 @@ func getConfigItemBoolValue(configFile *ini.File, sectionName string, itemName s
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getEnvironmentKey(sectionName string, itemName string) string {
|
func getEnvironmentKey(sectionName string, itemName string) string {
|
||||||
return fmt.Sprintf("%s_%s_%s", LAB_ENVIRONMENT_KEY_PREFIX, strings.ToUpper(sectionName), strings.ToUpper(itemName))
|
return fmt.Sprintf("%s_%s_%s", labEnvNamePrefix, strings.ToUpper(sectionName), strings.ToUpper(itemName))
|
||||||
}
|
}
|
||||||
|
|
||||||
func getLogLevel(logLevelStr string, defaultLogLevel Level) Level {
|
func getLogLevel(logLevelStr string, defaultLogLevel Level) Level {
|
||||||
|
|||||||
@@ -16,10 +16,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
CHARACTERS = "!#$&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"
|
availableCharacters = "!#$&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"
|
||||||
NUMBER_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyz"
|
availableNumberAndLetters = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||||
CHARACTERS_LENGTH = len(CHARACTERS)
|
availableCharactersLength = len(availableCharacters)
|
||||||
NUMBER_AND_LETTERS_LENGTH = len(NUMBER_AND_LETTERS)
|
availableNumberAndLettersLength = len(availableNumberAndLetters)
|
||||||
)
|
)
|
||||||
|
|
||||||
// SubString returns part of the source string according to start index and length
|
// SubString returns part of the source string according to start index and length
|
||||||
@@ -77,13 +77,13 @@ func GetRandomString(n int) (string, error) {
|
|||||||
var result = make([]byte, n)
|
var result = make([]byte, n)
|
||||||
|
|
||||||
for i := 0; i < n; i++ {
|
for i := 0; i < n; i++ {
|
||||||
index, err := GetRandomInteger(CHARACTERS_LENGTH)
|
index, err := GetRandomInteger(availableCharactersLength)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
result[i] = CHARACTERS[index]
|
result[i] = availableCharacters[index]
|
||||||
}
|
}
|
||||||
|
|
||||||
return string(result), nil
|
return string(result), nil
|
||||||
@@ -94,13 +94,13 @@ func GetRandomNumberOrLetter(n int) (string, error) {
|
|||||||
var result = make([]byte, n)
|
var result = make([]byte, n)
|
||||||
|
|
||||||
for i := 0; i < n; i++ {
|
for i := 0; i < n; i++ {
|
||||||
index, err := GetRandomInteger(NUMBER_AND_LETTERS_LENGTH)
|
index, err := GetRandomInteger(availableNumberAndLettersLength)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
result[i] = NUMBER_AND_LETTERS[index]
|
result[i] = availableNumberAndLetters[index]
|
||||||
}
|
}
|
||||||
|
|
||||||
return string(result), nil
|
return string(result), nil
|
||||||
|
|||||||
@@ -9,20 +9,20 @@ import (
|
|||||||
|
|
||||||
// Length and mask of all information in uuid
|
// Length and mask of all information in uuid
|
||||||
const (
|
const (
|
||||||
INTERNAL_UUID_UNIX_TIME_BITS = 32
|
internalUuidUnixTimeBits = 32
|
||||||
INTERNAL_UUID_UNIX_TIME_MASK = (1 << INTERNAL_UUID_UNIX_TIME_BITS) - 1
|
internalUuidUnixTimeMask = (1 << internalUuidUnixTimeBits) - 1
|
||||||
|
|
||||||
INTERNAL_UUID_TYPE_BITS = 4
|
internalUuidTypeBits = 4
|
||||||
INTERNAL_UUID_TYPE_MASK = (1 << INTERNAL_UUID_TYPE_BITS) - 1
|
internalUuidTypeMask = (1 << internalUuidTypeBits) - 1
|
||||||
|
|
||||||
INTERNAL_UUID_SERVER_ID_BITS = 8
|
internalUuidServerIdBits = 8
|
||||||
INTERNAL_UUID_SERVER_ID_MASK = (1 << INTERNAL_UUID_SERVER_ID_BITS) - 1
|
internalUuidServerIdMask = (1 << internalUuidServerIdBits) - 1
|
||||||
|
|
||||||
INTERNAL_UUID_SEQ_ID_BITS = 19
|
internalUuidSeqIdBits = 19
|
||||||
INTERNAL_UUID_SEQ_ID_MASK = (1 << INTERNAL_UUID_SEQ_ID_BITS) - 1
|
internalUuidSeqIdMask = (1 << internalUuidSeqIdBits) - 1
|
||||||
|
|
||||||
SEQ_NUMBER_ID_BITS = 32
|
seqNumberIdBits = 32
|
||||||
SEQ_NUMBER_ID_MASK = (1 << SEQ_NUMBER_ID_BITS) - 1
|
seqNumberIdMask = (1 << seqNumberIdBits) - 1
|
||||||
)
|
)
|
||||||
|
|
||||||
// InternalUuidInfo represents a struct which has all information in uuid
|
// InternalUuidInfo represents a struct which has all information in uuid
|
||||||
@@ -36,7 +36,7 @@ type InternalUuidInfo struct {
|
|||||||
// InternalUuidGenerator represents internal bundled uuid generator
|
// InternalUuidGenerator represents internal bundled uuid generator
|
||||||
type InternalUuidGenerator struct {
|
type InternalUuidGenerator struct {
|
||||||
uuidServerId uint8
|
uuidServerId uint8
|
||||||
uuidSeqNumbers [1 << INTERNAL_UUID_TYPE_BITS]uint64
|
uuidSeqNumbers [1 << internalUuidTypeBits]uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewInternalUuidGenerator returns a new internal uuid generator
|
// NewInternalUuidGenerator returns a new internal uuid generator
|
||||||
@@ -60,24 +60,24 @@ func (u *InternalUuidGenerator) GenerateUuid(idType UuidType) int64 {
|
|||||||
unixTime = uint64(time.Now().Unix())
|
unixTime = uint64(time.Now().Unix())
|
||||||
newSeqId = atomic.AddUint64(&u.uuidSeqNumbers[uuidType], 1)
|
newSeqId = atomic.AddUint64(&u.uuidSeqNumbers[uuidType], 1)
|
||||||
|
|
||||||
if newSeqId>>SEQ_NUMBER_ID_BITS == unixTime {
|
if newSeqId>>seqNumberIdBits == unixTime {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
currentSeqId := newSeqId
|
currentSeqId := newSeqId
|
||||||
newSeqId = unixTime << SEQ_NUMBER_ID_BITS
|
newSeqId = unixTime << seqNumberIdBits
|
||||||
|
|
||||||
if atomic.CompareAndSwapUint64(&u.uuidSeqNumbers[uuidType], currentSeqId, newSeqId) {
|
if atomic.CompareAndSwapUint64(&u.uuidSeqNumbers[uuidType], currentSeqId, newSeqId) {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
seqId := newSeqId & SEQ_NUMBER_ID_MASK
|
seqId := newSeqId & seqNumberIdMask
|
||||||
|
|
||||||
unixTimePart := (int64(unixTime) & INTERNAL_UUID_UNIX_TIME_MASK) << (INTERNAL_UUID_TYPE_BITS + INTERNAL_UUID_SERVER_ID_BITS + INTERNAL_UUID_SEQ_ID_BITS)
|
unixTimePart := (int64(unixTime) & internalUuidUnixTimeMask) << (internalUuidTypeBits + internalUuidServerIdBits + internalUuidSeqIdBits)
|
||||||
uuidTypePart := (int64(uuidType) & INTERNAL_UUID_TYPE_MASK) << (INTERNAL_UUID_SERVER_ID_BITS + INTERNAL_UUID_SEQ_ID_BITS)
|
uuidTypePart := (int64(uuidType) & internalUuidTypeMask) << (internalUuidServerIdBits + internalUuidSeqIdBits)
|
||||||
uuidServerIdPart := (int64(u.uuidServerId) & INTERNAL_UUID_SERVER_ID_MASK) << INTERNAL_UUID_SEQ_ID_BITS
|
uuidServerIdPart := (int64(u.uuidServerId) & internalUuidServerIdMask) << internalUuidSeqIdBits
|
||||||
seqIdPart := int64(seqId) & INTERNAL_UUID_SEQ_ID_MASK
|
seqIdPart := int64(seqId) & internalUuidSeqIdMask
|
||||||
|
|
||||||
uuid := unixTimePart | uuidTypePart | uuidServerIdPart | seqIdPart
|
uuid := unixTimePart | uuidTypePart | uuidServerIdPart | seqIdPart
|
||||||
|
|
||||||
@@ -86,16 +86,16 @@ func (u *InternalUuidGenerator) GenerateUuid(idType UuidType) int64 {
|
|||||||
|
|
||||||
// ParseUuidInfo returns a info struct which contains all information in uuid
|
// ParseUuidInfo returns a info struct which contains all information in uuid
|
||||||
func (u *InternalUuidGenerator) ParseUuidInfo(uuid int64) *InternalUuidInfo {
|
func (u *InternalUuidGenerator) ParseUuidInfo(uuid int64) *InternalUuidInfo {
|
||||||
seqId := uint32(uuid & INTERNAL_UUID_SEQ_ID_MASK)
|
seqId := uint32(uuid & internalUuidSeqIdMask)
|
||||||
uuid = uuid >> INTERNAL_UUID_SEQ_ID_BITS
|
uuid = uuid >> internalUuidSeqIdBits
|
||||||
|
|
||||||
uuidServerId := uint8(uuid & INTERNAL_UUID_SERVER_ID_MASK)
|
uuidServerId := uint8(uuid & internalUuidServerIdMask)
|
||||||
uuid = uuid >> INTERNAL_UUID_SERVER_ID_BITS
|
uuid = uuid >> internalUuidServerIdBits
|
||||||
|
|
||||||
uuidType := uint8(uuid & INTERNAL_UUID_TYPE_MASK)
|
uuidType := uint8(uuid & internalUuidTypeMask)
|
||||||
uuid = uuid >> INTERNAL_UUID_TYPE_BITS
|
uuid = uuid >> internalUuidTypeBits
|
||||||
|
|
||||||
unixTime := uint32(uuid & INTERNAL_UUID_UNIX_TIME_MASK)
|
unixTime := uint32(uuid & internalUuidUnixTimeMask)
|
||||||
|
|
||||||
return &InternalUuidInfo{
|
return &InternalUuidInfo{
|
||||||
UnixTime: unixTime,
|
UnixTime: unixTime,
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ var (
|
|||||||
|
|
||||||
// InitializeUuidGenerator initialized the current uuid generator according to the config
|
// InitializeUuidGenerator initialized the current uuid generator according to the config
|
||||||
func InitializeUuidGenerator(config *settings.Config) error {
|
func InitializeUuidGenerator(config *settings.Config) error {
|
||||||
if config.UuidGeneratorType == settings.UUID_GENERATOR_TYPE_INTERNAL {
|
if config.UuidGeneratorType == settings.InternalUuidGeneratorType {
|
||||||
generator, err := NewInternalUuidGenerator(config)
|
generator, err := NewInternalUuidGenerator(config)
|
||||||
Container.Current = generator
|
Container.Current = generator
|
||||||
|
|
||||||
|
|||||||
@@ -4,10 +4,11 @@ import (
|
|||||||
"github.com/go-playground/validator/v10"
|
"github.com/go-playground/validator/v10"
|
||||||
)
|
)
|
||||||
|
|
||||||
const PARENT_ACCOUNT_CURRENCY_PLACEHODLER = "---"
|
// ParentAccountCurrencyPlaceholder represents the currency field of parent account stored in database
|
||||||
|
const ParentAccountCurrencyPlaceholder = "---"
|
||||||
|
|
||||||
// ISO 4217
|
// ISO 4217
|
||||||
var ALL_CURRENCY_NAMES = map[string]bool{
|
var allCurrencyNames = map[string]bool{
|
||||||
"AED": true, //UAE Dirham
|
"AED": true, //UAE Dirham
|
||||||
"AFN": true, //Afghani
|
"AFN": true, //Afghani
|
||||||
"ALL": true, //Lek
|
"ALL": true, //Lek
|
||||||
@@ -169,11 +170,11 @@ var ALL_CURRENCY_NAMES = map[string]bool{
|
|||||||
|
|
||||||
func ValidCurrency(fl validator.FieldLevel) bool {
|
func ValidCurrency(fl validator.FieldLevel) bool {
|
||||||
if value, ok := fl.Field().Interface().(string); ok {
|
if value, ok := fl.Field().Interface().(string); ok {
|
||||||
if value == PARENT_ACCOUNT_CURRENCY_PLACEHODLER {
|
if value == ParentAccountCurrencyPlaceholder {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
_, ok := ALL_CURRENCY_NAMES[value]
|
_, ok := allCurrencyNames[value]
|
||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user