app

package
v0.0.22 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2024 License: MIT Imports: 43 Imported by: 0

Documentation

Overview

app is a package to accommodate classes or common variables that are used in almost all end points.

Index

Constants

View Source
const (
	TestInvalidToken        = "invalidToken"
	TestForbiddenToken      = "forbiddenToken"
	TestReadOnlyToken       = "detail,list"
	TestCreateReadOnlyToken = "detail,list,create"
	TestEditReadOnlyToken   = "detail,list,edit"
	TestDeleteReadOnlyToken = "detail,list,delete"
	TestFullAccessToken     = "fullAccessToken"
)
View Source
const CtxKey = "ctx"

Variables

View Source
var (
	APP_VERSION = "23.03.161330"

	APP_ENV  = "local"
	APP_PORT = "4001"
	APP_URL  = "http://localhost:4001"

	IS_MAIN_SERVER = true // set to true to run migration, seed and task scheduling

	IS_GENERATE_OPEN_API_DOC = false

	// for testing
	ENV_FILE            = ""
	IS_USE_MOCK_SERVICE = false
	IS_USE_MOCK_DB      = false

	LOG_LEVEL                 = "info"                             // debug, info, warning, error
	LOG_CONSOLE_ENABLED       = true                               // print log to the terminal
	LOG_CONSOLE_WITH_JSON     = false                              // log console with json format
	LOG_CONSOLE_TIME_FORMAT   = "[2006-01-02 15:04:05.000 Z07:00]" // log console time format
	LOG_CONSOLE_EXCLUDED_KEYS = ""                                 // log console excluded keys
	LOG_FILE_ENABLED          = true                               // log to a file. the fields below can be skipped if this value is false
	LOG_FILE_WITH_JSON        = true                               // log file with json format
	LOG_FILE_USE_LOCAL_TIME   = true                               // if false log rotation filename will be use UTC time
	LOG_FILE_FILENAME         = "logs/api.log"                     // log file filename
	LOG_FILE_MAX_SIZE         = 100                                // MB
	LOG_FILE_MAX_AGE          = 7                                  // days
	LOG_FILE_MAX_BACKUPS      = 0                                  // files
	LOG_WITH_DURATION         = true
	LOG_WITH_REQUEST_HEADER   = true
	LOG_WITH_REQUEST_BODY     = true
	LOG_WITH_RESPONSE_BODY    = true

	JWT_KEY     = "f4cac8b77a8d4cb5881fac72388bb226"
	CRYPTO_KEY  = "wAGyTpFQX5uKV3JInABXXEdpgFkQLPTf"
	CRYPTO_SALT = "0de0cda7d2dd4937a1c4f7ddc43c580f"
	CRYPTO_INFO = "info"

	DB_DRIVER            = "postgres"
	DB_HOST              = "127.0.0.1"
	DB_HOST_READ         = ""
	DB_PORT              = 5432
	DB_DATABASE          = "data.db"
	DB_USERNAME          = "postgres"
	DB_PASSWORD          = "secret"
	DB_MAX_OPEN_CONNS    = 0
	DB_MAX_IDLE_CONNS    = 5
	DB_CONN_MAX_LIFETIME = time.Hour // on .env = "1h". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
	DB_IS_DEBUG          = false

	REDIS_HOST      = "127.0.0.1"
	REDIS_PORT      = "6379"
	REDIS_CACHE_DB  = 3
	REDIS_REPORT_DB = 3
	REDIS_USERNAME  = ""
	REDIS_PASSWORD  = ""

	FS_DRIVER          = "local"
	FS_LOCAL_DIR_PATH  = "storages"
	FS_PUBLIC_DIR_PATH = "storages"
	FS_END_POINT       = "s3.amazonaws.com"
	FS_PORT            = 443
	FS_REGION          = "ap-southeast-3"
	FS_BUCKET_NAME     = "attachments"
	FS_ACCESS_KEY      = ""
	FS_SECRET_KEY      = ""

	TELEGRAM_ALERT_TOKEN   = ""
	TELEGRAM_ALERT_USER_ID = ""
)

These variables represent various configuration settings used by the application. Each variable is assigned a default value or a value loaded from environment variables.

Functions

func Cache

func Cache() *cacheUtil

Cache returns a pointer to the cacheUtil instance (cache). If cache is not initialized, it creates a new cacheUtil instance, configures it, and assigns it to cache. It ensures that only one instance of cacheUtil is created and reused.

func Config

func Config()

Config initializes the configuration (config) if it is not already initialized. If config is not initialized, it creates a new configUtil instance, configures it, and assigns it to config. It ensures that only one instance of config is created and reused.

func Crypto

