Documentation
¶
Overview ¶
app merupakan class atau fungsi atau variabel umum yang dipakai pada sebagian besar API.
Index ¶
- Constants
- Variables
- func Config()
- func ErrorHandler(c *fiber.Ctx, err error) error
- func Find(db *gorm.DB, model ModelInterface, query url.Values) ([]map[string]any, error)
- func First(db *gorm.DB, model ModelInterface, query url.Values) error
- func Logger() *loggerUtil
- func Mock() *mockUtil
- func NewCrypto(keys ...string) *cryptoUtil
- func NewError(statusCode int, message string, detail ...any) *grest.Error
- func NotFoundHandler(c *fiber.Ctx) error
- func OpenAPI() *openAPIUtil
- func OpenAPIError() *openAPIError
- func PaginationInfo(db *gorm.DB, model ModelInterface, query url.Values) (int64, int, int, int, error)
- func ParseQuery(c *fiber.Ctx) url.Values
- func Recover(c *fiber.Ctx) (err error)
- func Test() *testUtil
- func VersionHandler(c *fiber.Ctx) error
- type Action
- type CacheInterface
- type CryptoInterface
- type Ctx
- func (c Ctx) DB(connName ...string) (*gorm.DB, error)
- func (c Ctx) Hook(method, reason, id string, old any)
- func (c Ctx) NotFoundError(err error, entity, key, value string) error
- func (c Ctx) Trans(key string, params ...map[string]string) string
- func (c *Ctx) TxBegin() error
- func (c *Ctx) TxCommit()
- func (c *Ctx) TxRollback()
- func (c Ctx) ValidateParam(v any) error
- func (c Ctx) ValidatePermission(aclKey string) error
- type DBInterface
- type FSInterface
- type FileDeleteOption
- type FileUploadInfo
- type FileUploadOption
- type HttpClientInterface
- type ListModel
- type Model
- type ModelInterface
- type NullBool
- type NullDate
- type NullDateTime
- type NullFloat64
- type NullInt64
- type NullJSON
- type NullString
- type NullText
- type NullTime
- type NullUUID
- type NullUnixTime
- type OpenAPIOperation
- type OpenAPIOperationInterface
- type ServerInterface
- type Setting
- type TelegramInterface
- type TranslatorInterface
- type ValidatorInterface
Constants ¶
const ( TestInvalidToken = "invalidToken" TestForbiddenToken = "forbiddenToken" TestReadOnlyToken = "detail,list" TestCreateReadOnlyToken = "detail,list,create" TestEditReadOnlyToken = "detail,list,edit" TestDeleteReadOnlyToken = "detail,list,delete" TestFullAccessToken = "fullAccessToken" )
const CtxKey = "ctx"
Variables ¶
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_CONSOLE_ENABLED = true // print log to the terminal LOG_FILE_ENABLED = true // log to a file. the fields below can be skipped if this value is false LOG_FILE_USE_LOCAL_TIME = true // if false log rotation filename will be use UTC time LOG_FILE_FILENAME = "logs/api.log" // LOG_FILE_MAX_SIZE = 100 // MB LOG_FILE_MAX_AGE = 7 // days LOG_FILE_MAX_BACKUPS = 0 // files 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 = "" )
default config
Functions ¶
func ErrorHandler ¶
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 (*mockHandler) 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 NotFoundHandler ¶
func NotFoundHandler(c *fiber.Ctx) error
func OpenAPIError ¶
func OpenAPIError() *openAPIError
func PaginationInfo ¶
func ParseQuery ¶
func VersionHandler ¶
func VersionHandler(c *fiber.Ctx) error
Types ¶
type CacheInterface ¶
type CacheInterface interface {
Get(key string, val any) error
Set(key string, val any, e ...time.Duration) error
Delete(key string) error
DeleteWithPrefix(prefix string) error
Invalidate(prefix string, keys ...string)
Clear() error
}
func Cache ¶
func Cache() CacheInterface
type CryptoInterface ¶
type CryptoInterface interface {
NewToken() string
NewHash(text string, cost ...int) (string, error)
CompareHash(hashed, text string) error
NewJWT(claims any) (string, error)
ParseAndVerifyJWT(token string, claims any) error
Encrypt(text string) (string, error)
Decrypt(text string) (string, error)
GenerateKey() ([]byte, error)
PKCS5Padding(ciphertext []byte, blockSize int) []byte
PKCS5Unpadding(encrypt []byte) ([]byte, error)
}
func Crypto ¶
func Crypto() CryptoInterface
type Ctx ¶
type Ctx struct {
Lang string // bahasa yang digunakan oleh user ybs
Action Action // informasi umum terkait request
IsAsync bool // for async use, autocommit
// contains filtered or unexported fields
}
func (Ctx) Trans ¶
Trans memberikan translasi atas key dan params sesuai dengan bahasa yang sedang digunakan user.
func (*Ctx) TxCommit ¶
func (c *Ctx) TxCommit()
Commit db transaction, dipanggil dari middleware setelah dari handler ketika response nya berhasil (2xx).
func (*Ctx) TxRollback ¶
func (c *Ctx) TxRollback()
Rollback db transaction, dipanggil dari middleware setelah dari handler ketika response nya error (selain 2xx).
func (Ctx) ValidateParam ¶
ValidateParam melakukan validasi atas payload yang dikirim.
func (Ctx) ValidatePermission ¶
ValidateAuth melakukan validasi apakah permintaan dilakukan oleh user yang berwenang atau tidak.
type DBInterface ¶
type DBInterface interface {
RegisterConn(connName string, conn *gorm.DB)
Conn(connName string) (*gorm.DB, error)
Close()
RegisterTable(connName string, t grest.Table) error
MigrateTable(tx *gorm.DB, connName string, mTable grest.MigrationTable) error
RegisterSeeder(connName, seederKey string, seederHandler grest.SeederHandler) error
RunSeeder(tx *gorm.DB, connName string, seedTable grest.SeederTable) error
Connect(connName string, c grest.DBConfig) error
IsNotFoundError(err error) bool
}
func DB ¶
func DB() DBInterface
type FSInterface ¶
type FSInterface interface {
GetFileUrl(fileName string, path ...string) string
Upload(fileName string, src io.Reader, fileSize int64, opts ...FileUploadOption) (FileUploadInfo, error)
Delete(fileName string, opts ...FileDeleteOption) error
}
func FS ¶
func FS() FSInterface
type FileDeleteOption ¶
type FileDeleteOption struct {
minio.RemoveObjectOptions
}
type FileUploadInfo ¶
type FileUploadInfo struct {
minio.UploadInfo
}
type FileUploadOption ¶
type FileUploadOption struct {
minio.PutObjectOptions
}
type HttpClientInterface ¶
type HttpClientInterface interface {
Debug()
AddHeader(key, value string)
AddMultipartBody(body any) error
AddUrlEncodedBody(body any) error
AddJsonBody(body any) error
AddXmlBody(body any) error
SetTimeout(timeout time.Duration)
Send() (*http.Response, error)
BodyResponseStr() string
UnmarshalJson(v any) error
UnmarshalXml(v any) error
}
func HttpClient ¶
func HttpClient(method, url string) HttpClientInterface
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"`
}
type ModelInterface ¶
type ModelInterface interface {
grest.ModelInterface
}
type NullBool ¶
NullBool is nullable Bool, it embeds a grest.NullBool, so you can add your own method or override grest.NullBool method
type NullDate ¶
NullDate is nullable Date, it embeds a grest.NullDate, so you can add your own method or override grest.NullDate method
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 ¶
NullInt64 is nullable Int64, it embeds a grest.NullInt64, so you can add your own method or override grest.NullInt64 method
type 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
type NullText ¶
NullText is nullable Text, it embeds a grest.NullText, so you can add your own method or override grest.NullText method
type NullTime ¶
NullTime is nullable Time, it embeds a grest.NullTime, so you can add your own method or override grest.NullTime method
type NullUUID ¶
NullUUID is nullable UUID, it embeds a grest.NullUUID, so you can add your own method or override grest.NullUUID method
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 ServerInterface ¶
type ServerInterface interface {
AddRoute(path, method string, handler fiber.Handler, operation OpenAPIOperationInterface)
AddStaticRoute(path string, fsConfig filesystem.Config)
AddOpenAPIDoc(path string, f embed.FS)
AddMiddleware(handler fiber.Handler)
Start() error
Test(req *http.Request, msTimeout ...int) (resp *http.Response, err error)
}
func Server ¶
func Server() ServerInterface
type Setting ¶
type Setting struct {
Key string `gorm:"column:key;primaryKey"`
Value string `gorm:"column:value"`
}
func (Setting) MigrationKey ¶
func (Setting) ValueField ¶
type TelegramInterface ¶
type TelegramInterface interface {
AddMessage(text string)
AddAttachment(file *multipart.FileHeader)
Send() error
}
func Telegram ¶
func Telegram(message ...string) TelegramInterface
type TranslatorInterface ¶
func Translator ¶
func Translator() TranslatorInterface