func Crypto() *cryptoUtil

Crypto returns a pointer to the cryptoUtil instance (crpto). If crpto is not initialized, it creates a new cryptoUtil instance, configures it, and assigns it to crpto. It ensures that only one instance of cryptoUtil is created and reused.

func DB

func DB() *dbUtil

DB returns a pointer to the dbUtil instance (db). If db is not initialized, it creates a new dbUtil instance, configures it, and assigns it to db. It ensures that only one instance of dbUtil is created and reused.

func Error added in v0.0.20

func Error() *errorUtil

Error returns a pointer to the errorUtil instance (eu). If eu is not initialized, it creates a new errorUtil instance and assigns it to eu. It ensures that only one instance of errorUtil is created and reused.

func FS

func FS() *fsUtil

FS returns the instance of fsUtil (filesystem utility). If the fsClient is nil, it initializes it by calling the configure method of fsUtil. It then returns the fsClient.

func HttpClient

func HttpClient(method, url string) *httpClientUtil

HttpClient creates and returns a new instance of httpClientUtil. It takes two parameters: method (HTTP method) and url (URL). The function initializes the Method and Url fields of the httpClientUtil instance and returns it.

func Logger

func Logger() *loggerUtil

Logger returns a pointer to the loggerUtil instance (logger). If logger is not initialized, it creates a new loggerUtil instance, configures it, and assigns it to logger. It ensures that only one instance of loggerUtil is created and reused.

func Mock

func Mock() *mockUtil

add your mock service here, for example :

// original func (add IS_USE_MOCK_SERVICE_ABC and IS_USE_MOCK_SUCCESS to config)
func (*UseCaseHandler) CallServiceABC(ctx *Ctx, param RequestServiceABC) (ResponseServiceABC, error) {
	if IS_USE_MOCK_SERVICE_ABC {
		return Mock().CallServiceABC(ctx, param)
	}
	var err error
	res := ResponseServiceABC{}
	// do something here
	return res, err
}

// mock func
func (*mockHandler) CallServiceABC(ctx *Ctx, param RequestServiceABC) (ResponseServiceABC, error) {
	if IS_USE_MOCK_SUCCESS  {
		// return success dummy
	}
	return ResponseServiceABC{}, NewError(http.StatusInternalServerError, "Something wrong")
}

func NewCrypto

func NewCrypto(keys ...string) *cryptoUtil

NewCrypto creates a new cryptoUtil instance with custom keys. It initializes the instance, configures it, and assigns the custom keys (if provided) to the corresponding fields (c.Key, c.Salt, c.Info, c.JWTKey). It returns the created cryptoUtil instance.

func OpenAPI

func OpenAPI() *openAPIUtil

func OpenAPIError

func OpenAPIError() *openAPIError

func Query added in v0.0.20

func Query() *queryUtil

Query returns a pointer to the queryUtil instance (qu). If qu is not initialized, it creates a new queryUtil instance, configures it, and assigns it to qu. It ensures that only one instance of queryUtil is created and reused.

func Server

func Server() *serverUtil

func Telegram

func Telegram(message ...string) *telegramUtil

telegram returns a pointer to the telegramUtil instance (telegram). If telegram is not initialized, it creates a new telegramUtil instance, configures it, and assigns it to telegram. It ensures that only one instance of telegramUtil is created and reused.

func Test added in v0.0.12

func Test() *testUtil

func Translator

func Translator() *translatorUtil

Translator returns a pointer to the translatorUtil instance (translator). If translator is not initialized, it creates a new translatorUtil instance, configures it, and assigns it to translator. It ensures that only one instance of translatorUtil is created and reused.

func Validator

func Validator() *validatorUtil

Validator returns a pointer to the validatorUtil instance (validator). If validator is not initialized, it creates a new validatorUtil instance, configures it, and assigns it to validator. It ensures that only one instance of validatorUtil is created and reused.

Types

type Action

type Action struct {
	Method string
	Path   string
	DataID string
}

type Ctx

type Ctx struct {
	Lang   string // language code
	Action Action // general request info
	Err    error

	IsAsync bool // for async use, autocommit
	// contains filtered or unexported fields
}

func (Ctx) DB

func (c Ctx) DB(connName ...string) (*gorm.DB, error)

This method returns the GORM database connection based on the provided connection name (connName). If IS_USE_MOCK_DB is true, it returns the mock database connection. If c.IsAsync is false and there is an active transaction (c.mainTx), it returns the transaction connection. Otherwise, it returns the main database connection.

func (Ctx) Deleted added in v0.0.21

func (c Ctx) Deleted(entity, key, value string) map[string]any

Deleted return translated message for deleted data.

func (Ctx) Hook

func (c Ctx) Hook(method, reason, id string, old any)

This method performs a hook operation, which involves sleeping for 2 seconds and performing some data manipulation based on the provided parameters. It checks if the old value implements the IsFlat() method and determines whether the data is flat. If the data is not flat, it converts the old value to a structured format. You can do anything you want with this method, for example to save user activity log, send callback/webhook, etc.

func (Ctx) NotFoundError

func (c Ctx) NotFoundError(err error, entity, key, value string) error

NotFoundError creates a new HTTP error with a "not found" status and a translated error message. The translated message includes the entity, key, and value involved in the error. It returns the created error or nil if the given error is not a "not found" error.

func (Ctx) Trans

func (c Ctx) Trans(key string, params ...map[string]string) string

Trans translates a given key using the language specified in the context (c.Lang). It supports optional parameters for dynamic translation.

func (*Ctx) TxBegin

func (c *Ctx) TxBegin() error

TxBegin begins a new transaction using the main database connection. It returns an error if there is an issue establishing the connection.

func (*Ctx) TxCommit

func (c *Ctx) TxCommit()

TxCommit commits the current transaction if it exists (mainTx is not nil). Called in middleware when there is no error (http status code is 2xx). It does nothing if there is no active transaction.

func (*Ctx) TxRollback

func (c *Ctx) TxRollback()

TxRollback rolls back the current transaction if it exists (mainTx is not nil). Called on middleware when there is an error (http status code not 2xx) It does nothing if there is no active transaction.

func (Ctx) ValidateParam

func (c Ctx) ValidateParam(v any) error

This method validates the parameters based on struct tag. It returns an error using the language specified in the context (c.Lang) if the validation fails.

func (Ctx) ValidatePermission

func (c Ctx) ValidatePermission(aclKey string) error

ValidatePermission validates permission for a given ACL key. It returns an error if the permission is not granted.

type FileDeleteOption

type FileDeleteOption struct {
	minio.RemoveObjectOptions
}

FileDeleteOption represents the options for file deletion. It embeds minio.RemoveObjectOptions to provide additional delete options.

type FileUploadInfo

type FileUploadInfo struct {
	minio.UploadInfo
}

FileUploadOption represents the information related to a file upload. It embeds minio.UploadInfo to store upload-specific details.

type FileUploadOption

type FileUploadOption struct {
	minio.PutObjectOptions
}

This type represents the options for file upload. It embeds minio.PutObjectOptions to store upload-specific details.

type ListModel

type ListModel struct {
	Count       int64 `json:"count"`
	PageContext struct {
		Page      int `json:"page"`
		PerPage   int `json:"per_page"`
		PageCount int `json:"total_pages"`
	} `json:"page_context"`
	Links struct {
		First    string `json:"first"`
		Previous string `json:"previous"`
		Next     string `json:"next"`
		Last     string `json:"last"`
	} `json:"links"`
	Data []map[string]any `json:"results"`
}

func (*ListModel) SetData

func (list *ListModel) SetData(data []map[string]any, query url.Values)
func (list *ListModel) SetLink(c *fiber.Ctx)

func (*ListModel) SetOpenAPISchema added in v0.0.20

func (list *ListModel) SetOpenAPISchema(m ModelInterface) map[string]any

type Model

type Model struct {
	grest.Model
}

type ModelInterface

type ModelInterface interface {
	grest.ModelInterface
}

type NullBool

type NullBool struct {
	grest.NullBool
}

NullBool is nullable Bool, it embeds a grest.NullBool, so you can add your own method or override grest.NullBool method

func NewNullBool

func NewNullBool(val bool) NullBool

NewNullBool return NullBool

type NullDate

type NullDate struct {
	grest.NullDate
}

NullDate is nullable Date, it embeds a grest.NullDate, so you can add your own method or override grest.NullDate method

func NewNullDate

func NewNullDate(val time.Time) NullDate

NewNullDate return NullDate

type NullDateTime

type NullDateTime struct {
	grest.NullDateTime
}

NullDateTime is nullable DateTime, it embeds a grest.NullDateTime, so you can add your own method or override grest.NullDateTime method

func NewNullDateTime

func NewNullDateTime(val time.Time) NullDateTime

NewNullDateTime return NullDateTime

type NullFloat64

type NullFloat64 struct {
	grest.NullFloat64
}

NullFloat64 is nullable Float64, it embeds a grest.NullFloat64, so you can add your own method or override grest.NullFloat64 method

func NewNullFloat64

func NewNullFloat64(val float64) NullFloat64

NewNullFloat64 return NullFloat64

type NullInt64

type NullInt64 struct {
	grest.NullInt64
}

NullInt64 is nullable Int64, it embeds a grest.NullInt64, so you can add your own method or override grest.NullInt64 method

func NewNullInt64

func NewNullInt64(val int64) NullInt64

NewNullInt64 return NullInt64

type NullJSON

type NullJSON struct {
	grest.NullJSON
}

NullJSON is nullable JSON, it embeds a grest.NullJSON, so you can add your own method or override grest.NullJSON method

type NullString

type NullString struct {
	grest.NullString
}

NullString is nullable String, it embeds a grest.NullString, so you can add your own method or override grest.NullString method

func NewNullString

func NewNullString(val string) NullString

NewNullString return NullString

type NullText

type NullText struct {
	grest.NullText
}

NullText is nullable Text, it embeds a grest.NullText, so you can add your own method or override grest.NullText method

func NewNullText

func NewNullText(val string) NullText

NewNullText return NullText

type NullTime

type NullTime struct {
	grest.NullTime
}

NullTime is nullable Time, it embeds a grest.NullTime, so you can add your own method or override grest.NullTime method

func NewNullTime

func NewNullTime(val time.Time) NullTime

NewNullTime return NullTime

type NullUUID

type NullUUID struct {
	grest.NullUUID
}

NullUUID is nullable UUID, it embeds a grest.NullUUID, so you can add your own method or override grest.NullUUID method

func NewNullUUID

func NewNullUUID(val ...string) NullUUID

NewNullUUID return NullUUID

type NullUnixTime added in v0.0.12

type NullUnixTime struct {
	grest.NullUnixTime
}

NullUnixTime is nullable Unix DateTime, it embeds a grest.NullUnixTime, so you can add your own method or override grest.NullUnixTime method

func NewNullUnixTime added in v0.0.12

func NewNullUnixTime(val time.Time) NullUnixTime

NewNullUnixTime return NullUnixTime

type OpenAPIOperation

type OpenAPIOperation struct {
	grest.OpenAPIOperation
}

type OpenAPIOperationInterface

type OpenAPIOperationInterface interface {
	grest.OpenAPIOperationInterface
}

type RegisteredJWTClaim added in v0.0.20

type RegisteredJWTClaim struct {

	// ID claim provides a unique identifier for the JWT.
	ID string `json:"jti,omitempty"`

	// Audience claim identifies the recipients that the JWT is intended for.
	Audience string `json:"aud,omitempty"`

	// Issuer claim identifies the principal that issued the JWT.
	Issuer string `json:"iss,omitempty"`

	// Subject claim identifies the principal that is the subject of the JWT.
	Subject string `json:"sub,omitempty"`

	// IssuedAt claim identifies the time at which the JWT was issued.
	// This claim can be used to determine the age of the JWT.
	IssuedAt NullUnixTime `json:"iat,omitempty"`

	// ExpiresAt claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.
	ExpiresAt NullUnixTime `json:"exp,omitempty"`

	// NotBefore claim identifies the time before which the JWT MUST NOT be accepted for processing.
	NotBefore NullUnixTime `json:"nbf,omitempty"`
}

RegisteredJWTClaim represents registered claim names in the IANA "JSON Web Token Claims" registry.

See: https://tools.ietf.org/html/rfc7519#section-4.1

func (RegisteredJWTClaim) IsValidAt added in v0.0.20

func (rc RegisteredJWTClaim) IsValidAt(now time.Time) bool

IsValidAt reports whether a token is valid at a given time.

func (RegisteredJWTClaim) IsValidExpiresAt added in v0.0.20

func (rc RegisteredJWTClaim) IsValidExpiresAt(now time.Time) bool

IsValidExpiresAt reports whether a token isn't expired at a given time.

func (RegisteredJWTClaim) IsValidIssuedAt added in v0.0.20

func (rc RegisteredJWTClaim) IsValidIssuedAt(now time.Time) bool

IsValidIssuedAt reports whether a token was created before a given time.

func (RegisteredJWTClaim) IsValidNotBefore added in v0.0.20

func (rc RegisteredJWTClaim) IsValidNotBefore(now time.Time) bool

IsValidNotBefore reports whether a token isn't used before a given time.

type Setting

type Setting struct {
	Key   string `gorm:"column:key;primaryKey"`
	Value string `gorm:"column:value"`
}

func (Setting) KeyField

func (Setting) KeyField() string

func (Setting) MigrationKey

func (Setting) MigrationKey() string

func (Setting) SeederKey added in v0.0.21

func (Setting) SeederKey() string

func (Setting) TableName

func (Setting) TableName() string

func (Setting) ValueField

func (Setting) ValueField() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL