Documentation ¶
Index ¶
- Constants
- Variables
- func Find(db *gorm.DB, model ModelInterface, query url.Values) ([]map[string]any, error)
- func Fmt(s string, attribute ...uint8) string
- func FormatFile(paths ...string)
- func LoadEnv(key string, value any)
- func NewMockDB() (*gorm.DB, sqlmock.Sqlmock, error)
- func StartupMessage(addr string)
- type Cache
- func (c *Cache) Clear() error
- func (c *Cache) Configure() error
- func (c *Cache) Delete(key string) error
- func (c *Cache) DeleteWithPrefix(prefix string) error
- func (c *Cache) Get(key string, val any) error
- func (c *Cache) Invalidate(prefix string, keys ...string)
- func (c *Cache) Set(key string, val any, e ...time.Duration) error
- type Crypto
- func (*Crypto) CompareHash(hashed, text string) error
- func (c *Crypto) Decrypt(text string) (string, error)
- func (c *Crypto) Encrypt(text string) (string, error)
- func (c *Crypto) GenerateKey() ([]byte, error)
- func (*Crypto) NewHash(text string, cost ...int) (string, error)
- func (c *Crypto) NewJWT(claims any) (string, error)
- func (*Crypto) PKCS5Padding(ciphertext []byte, blockSize int) []byte
- func (*Crypto) PKCS5Unpadding(encrypt []byte) ([]byte, error)
- func (c *Crypto) ParseAndVerifyJWT(token string, claims any) error
- type DB
- func (db *DB) Close()
- func (db *DB) CloseConn(connName string) error
- func (db *DB) Conn(connName string) (*gorm.DB, error)
- func (db *DB) MigrateTable(tx *gorm.DB, connName string, mTable MigrationTable) error
- func (db *DB) RegisterConn(connName string, conn *gorm.DB)
- func (db *DB) RegisterSeeder(connName, seederKey string, seederHandler any) error
- func (db *DB) RegisterTable(connName string, t Table) error
- func (db *DB) RunSeeder(tx *gorm.DB, connName string, seederTable SeederTable) error
- type DBConfig
- type DBQuery
- func (q *DBQuery) Find(schema map[string]any, qry ...url.Values) ([]map[string]any, error)
- func (q *DBQuery) GetPageLimit(qry ...url.Values) (int, int)
- func (q DBQuery) NewUUIDSQL() string
- func (q *DBQuery) Prepare(db *gorm.DB, schema map[string]any, query url.Values) (*gorm.DB, error)
- func (q DBQuery) Quote(text string) string
- func (q DBQuery) QuoteJSON(column, jsonKey string) string
- func (q *DBQuery) SetGroup(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB
- func (q *DBQuery) SetJoin(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB
- func (q *DBQuery) SetOrder(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB
- func (q *DBQuery) SetPagination(db *gorm.DB, query url.Values) *gorm.DB
- func (q *DBQuery) SetSelect(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB
- func (q *DBQuery) SetTable(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB
- func (q *DBQuery) SetWhere(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB
- func (q *DBQuery) ToSQL(schema map[string]any, qry ...url.Values) string
- type Error
- func (e *Error) Body() map[string]any
- func (e *Error) Error() string
- func (e *Error) GetError(err any) *Error
- func (e *Error) New(code int, message string, detail ...any) *Error
- func (e *Error) OriginalMessage() string
- func (e *Error) StatusCode() int
- func (e *Error) Trace() []map[string]any
- func (e *Error) TraceSimple() map[string]string
- type FileFormatter
- func (ff FileFormatter) Format(fileName string)
- func (ff FileFormatter) FormattedTagString(tags []StructTag, maxTagLen map[string]int) string
- func (ff FileFormatter) ParseTag(fields []*ast.Field) (mapTag map[string][]StructTag, maxTagLen map[string]int)
- func (ff FileFormatter) RewriteTag(fields []*ast.Field, mapTag map[string][]StructTag, maxTagLen map[string]int)
- func (ff FileFormatter) TagValueWithDelimiter(str string, maxLen int) string
- type HttpClient
- func (c *HttpClient) AddHeader(key, value string)
- func (c *HttpClient) AddJsonBody(body any) error
- func (c *HttpClient) AddMultipartBody(body any) error
- func (c *HttpClient) AddUrlEncodedBody(body any) error
- func (c *HttpClient) AddXmlBody(body any) error
- func (c *HttpClient) BodyResponseStr() string
- func (c *HttpClient) Debug()
- func (c *HttpClient) Send() (*http.Response, error)
- func (c *HttpClient) SetClient(client *http.Client)
- func (c *HttpClient) SetLogger(logger LoggerInterface)
- func (c *HttpClient) SetTimeout(timeout time.Duration)
- func (c *HttpClient) UnmarshalJson(v any) error
- func (c *HttpClient) UnmarshalXml(v any) error
- type JSON
- func (j JSON) FillMap(data map[string]any, key string, val any) any
- func (j JSON) JoinKey(prefix, key string, sep JSONSeparator, isTop bool) string
- func (j JSON) Marshal() ([]byte, error)
- func (j JSON) MarshalIndent(indent string) ([]byte, error)
- func (j JSON) ToFlat(separator ...JSONSeparator) JSON
- func (j JSON) ToFlatMap(flatMap map[string]any, data any, sep JSONSeparator, isTop bool, ...)
- func (j JSON) ToStructured(separator ...JSONSeparator) JSON
- func (j JSON) ToStructuredMap(m map[string]any, sep JSONSeparator) map[string]any
- func (j JSON) Unmarshal(v any) error
- type JSONSeparator
- type LoggerInterface
- type MapSlice
- type MigrationTable
- type Model
- func (m *Model) AddArrayField(fieldKey string, fieldOpt map[string]any)
- func (m *Model) AddField(fieldKey string, fieldOpt map[string]any)
- func (m *Model) AddFilter(filter map[string]any)
- func (m *Model) AddGroup(fieldKey string, fieldName string)
- func (m *Model) AddRelation(joinType string, tableName any, tableAliasName string, ...)
- func (m *Model) AddSort(sort map[string]any)
- func (*Model) Bind(m ModelInterface, data []byte) error
- func (m *Model) GetArrayFieldOrder() []string
- func (m *Model) GetArrayFields() map[string]map[string]any
- func (m *Model) GetData() any
- func (m *Model) GetFieldOrder() []string
- func (m *Model) GetFields() map[string]map[string]any
- func (m *Model) GetFilters() []map[string]any
- func (m *Model) GetGroups() map[string]string
- func (m *Model) GetOpenAPISchema() map[string]any
- func (m *Model) GetRelationOrder() []string
- func (m *Model) GetRelations() map[string]map[string]any
- func (m *Model) GetSchema() map[string]any
- func (m *Model) GetSorts() []map[string]any
- func (m *Model) IsFlat() bool
- func (m *Model) OpenAPISchemaName() string
- func (m *Model) SetFields(p any)
- func (m *Model) SetOpenAPISchema(p any) map[string]any
- func (m *Model) SetSchema(model ModelInterface) map[string]any
- func (m *Model) TableAliasName() string
- func (m *Model) TableName() string
- func (m *Model) TableSchema() map[string]any
- func (m *Model) TableVersion() string
- type ModelInterface
- type NullBool
- func (n NullBool) IsZero() bool
- func (n NullBool) MarshalJSON() ([]byte, error)
- func (n NullBool) MarshalText() ([]byte, error)
- func (n *NullBool) Scan(value any) error
- func (n *NullBool) Set(val bool)
- func (n *NullBool) UnmarshalJSON(data []byte) error
- func (n *NullBool) UnmarshalText(text []byte) error
- func (n *NullBool) Val() bool
- func (n NullBool) Value() (driver.Value, error)
- type NullDate
- type NullDateTime
- type NullFloat64
- func (n NullFloat64) IsZero() bool
- func (n NullFloat64) MarshalJSON() ([]byte, error)
- func (n NullFloat64) MarshalText() ([]byte, error)
- func (n *NullFloat64) Set(val float64)
- func (n *NullFloat64) UnmarshalJSON(data []byte) error
- func (n *NullFloat64) UnmarshalText(text []byte) error
- func (n *NullFloat64) Val() float64
- type NullInt64
- func (n NullInt64) IsZero() bool
- func (n NullInt64) MarshalJSON() ([]byte, error)
- func (n NullInt64) MarshalText() ([]byte, error)
- func (n *NullInt64) Set(val int64)
- func (n *NullInt64) UnmarshalJSON(data []byte) error
- func (n *NullInt64) UnmarshalText(text []byte) error
- func (n *NullInt64) Val() int64
- type NullJSON
- func (NullJSON) GormDBDataType(db *gorm.DB, field *schema.Field) string
- func (NullJSON) GormDataType() string
- func (n NullJSON) IsZero() bool
- func (n NullJSON) MarshalJSON() ([]byte, error)
- func (n *NullJSON) Scan(value any) error
- func (n *NullJSON) Set(val any)
- func (n *NullJSON) UnmarshalJSON(data []byte) error
- func (n *NullJSON) Val() string
- func (n NullJSON) Value() (driver.Value, error)
- type NullString
- func (n NullString) IsZero() bool
- func (n NullString) MarshalJSON() ([]byte, error)
- func (n NullString) MarshalText() ([]byte, error)
- func (n *NullString) Set(val string)
- func (n *NullString) UnmarshalJSON(data []byte) error
- func (n *NullString) UnmarshalText(text []byte) error
- func (n *NullString) Val() string
- type NullText
- type NullTime
- func (NullTime) GormDBDataType(db *gorm.DB, field *schema.Field) string
- func (NullTime) GormDataType() string
- func (n NullTime) IsZero() bool
- func (t *NullTime) Scan(value any) error
- func (n *NullTime) Set(val string)
- func (n *NullTime) UnmarshalJSON(data []byte) error
- func (n *NullTime) Val() string
- type NullUUID
- type NullUnixTime
- func (NullUnixTime) GormDBDataType(db *gorm.DB, field *schema.Field) string
- func (NullUnixTime) GormDataType() string
- func (n NullUnixTime) MarshalJSON() ([]byte, error)
- func (n *NullUnixTime) Scan(value any) error
- func (n *NullUnixTime) UnmarshalJSON(data []byte) error
- func (n NullUnixTime) Value() (driver.Value, error)
- type OpenAPI
- func (o *OpenAPI) AddComponent(key string, val any)
- func (o *OpenAPI) AddPath(key, method string, operationObject any)
- func (o *OpenAPI) AddRoute(path, method string, op OpenAPIOperationInterface)
- func (o *OpenAPI) AddServer(server map[string]any)
- func (o *OpenAPI) AddTag(tag map[string]any)
- func (o *OpenAPI) AddWebhook(key string, val any)
- func (o *OpenAPI) Configure()
- func (o *OpenAPI) Generate(p ...string) error
- func (o *OpenAPI) SetVersion()
- type OpenAPIContact
- type OpenAPIExternalDoc
- type OpenAPIInfo
- type OpenAPILicense
- type OpenAPIOperation
- func (o *OpenAPIOperation) OpenAPIBody() map[string]any
- func (o *OpenAPIOperation) OpenAPICallbacks() map[string]any
- func (o *OpenAPIOperation) OpenAPICookieParam() []map[string]any
- func (o *OpenAPIOperation) OpenAPIDeprecated() bool
- func (o *OpenAPIOperation) OpenAPIDescription() string
- func (o *OpenAPIOperation) OpenAPIExternalDoc() (string, string)
- func (o *OpenAPIOperation) OpenAPIHeaderParam() []map[string]any
- func (o *OpenAPIOperation) OpenAPIOperationID() string
- func (o *OpenAPIOperation) OpenAPIPathParam() []map[string]any
- func (o *OpenAPIOperation) OpenAPIQueryParam() []map[string]any
- func (o *OpenAPIOperation) OpenAPIResponses() map[string]map[string]any
- func (o *OpenAPIOperation) OpenAPISecurity() []map[string][]string
- func (o *OpenAPIOperation) OpenAPIServer() []map[string]any
- func (o *OpenAPIOperation) OpenAPISummary() string
- func (o *OpenAPIOperation) OpenAPITags() []string
- type OpenAPIOperationInterface
- type OpenAPISchemaComponent
- type SeederTable
- type SettingTable
- type StandardDataType
- type String
- func (String) AddSlashes(str string) string
- func (s String) CamelCase(str string, startWithUpper ...bool) string
- func (s String) FirstAlphaNumericRuneIndex(sr []rune, start int) int
- func (s String) FirstAlphaRuneIndex(sr []rune, start int) int
- func (String) GetVars(str, before, after string) []string
- func (s String) IsAlphaNumericRune(r rune) bool
- func (String) IsLowerAlphaRune(r rune) bool
- func (String) IsNumericRune(r rune) bool
- func (String) IsUpperAlphaRune(r rune) bool
- func (s String) KebabCase(str string) string
- func (s String) PascalCase(str string) string
- func (s String) SnakeCase(str string) string
- func (s String) SpecialCase(str string, delimiter rune) string
- func (String) StripSlashes(str string) string
- func (s String) ToLowerAlphaRune(r rune) rune
- func (s String) ToUpperAlphaRune(r rune) rune
- type StructTag
- type Table
- type Telegram
- type Translator
- type Validator
- func (v *Validator) IsValid(val any, tag string) bool
- func (v *Validator) New()
- func (v *Validator) RegisterTranslator(lang string, lt locales.Translator, ...) error
- func (v *Validator) TranslateError(err error, lang string) error
- func (v *Validator) ValidateStruct(val any, lang string) error
- func (*Validator) ValidateTagNamer(fld reflect.StructField) string
- func (*Validator) ValidateValuer(field reflect.Value) any
Constants ¶
const ( FmtReset uint8 = iota FmtBold FmtFaint FmtItalic FmtUnderline FmtBlinkSlow FmtBlinkRapid FmtReverseVideo FmtConcealed FmtCrossedOut )
Base attributes
const ( FmtBlack uint8 = iota + 30 FmtRed FmtGreen FmtYellow FmtBlue FmtMagenta FmtCyan FmtWhite )
Foreground text colors
const ( FmtHiBlack uint8 = iota + 90 FmtHiRed FmtHiGreen FmtHiYellow FmtHiBlue FmtHiMagenta FmtHiCyan FmtHiWhite )
Foreground Hi-Intensity text colors
const ( FmtBgBlack uint8 = iota + 40 FmtBgRed FmtBgGreen FmtBgYellow FmtBgBlue FmtBgMagenta FmtBgCyan FmtBgWhite )
Background text colors
const ( FmtBgHiBlack uint8 = iota + 100 FmtBgHiRed FmtBgHiGreen FmtBgHiYellow FmtBgHiBlue FmtBgHiMagenta FmtBgHiCyan FmtBgHiWhite )
Background Hi-Intensity text colors
const LangHeader = "Accept-Language"
The Accept-Language request HTTP header indicates the natural language and locale that the client prefers.
See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language
const Version = "v0.0.1"
Version is the current version of the GREST.
Variables ¶
var ( CryptoKey = "wAGyTpFQX5uKV3JInABXXEdpgFkQLPTf" CryptoSalt = "0de0cda7d2dd4937a1c4f7ddc43c580f" CryptoInfo = "info" JWTKey = "f4cac8b77a8d4cb5881fac72388bb226" )
var ( // pagination query params setting // if QueryLimit not setted, QueryDefaultLimit will be applied // if QueryLimit setted to 0, only PaginationInfo will be executed (only run a counting query against the database). // if QueryLimit setted greater than QueryMaxLimit, QueryDefaultLimit will be applied, Set QueryDefaultLimit to 0 to allow unlimited QueryLimit. // if QueryDisablePagination setted to true, QueryMaxLimit will be ignored and PaginationInfo will not be executed QueryDefaultLimit = 10 // Sets the default number of items when $per_page is not set QueryMaxLimit = 100 // Sets the maximum allowed number of items per page (even if the QueryLimit query parameter is set higher) QueryLimit = "$per_page" // ex: /contacts?$per_page=20 => sql: select * from contacts limit 20 QueryOffset = "$offset" // ex: /contacts?$offset=20 => sql: select * from contacts offset 20 QueryPage = "$page" // ex: /contacts?$page=3&per_page=10 => sql: select * from contacts limit 10 offset 20 QueryDisablePagination = "$is_disable_pagination" // ex: /contacts?$is_disable_pagination=true => sql: select * from contacts // selection query params setting // it can be setted by multiple fields, separated by comma // ex: /contacts?$select=id,code,name => sql: select id, code, name from contacts QuerySelect = "$select" // filtering query params setting QueryOptEqual = "$eq" // ex: /contacts?gender.$eq=male => sql: select * from contacts where gender = 'male' => same with /contacts?gender=male QueryOptNotEqual = "$ne" // ex: /contacts?phone.$ne=null => sql: select * from contacts where phone is not null QueryOptGreaterThan = "$gt" // ex: /contacts?age.$gt=18 => sql: select * from contacts where age > 18 QueryOptGreaterThanOrEqual = "$gte" // ex: /contacts?age.$gte=21 => sql: select * from contacts where age >= 21 QueryOptLowerThan = "$lt" // ex: /contacts?age.$lt=17 => sql: select * from contacts where age < 17 QueryOptLowerThanOrEqual = "$lte" // ex: /contacts?age.$lte=15 => sql: select * from contacts where age <= 15 QueryOptLike = "$like" // ex: /contacts?name.$like=john% => sql: select * from contacts where name like 'john%' QueryOptNotLike = "$nlike" // ex: /contacts?name.$nlike=john% => sql: select * from contacts where name not like 'john%' QueryOptInsensitiveLike = "$ilike" // ex: /contacts?name.$ilike=john% => sql: select * from contacts where lower(name) like lower('john%') QueryOptInsensitiveNotLike = "$nilike" // ex: /contacts?name.$nilike=john% => sql: select * from contacts where lower(name) not like lower('john%') QueryOptIn = "$in" // ex: /contacts?age.$in=17,21,34 => sql: select * from contacts where age in (17,21,34) QueryOptNotIn = "$nin" // ex: /contacts?age.$nin=17,21,34 => sql: select * from contacts where age not in (17,21,34) // sorting query params setting // default is ascending // it can be setted by multiple fields, separated by comma // add prefix - to sort descending // add sufix :i to sort case insensitive // ex: /contacts?$sort=gender,-age,-name:i => sql: select * from contacts order by gender, age desc, lower(name) desc QuerySort = "$sort" // or query params setting // ex: /contacts?$or=gender:female|age.$lt:10&$or=is_salesman:true|is_employee:true => sql: select * from contacts where (gender = 'female' or age < 10) and (is_salesman = '1' or is_employee = '1') QueryOr = "$or" QueryOrDelimiter = "|" // search query params setting // ex: /contacts?$search=code,name:john => sql: select * from contacts where (lower(code) = lower('john') or lower(name) = lower('john')) QuerySearch = "$search" // field query params setting // useful for filter, select or sort using another field // ex: /products?qty_available=$field:qty_on_hand => sql: select * from products where qty_available = qty_on_hand // ex: /products?qty_on_order.$gt=$field:qty_available => sql: select * from products where qty_on_order > qty_available QueryField = "$field" // aggregation query params // ex: /products?$select=$count:id => sql: select count(id) as "count.id" from products // ex: /products?$select=$sum:sold => sql: select sum(sold) as "sum.sold" from products // ex: /products?$select=$min:sold => sql: select min(sold) as "min.sold" from products // ex: /products?$select=$max:sold => sql: select max(sold) as "max.sold" from products // ex: /products?$select=$avg:sold => sql: select avg(sold) as "avg.sold" from products QueryCount = "$count" QuerySum = "$sum" QueryMin = "$min" QueryMax = "$max" QueryAvg = "$avg" // grouping query params setting // ex: /products?$group=category.id => sql: select category_id from products group by category_id // ex: /products?$group=category.id&$select=category.id,$avg:sold => sql: select category_id, avg(sold) as "avg.sold" from products group by category_id // ex: /products?$group=category.id&$select=category.id,$sum:sold&$sum:sold.$gt=0 => sql: select category_id, sum(sold) as "sum.sold" from products group by category_id having sum(sold) > 0 // ex: /products?$group=category.id&$select=category.id,$sum:sold&$sort:-$sum:sold => sql: select category_id, sum(sold) as "sum.sold" from products group by category_id order by sum(sold) desc QueryGroup = "$group" // include query params setting // for First method, by default query for all array fields is executed // but for Find method, by default query for array fields (has many or many to many) is not executed for optimum performance // to execute array fields query on Find method, you can add using QueryInclude // it can be setted by multiple fields, separated by comma // if QueryInclude setted to all, query for all array fields is executed // ex: /contacts?$include=families,friends,phones => include array fields: families, friends, and phones // ex: /contacts?$include=all => include all array fields // ex: /contacts/{id} => same as /contacts?id={id}&$include=all QueryInclude = "$include" // exclude query params setting // for First method and Find method, by default query for all fields defined in struct is executed // except for fields that explicitly hide by db:"-,hide" struct tags // to exclude some fields from executed in query you can hide it using QueryExclude // it can be setted by multiple fields, separated by comma // ex: /contacts?$exclude=families,friends,phones => exclude fields: families, friends, and phones QueryExclude = "$exclude" QueryDbField = "$db_field" // QueryCast defines the delimiter used for casting data types in query parameters. // It allows specifying the desired data type for a field in the format "field:type". // ex: /contacts?created_at:date=2024-01-01 => sql: select * from contacts where CAST(created_at AS DATE) = 2024-01-01 // ex: /contacts?created_at:date.$gte=2024-01-01 => sql: select * from contacts where CAST(created_at AS DATE) >= 2024-01-01 // ex: /contacts?is_employee:boolean=true => sql: select * from contacts where CAST(is_employee AS BOOLEAN) = TRUE QueryCast = ":" )
GREST support a common way for pagination, selecting fields, filtering, sorting, searching and other using URL query params this is the default of query parameter setting, you can override this with your own preferences
var ( // DisableFmt defines if the output is colorized or not. DisableFmt = (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) // Output defines the standard output of the print functions. By default os.Stdout is used. FmtStdout = colorable.NewColorableStdout() )
Functions ¶
func Fmt ¶
Fmt format log with attribute
for example : log.Fmt("text", log.Bold, log.Red) output (text with bold red foreground) : \x1b[1;31mtext\x1b[0m
func FormatFile ¶
func FormatFile(paths ...string)
FormatFile formats struct tags in Go source files. It accepts a list of file paths to process.
func LoadEnv ¶
LoadEnv loads environment variable values into corresponding variables. It takes a 'key' as the environment variable name and a 'value' as a pointer to the variable where the environment variable's value will be assigned.
func StartupMessage ¶
func StartupMessage(addr string)
StartupMessage generates and prints the startup message for the server.
Types ¶
type Cache ¶
type Cache struct { Exp time.Duration Ctx context.Context RedisClient *redis.Client IsUseRedis bool // contains filtered or unexported fields }
Cache is a cache utility that manages caching using redis or in-memory data.
func (*Cache) Configure ¶
Configure initializes the Cache by setting up the Redis client and context.
func (*Cache) DeleteWithPrefix ¶
DeleteWithPrefix removes all cached values with keys matching the specified prefix.
func (*Cache) Get ¶
Get retrieves a cached value associated with a key and stores the result in the value pointed to by val.
func (*Cache) Invalidate ¶
Invalidate removes cached values with keys having the specified prefix and additional keys.
type Crypto ¶
Crypto is a crypto utility for managing cryptographic operations.
func (*Crypto) CompareHash ¶
CompareHash compares a hashed value with its plain text counterpart.
func (*Crypto) GenerateKey ¶
GenerateKey generates a cryptographic key using HKDF.
func (*Crypto) PKCS5Padding ¶
PKCS5Padding adds PKCS5-style padding to a block of bytes.
func (*Crypto) PKCS5Unpadding ¶
PKCS5Unpadding removes PKCS5-style padding from a block of bytes.
type DB ¶
type DB struct { Conns map[string]*gorm.DB Migrations map[string]map[string]Table Seeders map[string]map[string]any // contains filtered or unexported fields }
DB is a DB utility to manage database connections, migrations, and seeders.
func (*DB) MigrateTable ¶
MigrateTable performs migrations for a specific table.
func (*DB) RegisterConn ¶
RegisterConn registers a database connection.
func (*DB) RegisterSeeder ¶
RegisterSeeder registers a seeder for a specific connection.
func (*DB) RegisterTable ¶
RegisterTable registers a table for migration.
type DBConfig ¶
type DBConfig struct { Driver string Host string Port int User string Password string DbName string Protocol string Charset string TimeZone *time.Location // see https://pkg.go.dev/time#LoadLocation for details ReadTimeout time.Duration WriteTimeout time.Duration SslMode string OtherParams map[string]string }
DBConfig represents the configuration for a database connection.
func (*DBConfig) ClickhouseDSN ¶
ClickhouseDSN generates the ClickHouse-specific DSN.
Reference: https://github.com/ClickHouse/clickhouse-go#dsn
example:
tcp://localhost:9000?database=gorm&username=gorm&password=gorm&read_timeout=10&write_timeout=20
func (*DBConfig) FirebirdDSN ¶
FirebirdDSN generates the Firebird-specific DSN.
Reference: https://github.com/nakagami/firebirdsql#connection-string
example:
SYSDBA:masterkey@127.0.0.1:3050/path/to/db_file_or_alias?charset=utf8
func (*DBConfig) MySqlDSN ¶
MySqlDSN generates the MySQL-specific DSN.
Reference: https://github.com/go-sql-driver/mysql#dsn-data-source-name
example:
user:pass@tcp(127.0.0.1:3306)/dbname?parseTime=true&loc=Asia/Jakarta
func (*DBConfig) PostgreSqlDSN ¶
PostgreSqlDSN generates the PostgreSQL-specific DSN.
Reference: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
example:
host=localhost port=9920 user=postgres password=postgres dbname=postgres sslmode=disable TimeZone=Asia/Jakarta
func (*DBConfig) SqlServerDSN ¶
SqlServerDSN generates the SQL Server-specific DSN.
Reference: https://github.com/denisenkom/go-mssqldb#connection-parameters-and-dsn
example:
sqlserver://username:password@localhost:9930?database=gorm
type DBQuery ¶
type DBQuery struct { DB *gorm.DB Model ModelInterface Schema map[string]any Query url.Values Data []map[string]any Err error }
DBQuery DBQuery definition for querying with model & query params
func (*DBQuery) Find ¶
Find finds all records matching given conditions conds from schema and query params
func (*DBQuery) GetPageLimit ¶
GetPageLimit return desire page & limit from query params
func (DBQuery) QuoteJSON ¶
QuoteJSON returns quoted json extract SQL string for json column with json key
func (*DBQuery) SetPagination ¶
SetPagination specify limit & offset method when retrieve records
type Error ¶
Error is an implementation of the error interface with trace and other details.
func NewError ¶
NewError returns an error with the specified status code, message, and optional detail.
func (*Error) Body ¶
Body returns the error details in a structured format suitable for response bodies.
func (*Error) Error ¶
Error returns the error message, makes it compatible with the `error` interface.
func (*Error) OriginalMessage ¶
OriginalMessage return error message or error.detail.message if exists
func (*Error) StatusCode ¶
StatusCode returns the HTTP status code associated with the error.
func (*Error) Trace ¶
Trace returns a slice of maps containing trace information about the error's origin.
func (*Error) TraceSimple ¶
TraceSimple returns a simplified map of trace information for displaying error traces.
type FileFormatter ¶
type FileFormatter struct{}
FileFormatter provides methods to format struct tags in Go source files.
func (FileFormatter) Format ¶
func (ff FileFormatter) Format(fileName string)
Format reformats struct tags in a given file.
func (FileFormatter) FormattedTagString ¶
func (ff FileFormatter) FormattedTagString(tags []StructTag, maxTagLen map[string]int) string
FormattedTagString generates a properly formatted struct tag string.
func (FileFormatter) ParseTag ¶
func (ff FileFormatter) ParseTag(fields []*ast.Field) (mapTag map[string][]StructTag, maxTagLen map[string]int)
ParseTag extracts struct tags from fields and returns a map of tag data along with max tag lengths.
func (FileFormatter) RewriteTag ¶
func (ff FileFormatter) RewriteTag(fields []*ast.Field, mapTag map[string][]StructTag, maxTagLen map[string]int)
RewriteTag rewrites struct tags in the fields based on the provided mapTag and maxTagLen data.
func (FileFormatter) TagValueWithDelimiter ¶
func (ff FileFormatter) TagValueWithDelimiter(str string, maxLen int) string
TagValueWithDelimiter formats the tag value with the appropriate delimiter and padding.
type HttpClient ¶
type HttpClient struct { IsDebug bool Logger LoggerInterface Client *http.Client Method string Url string Header http.Header Body io.Reader BodyRequest []byte BodyResponse []byte }
HttpClient is a utility to perform HTTP requests and manage various request parameters.
func NewHttpClient ¶
func NewHttpClient(method, url string) *HttpClient
NewHttpClient creates a new HttpClient instance with the provided HTTP method and URL.
func (*HttpClient) AddHeader ¶
func (c *HttpClient) AddHeader(key, value string)
AddHeader adds a new header to the request.
func (*HttpClient) AddJsonBody ¶
func (c *HttpClient) AddJsonBody(body any) error
AddJsonBody adds a JSON request body.
func (*HttpClient) AddMultipartBody ¶
func (c *HttpClient) AddMultipartBody(body any) error
AddMultipartBody adds a multipart/form-data request body.
func (*HttpClient) AddUrlEncodedBody ¶
func (c *HttpClient) AddUrlEncodedBody(body any) error
AddUrlEncodedBody adds an application/x-www-form-urlencoded request body.
func (*HttpClient) AddXmlBody ¶
func (c *HttpClient) AddXmlBody(body any) error
AddXmlBody adds an XML request body.
func (*HttpClient) BodyResponseStr ¶
func (c *HttpClient) BodyResponseStr() string
BodyResponseStr returns the response body as a string.
func (*HttpClient) Debug ¶
func (c *HttpClient) Debug()
Debug enables debug mode for the HttpClient, printing request and response details.
func (*HttpClient) Send ¶
func (c *HttpClient) Send() (*http.Response, error)
Send sends the HTTP request and returns the HTTP response.
func (*HttpClient) SetClient ¶
func (c *HttpClient) SetClient(client *http.Client)
SetClient set your own http client instead of http.DefaultClient
func (*HttpClient) SetLogger ¶
func (c *HttpClient) SetLogger(logger LoggerInterface)
SetLogger set logger
func (*HttpClient) SetTimeout ¶
func (c *HttpClient) SetTimeout(timeout time.Duration)
SetTimeout sets the timeout duration for the HTTP request.
func (*HttpClient) UnmarshalJson ¶
func (c *HttpClient) UnmarshalJson(v any) error
UnmarshalJson unmarshals the JSON response body into the provided target.
func (*HttpClient) UnmarshalXml ¶
func (c *HttpClient) UnmarshalXml(v any) error
UnmarshalXml unmarshals the XML response body into the provided target.
type JSON ¶
JSON is a struct that handles JSON data manipulation.
func (JSON) JoinKey ¶
func (j JSON) JoinKey(prefix, key string, sep JSONSeparator, isTop bool) string
JoinKey joins JSON keys using a separator to create a new key.
func (JSON) MarshalIndent ¶
MarshalIndent converts JSON data to an indented JSON byte slice.
func (JSON) ToFlat ¶
func (j JSON) ToFlat(separator ...JSONSeparator) JSON
ToFlat converts nested JSON structures to flattened form using a separator.
func (JSON) ToFlatMap ¶
func (j JSON) ToFlatMap(flatMap map[string]any, data any, sep JSONSeparator, isTop bool, pref ...string)
ToFlatMap recursively flattens a nested JSON map structure.
func (JSON) ToStructured ¶
func (j JSON) ToStructured(separator ...JSONSeparator) JSON
ToStructured converts JSON data to a structured form using a separator.
func (JSON) ToStructuredMap ¶
ToStructuredMap converts nested JSON data to a structured map using a separator.
type JSONSeparator ¶
JSONSeparator defines separators for flattening JSON keys.
type LoggerInterface ¶
type MigrationTable ¶
type MigrationTable interface { SettingTable MigrationKey() string }
MigrationTable is an interface for migration-related tables.
type Model ¶
type Model struct { // described in the following pattern : map[fieldKey]map[optKey]optValue // fieldKey: the field shown on json // optKey, same as model struct tag + the following key : // - dataType // optValue, same as model struct tag value Fields map[string]map[string]any `json:"-" gorm:"-"` FieldOrder []string `json:"-" gorm:"-"` // hold sql group by field data Groups map[string]string `json:"-" gorm:"-"` // hold array fields schema and filter (based on relation) : // ?arrayFields.0.field.id={field_id} > where exists (select 1 from array_table at where at.parent_id = parent.id and field_id = {field_id}) // ?arrayFields.*.field.id={field_id} > same as above but the array fields response also filtered ArrayFields map[string]map[string]any `json:"-" gorm:"-"` ArrayFieldOrder []string `json:"-" gorm:"-"` // described in the following pattern : map[fieldKey]map[optKey]optValue // fieldKey: same as "tableAliasName" on "optKey" // optKey : // - type : sql join type (inner, left, etc) // - tableName : table name to join // - tableSchema : schema for dynamic "join sub query" based on client's query params // - tableAliasName : table alias name // - conditions : []map[string]any same as "Filters" Relations map[string]map[string]any `json:"-" gorm:"-"` RelationOrder []string `json:"-" gorm:"-"` // described in the following pattern : []map[optKey]optValue // optKey : // - column1 : column in the db to be filtered // - column1jsonKey : dot notation paths of json field in column1 // - operator : sql operator (=, !=, >, >=, <, <=, like, not like, in, not in, etc) // - column2 : another column in the db (to compare values between columns in the db) // - column2jsonKey : dot notation paths of json field in column2 // - value : desired value to be filtered Filters []map[string]any `json:"-" gorm:"-"` // described in the following pattern : []map[optKey]optValue // optKey : // - column : column in the db to be filtered // - jsonKey : dot notation paths of json field in column // - direction : sql order direction (asc, desc) // - isCaseInsensitive : if true, the sort will case insensitive // - isRequired : if true, the sort will not be overridden by the client's own Sorts []map[string]any `json:"-" gorm:"-"` }
model struct tag :
json :
- dot notation field to be parsed to multi-dimensional json object
- also used for alias field when query to db
db :
- field to query to db
- add ",group" to group the field
- add ",hide" to hide the field on api response
gorm :
- field option for main table of the struct
- the details can be found at : https://gorm.io/docs/models.html#Fields-Tags
- if the field is not field of main table of the struct in the database, gorm must be setted to "-"
validate :
- validation tag to validate the data
- "required" tag will be used as "required" on OpenAPI Specification
- "oneof" tag will be used as "enum" on OpenAPI Specification
- "max" tag will be used as "maximum" or "maxLength" on OpenAPI Specification based on value type
- "min" tag will be used as "minimum" or "minLength" on OpenAPI Specification based on value type
- the details can be found at : https://pkg.go.dev/github.com/go-playground/validator/v10
title :
- used as "title" on OpenAPI Specification
note :
- used as "description" on OpenAPI Specification
default :
- used for the default value when insert to db
- used as "default" on OpenAPI Specification
example :
- used as "example" on OpenAPI Specification
func (*Model) AddArrayField ¶
AddArrayField adds an array field to the model if it doesn't exist.
func (*Model) AddRelation ¶
func (m *Model) AddRelation(joinType string, tableName any, tableAliasName string, conditions []map[string]any)
AddRelation adds a relation to the model.
- joinType : sql join type (inner, left, etc)
- tableName : column in the db (or raw subquery) to be joined or model schema (to auto generate sub query filtered based on client's filter)
- tableAliasName : table alias name on sql join, also used as relation key
- conditions : []map[string]any same as "Filters"
func (*Model) Bind ¶
func (*Model) Bind(m ModelInterface, data []byte) error
Bind binds JSON data to the model.
func (*Model) GetArrayFieldOrder ¶
GetArrayFieldOrder returns the order of array fields.
func (*Model) GetArrayFields ¶
GetArrayFields returns the array fields of the model.
func (*Model) GetFieldOrder ¶
GetFieldOrder returns the order of model fields.
func (*Model) GetFields ¶
GetFields returns the model fields.
Use SetFields to automatically setted by struct tag using SetFields, but you can add or override this. expected key :
- column : column to filter, based on field in the db (or raw query)
- as : column to filter, based on field in the db (or raw query)
- column2 : another column to filter, based on field in the db (or raw query), used to compare 2 column
- operator : operator to compare, if not set the default is "="
- value : value to compare
example :
func (m *Model) GetFields() map[string]map[string]any { m.SetFields(m) m.AddField(map[string]any{"column": "lower(p.name)", "as": "name_lower", "type": NullString}) }
func (*Model) GetFilters ¶
GetFilters returns the model filters. expected key :
- column1 : column (or raw query) in the db to be filtered
- column1jsonKey : dot notation paths of json field in column1
- operator : sql operator (=, !=, >, >=, <, <=, like, not like, in, not in, etc)
- column2 : another column (or raw query) in the db (to compare values between columns in the db)
- column2jsonKey : dot notation paths of json field in column2
- value : desired value to be filtered
example :
func (m *Model) GetFilters() []map[string]any { m.AddFilter(map[string]any{"column1": "p.deleted_at", "operator": "=", "value": nil}) return m.Filters }
func (*Model) GetOpenAPISchema ¶
SetOpenAPISchema sets the OpenAPI schema for the model.
func (*Model) GetRelationOrder ¶
GetRelationOrder returns the order of relations.
func (*Model) GetRelations ¶
GetRelations returns the model relations., expected key :
- type : sql join type (inner, left, etc)
- tableName :
- tableAliasName
- conditions : []map[string]any same as "Filters"
example :
func (m *Model) GetRelations() map[string]map[string]any { m.AddRelation("left", "product_categories", "pc", []map[string]any{{"column1": "pc.id", "operator": "=", "column2": "p.category_id"}}) return m.Relations }
func (*Model) GetSorts ¶
GetSorts returns the model sort orders. expected key :
- column : column in the db to be filtered
- jsonKey : dot notation paths of json field in column
- direction : sql order direction (asc, desc)
- isCaseInsensitive : if true, the sort will case insensitive
- isRequired : if true, the sort will not be overridden by the client's own
example :
func (m *Model) GetSorts() []map[string]any { m.AddSort(map[string]any{"column": "p.created_at", "direction": "desc"}) return m.Sorts }
func (*Model) OpenAPISchemaName ¶
OpenAPISchemaName returns the OpenAPI schema name.
func (*Model) SetOpenAPISchema ¶
SetOpenAPISchema generates the OpenAPI schema for the model based on its fields. It returns a map representing the OpenAPI schema for the model.
func (*Model) SetSchema ¶
func (m *Model) SetSchema(model ModelInterface) map[string]any
SetSchema sets the schema for the model.
func (*Model) TableAliasName ¶
TableAliasName returns the table alias name.
func (*Model) TableSchema ¶
TableSchema returns the table schema for dynamic "join sub query" based on client's query params.
example "from sub query" :
SELECT "u"."id" "user.id", "u"."name" "user.name", "ur"."total_review" "total_review" FROM (SELECT "user_id" "user_id", COUNT("user_id") "total_review" FROM "user_reviews" WHERE "rate" >= 4 GROUP BY "user_id" ) as "ur" JOIN "users" "u" on "u"."id" = "ur"."user_id"
for example :
func (m *Model) TableSchema() map[string]any { ur := &UserReviewTotal{} return ur.GetSchema() }
func (*Model) TableVersion ¶
table version, used for migration flag, change the value every time there is a change in the table structure
type ModelInterface ¶
type ModelInterface interface { TableVersion() string TableName() string TableSchema() map[string]any TableAliasName() string SetFields(any) AddField(fieldKey string, fieldOpt map[string]any) GetFields() map[string]map[string]any GetFieldOrder() []string AddArrayField(fieldKey string, fieldOpt map[string]any) GetArrayFields() map[string]map[string]any GetArrayFieldOrder() []string AddGroup(fieldKey string, fieldName string) GetGroups() map[string]string AddRelation(joinType string, tableName any, tableAliasName string, conditions []map[string]any) GetRelationOrder() []string GetRelations() map[string]map[string]any AddFilter(filter map[string]any) GetFilters() []map[string]any AddSort(sort map[string]any) GetSorts() []map[string]any SetSchema(ModelInterface) map[string]any GetSchema() map[string]any OpenAPISchemaName() string SetOpenAPISchema(any) map[string]any GetOpenAPISchema() map[string]any IsFlat() bool }
ModelInterface defines the methods that a model must implement.
type NullBool ¶
NullBool is a nullable bool.
- It will marshal to null if null, not false.
- It will unmarshal to true if input value is true, "true", "True", "TRUE", "t", "T", 1, or "1"
- It will unmarshal to false if input value is false, "false", "False", "FALSE", "f", "F", 0, or "0"
- Other input value will be considered null, not false and not error.
- It supports SQL and JSON serialization.
func (NullBool) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
- It will encode null if this Bool is null, not false.
func (NullBool) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
- It will encode blank if this NullBool is null, not false.
func (*NullBool) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
- It will unmarshal to true if input value is true, "true", "True", "TRUE", "t", "T", 1, or "1"
- It will unmarshal to false if input value is false, "false", "False", "FALSE", "f", "F", 0, or "0"
- Other input value will be considered null, not false and not error.
func (*NullBool) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
- It will unmarshal to true if input value is true, "true", "True", "TRUE", "t", "T", 1, or "1"
- It will unmarshal to false if input value is false, "false", "False", "FALSE", "f", "F", 0, or "0"
- Other input value will be considered null, not false.
type NullDate ¶
type NullDate struct {
NullDateTime
}
NullDate is a nullable date.
- It supports SQL and JSON serialization.
func (NullDate) GormDBDataType ¶
GormDBDataType returns gorm DB data type based on the current using database.
func (NullDate) GormDataType ¶
GormDataType returns gorm common data type. This type is used for the field's column type.
func (NullDate) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
- It will encode null if this NullDate is null.
func (*NullDate) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
- It supports a string that can be parsed to a time.Time.
- Other input value will be considered null, not error.
type NullDateTime ¶
NullDateTime is a nullable time.Time.
- It supports SQL and JSON serialization.
func (NullDateTime) IsZero ¶
func (n NullDateTime) IsZero() bool
IsZero returns true for zero time, for omitempty support
func (NullDateTime) MarshalJSON ¶
func (n NullDateTime) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
- It will encode null if this NullDateTime is null.
func (*NullDateTime) Set ¶
func (n *NullDateTime) Set(val ...time.Time)
Set sets the value for a NullDateTime.
func (*NullDateTime) UnmarshalJSON ¶
func (n *NullDateTime) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler.
- It supports a string that can be parsed to a time.Time.
- Other input value will be considered null, not error.
func (*NullDateTime) Val ¶
func (n *NullDateTime) Val() time.Time
Val returns the value of a NullDateTime.
type NullFloat64 ¶
type NullFloat64 struct {
sql.NullFloat64
}
NullFloat64 is a nullable float64.
- It supports number and a string that can be converted to a number.
- Other input value will be considered null, not 0 and not error.
- It supports SQL and JSON serialization.
func (NullFloat64) IsZero ¶
func (n NullFloat64) IsZero() bool
IsZero returns true for invalid float64, for omitempty support
func (NullFloat64) MarshalJSON ¶
func (n NullFloat64) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
- It will encode null if this NullFloat64 is null.
func (NullFloat64) MarshalText ¶
func (n NullFloat64) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler.
- It will encode a blank string if this NullFloat64 is null.
func (*NullFloat64) Set ¶
func (n *NullFloat64) Set(val float64)
Set sets the value for a NullFloat64.
func (*NullFloat64) UnmarshalJSON ¶
func (n *NullFloat64) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler.
- It supports number and a string that can be converted to a number.
- Other input value will be considered null, not 0 and not error.
func (*NullFloat64) UnmarshalText ¶
func (n *NullFloat64) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler.
- It supports number and a string that can be converted to a number.
- Other input value will be considered null, not 0 and not error.
func (*NullFloat64) Val ¶
func (n *NullFloat64) Val() float64
Val returns the value of a NullFloat64.
type NullInt64 ¶
NullInt64 is a nullable int64.
- It supports integer number and a string that can be converted to a integer number.
- Other input value will be considered null, not 0 and not error.
- It supports SQL and JSON serialization.
func (NullInt64) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
- It will encode null if this NullInt64 is null.
func (NullInt64) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
- It will encode a blank string if this NullInt64 is null.
func (*NullInt64) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
- It supports integer number and a string that can be converted to a integer number.
- Other input value will be considered null, not 0 and not error.
func (*NullInt64) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
- It supports integer number and a string that can be converted to a integer number.
- Other input value will be considered null, not 0 and not error.
type NullJSON ¶
NullJSON represents a nullable JSON value.
- It supports SQL and JSON serialization.
func (NullJSON) GormDBDataType ¶
GormDBDataType returns gorm DB data type based on the current using database.
func (NullJSON) GormDataType ¶
GormDataType returns gorm common data type. This type is used for the field's column type.
func (NullJSON) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*NullJSON) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
type NullString ¶
type NullString struct {
sql.NullString
}
NullString is a nullable string.
- It supports SQL and JSON serialization.
func (NullString) IsZero ¶
func (n NullString) IsZero() bool
IsZero returns true for invalid string, for omitempty support
func (NullString) MarshalJSON ¶
func (n NullString) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
- It will encode null if this NullString is null.
func (NullString) MarshalText ¶
func (n NullString) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler.
- It will encode a blank string if this NullString is null.
func (*NullString) UnmarshalJSON ¶
func (n *NullString) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler.
func (*NullString) UnmarshalText ¶
func (n *NullString) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler.
type NullText ¶
type NullText struct {
NullString
}
NullText represents a nullable text value.
func (NullText) GormDBDataType ¶
GormDBDataType returns gorm DB data type based on the current using database.
func (NullText) GormDataType ¶
GormDataType returns gorm common data type. This type is used for the field's column type.
type NullTime ¶
type NullTime struct {
NullString
}
NullTime is a nullable time.
- It supports SQL and JSON serialization.
func (NullTime) GormDBDataType ¶
GormDBDataType returns gorm DB data type based on the current using database.
func (NullTime) GormDataType ¶
GormDataType returns gorm common data type. This type is used for the field's column type.
func (*NullTime) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
- It supports a string that can be parsed to a time.Time.
- Other input value will be considered null, not error.
type NullUUID ¶
type NullUUID struct {
NullString
}
NullUUID represents a nullable UUID value.
func (NullUUID) GormDBDataType ¶
GormDBDataType returns gorm DB data type based on the current using database.
func (NullUUID) GormDataType ¶
GormDataType returns gorm common data type. This type is used for the field's column type.
type NullUnixTime ¶
type NullUnixTime struct {
NullDateTime
}
NullUnixTime is a nullable date.
- It supports SQL and JSON serialization.
func (NullUnixTime) GormDBDataType ¶
GormDBDataType returns gorm DB data type based on the current using database.
func (NullUnixTime) GormDataType ¶
func (NullUnixTime) GormDataType() string
GormDataType returns gorm common data type. This type is used for the field's column type.
func (NullUnixTime) MarshalJSON ¶
func (n NullUnixTime) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
- It will encode null if this NullUnixTime is null.
func (*NullUnixTime) Scan ¶
func (n *NullUnixTime) Scan(value any) error
Scan implements sql.Scanner interface and scans value into Date
func (*NullUnixTime) UnmarshalJSON ¶
func (n *NullUnixTime) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler.
- It supports a string that can be parsed to a time.Time.
- Other input value will be considered null, not error.
type OpenAPI ¶
type OpenAPI struct { OpenAPI string `json:"openapi,omitempty"` Info OpenAPIInfo `json:"info,omitempty"` JsonSchemaDialect string `json:"jsonSchemaDialect,omitempty"` Servers []map[string]any `json:"servers,omitempty"` Paths map[string]MapSlice `json:"paths,omitempty"` Webhooks map[string]any `json:"webhooks,omitempty"` Components map[string]any `json:"components,omitempty"` Security []map[string]any `json:"security,omitempty"` Tags []map[string]any `json:"tags,omitempty"` ExternalDocs OpenAPIExternalDoc `json:"externalDocs,omitempty"` }
OpenAPI represents the OpenAPI specification structure. The full Latest OpenAPI Specification is available on https://spec.openapis.org/oas/latest.html
func (*OpenAPI) AddComponent ¶
AddComponent adds a component to the OpenAPI specification. The full latest specs is available on https://spec.openapis.org/oas/latest.html#components-object
func (*OpenAPI) AddRoute ¶
func (o *OpenAPI) AddRoute(path, method string, op OpenAPIOperationInterface)
AddRoute generates and adds an OpenAPI operation for a route.
func (*OpenAPI) AddServer ¶
AddServer adds a server to the OpenAPI specification. The full latest specs is available on https://spec.openapis.org/oas/latest.html#server-object
func (*OpenAPI) AddTag ¶
AddTag adds a tag to the OpenAPI specification. The full latest specs is available on https://spec.openapis.org/oas/latest.html#tag-object
func (*OpenAPI) AddWebhook ¶
AddWebhook adds a webhook to the OpenAPI specification.
func (*OpenAPI) Configure ¶
func (o *OpenAPI) Configure()
Configure is a placeholder method for adding OpenAPI documentation.
func (*OpenAPI) SetVersion ¶
func (o *OpenAPI) SetVersion()
SetVersion sets the OpenAPI version to "3.0.3".
type OpenAPIContact ¶
type OpenAPIContact struct { Name string `json:"name"` Email string `json:"email,omitempty"` Url string `json:"url,omitempty"` }
OpenAPIContact represents the contact information in the OpenAPI info section.
type OpenAPIExternalDoc ¶
type OpenAPIExternalDoc struct { Description string `json:"description,omitempty"` Url string `json:"url"` }
OpenAPIExternalDoc represents an external documentation link in the OpenAPI specification.
type OpenAPIInfo ¶
type OpenAPIInfo struct { Title string `json:"title"` Description string `json:"description,omitempty"` TermsOfService string `json:"termsOfService,omitempty"` Contact OpenAPIContact `json:"contact"` License OpenAPILicense `json:"license"` Version string `json:"version"` }
OpenAPIInfo represents the information section of the OpenAPI specification.
type OpenAPILicense ¶
OpenAPILicense represents the license information in the OpenAPI info section.
type OpenAPIOperation ¶
type OpenAPIOperation struct { ID string Tags []string Summary string Description string PathParams []map[string]any HeaderParams []map[string]any CookieParams []map[string]any QueryParams []map[string]any Body map[string]any Responses map[string]map[string]any Securities []map[string][]string Servers []map[string]any Callbacks map[string]any IsDeprecated bool ExternalDocUrl string ExternalDocDesc string }
OpenAPIOperation represents an OpenAPI operation object.
func (*OpenAPIOperation) OpenAPIBody ¶
func (o *OpenAPIOperation) OpenAPIBody() map[string]any
func (*OpenAPIOperation) OpenAPICallbacks ¶
func (o *OpenAPIOperation) OpenAPICallbacks() map[string]any
func (*OpenAPIOperation) OpenAPICookieParam ¶
func (o *OpenAPIOperation) OpenAPICookieParam() []map[string]any
func (*OpenAPIOperation) OpenAPIDeprecated ¶
func (o *OpenAPIOperation) OpenAPIDeprecated() bool
func (*OpenAPIOperation) OpenAPIDescription ¶
func (o *OpenAPIOperation) OpenAPIDescription() string
func (*OpenAPIOperation) OpenAPIExternalDoc ¶
func (o *OpenAPIOperation) OpenAPIExternalDoc() (string, string)
func (*OpenAPIOperation) OpenAPIHeaderParam ¶
func (o *OpenAPIOperation) OpenAPIHeaderParam() []map[string]any
func (*OpenAPIOperation) OpenAPIOperationID ¶
func (o *OpenAPIOperation) OpenAPIOperationID() string
func (*OpenAPIOperation) OpenAPIPathParam ¶
func (o *OpenAPIOperation) OpenAPIPathParam() []map[string]any
func (*OpenAPIOperation) OpenAPIQueryParam ¶
func (o *OpenAPIOperation) OpenAPIQueryParam() []map[string]any
func (*OpenAPIOperation) OpenAPIResponses ¶
func (o *OpenAPIOperation) OpenAPIResponses() map[string]map[string]any
func (*OpenAPIOperation) OpenAPISecurity ¶
func (o *OpenAPIOperation) OpenAPISecurity() []map[string][]string
func (*OpenAPIOperation) OpenAPIServer ¶
func (o *OpenAPIOperation) OpenAPIServer() []map[string]any
func (*OpenAPIOperation) OpenAPISummary ¶
func (o *OpenAPIOperation) OpenAPISummary() string
func (*OpenAPIOperation) OpenAPITags ¶
func (o *OpenAPIOperation) OpenAPITags() []string
type OpenAPIOperationInterface ¶
type OpenAPIOperationInterface interface { // The tags of specific endpoint. // for example : // func (Doc) OpenAPITags() []string { // return []string{"Data Store - Product"} // } OpenAPITags() []string // The summary of specific endpoint. // for example : // func (Doc) OpenAPISummary() string { // return "Create Product" // } OpenAPISummary() string // The description of specific endpoint. // for example : // func (Doc) OpenAPISummary() string { // return "Use this method to create contact" // } OpenAPIDescription() string // The path param of specific endpoint. // for example, for endpoint PUT /api/products/{ProductID} you can add the path param like this : // func (Doc) OpenAPIPathParam() []map[string]any { // return []map[string]any{ // { // "in": "path", // "name": "contactID", // "schema": map[string]any{ // "type": "string", // }, // }, // } // } // Full specs is available on https://spec.openapis.org/oas/latest.html#parameter-object OpenAPIPathParam() []map[string]any // The header param of specific endpoint. // for example : // func (Doc) OpenAPIHeaderParam() []map[string]any { // return []map[string]any{ // { // "in": "header", // "name": "Content-Language", // "schema": map[string]any{ // "type": "string", // }, // "examples": map[string]any{ // "English (US)": map[string]any{ // "value": "en-US", // }, // "Bahasa Indonesia": map[string]any{ // "value": "id-ID", // }, // }, // }, // } // } // Full specs is available on https://spec.openapis.org/oas/latest.html#parameter-object OpenAPIHeaderParam() []map[string]any // The cookie param of specific endpoint. // for example : // func (Doc) OpenAPICookieParam() []map[string]any { // return []map[string]any{ // { // "in": "header", // "name": "token", // "schema": map[string]any{ // "type": "string", // }, // }, // } // } // Full specs is available on https://spec.openapis.org/oas/latest.html#parameter-object OpenAPICookieParam() []map[string]any // The query param of specific endpoint. // for example : // func (Doc) OpenAPIQueryParam() []map[string]any { // return []map[string]any{ // { // "in": "query", // "name": "params", // "schema": map[string]any{ // "type": "object", // "additionalProperties": map[string]any{ // "type": "string", // }, // }, // "style": "form", // "explode": true, // }, // } // } // Full specs is available on https://spec.openapis.org/oas/latest.html#parameter-object OpenAPIQueryParam() []map[string]any // Body request of specific endpoint. // example : // func (Doc) OpenAPIBody() map[string]any { // return map[string]any{ // "application/json": &Model{}, // will auto create schema $ref: '#/components/schemas/Model' if not exists // "application/xml": &Model{}, // "application/x-www-form-urlencoded": &Model{}, // } // } OpenAPIBody() map[string]any // Response of specific endpoint. // example : // func (Doc) OpenAPIResponses() map[string]map[string]any { // return map[string]map[string]any{ // "200": { // "description": "Success", // "content": map[string]any{ // "application/json": &Model{}, // will auto create schema $ref: '#/components/schemas/Model' if not exists // "application/xml": &Model{}, // }, // }, // "401": { // "description": "Unauthorized", // "content": map[string]any{ // "application/json": &app.UnauthorizedModel, // will auto create schema $ref: '#/components/schemas/app.UnauthorizedModel' if not exists // "application/xml": &app.UnauthorizedModel, // }, // }, // } // } // Full specs is available on https://spec.openapis.org/oas/latest.html#response-object OpenAPIResponses() map[string]map[string]any // Security requirement object of specific endpoint. // example : // func (Doc) OpenAPISecurity() []map[string][]string { // return []map[string][]string{ // { // "my_app_auth": { // "products:get", // "products:create", // }, // }, // } // } // // Full specs is available on https://spec.openapis.org/oas/latest.html#security-requirement-object OpenAPISecurity() []map[string][]string OpenAPIServer() []map[string]any OpenAPIOperationID() string OpenAPICallbacks() map[string]any OpenAPIDeprecated() bool // Allows referencing an external resource for extended documentation of specific endpoint // example : // func (Doc) OpenAPIExternalDoc() (string, string) { // return "https://example.com", "Find more info here" // } OpenAPIExternalDoc() (string, string) }
OpenAPIOperationInterface defines the interface for completing the operation object of an endpoint in the OpenAPI document. Full specifications are available at: https://spec.openapis.org/oas/latest.html#operation-object
type OpenAPISchemaComponent ¶
type OpenAPISchemaComponent interface { OpenAPISchemaName() string GetOpenAPISchema() map[string]any }
OpenAPISchemaComponent defines the interface for components with OpenAPI schemas.
type SeederTable ¶
type SeederTable interface { SettingTable SeederKey() string }
SeederTable is an interface for seeder-related tables.
type SettingTable ¶
SettingTable is an interface for setting-related tables.
type StandardDataType ¶
type String ¶
type String struct{}
String represents utility functions for string manipulation.
func (String) AddSlashes ¶
AddSlashes adds slashes before characters that need to be escaped. These characters are:
- single quote (')
- double quote (")
- and backslash (\)
func (String) FirstAlphaNumericRuneIndex ¶
FirstAlphaNumericRuneIndex finds the index of the first alphanumeric rune.
func (String) FirstAlphaRuneIndex ¶
FirstAlphaRuneIndex finds the index of the first alphabetic rune.
func (String) GetVars ¶
GetVars extracts variables from a string using specified before and after delimiters.
func (String) IsAlphaNumericRune ¶
IsAlphaNumericRune checks if a rune is an alphanumeric character.
func (String) IsLowerAlphaRune ¶
IsLowerAlphaRune checks if a rune is a lowercase alphabetic character.
func (String) IsNumericRune ¶
IsNumericRune checks if a rune is a numeric character.
func (String) IsUpperAlphaRune ¶
IsUpperAlphaRune checks if a rune is an uppercase alphabetic character.
func (String) PascalCase ¶
PascalCase converts a string to PascalCase.
func (String) SpecialCase ¶
SpecialCase converts a string to snake_case, kebab-case, or other formats based on the delimiter.
func (String) StripSlashes ¶
StripSlashes un-quotes a quoted string.
func (String) ToLowerAlphaRune ¶
ToLowerAlphaRune converts an uppercase alphabetic rune to lowercase.
func (String) ToUpperAlphaRune ¶
ToUpperAlphaRune converts a lowercase alphabetic rune to uppercase.
type Table ¶
type Table interface {
TableName() string
}
Table is an interface for database table models.
type Telegram ¶
type Telegram struct { BaseURL string BotToken string ChatID string ParseMode string Text string Photo *multipart.FileHeader Audio *multipart.FileHeader Video *multipart.FileHeader Document *multipart.FileHeader ReplyMarkup any }
Telegram is an utility to send telegram message using the Telegram API.
func (*Telegram) AddAttachment ¶
func (t *Telegram) AddAttachment(file *multipart.FileHeader)
AddAttachment adds an attachment to the message based on the file type.
func (*Telegram) AddMessage ¶
AddMessage sets the text message to be sent.
type Translator ¶
type Translator struct {
// contains filtered or unexported fields
}
Translator handles translation of messages based on language keys.
func (*Translator) AddTranslation ¶
func (t *Translator) AddTranslation(lang string, messages map[string]string)
AddTranslation adds translation data for a specific language.
func (*Translator) GetTranslation ¶
func (t *Translator) GetTranslation(lang string) map[string]string
GetTranslation retrieves translation data for a specific language.
func (Translator) SupportedLanguage ¶
func (t Translator) SupportedLanguage(lang string) string
SupportedLanguage determines the most appropriate supported language based on client's preference.
type Validator ¶
type Validator struct { *validator.Validate I18n map[string]ut.Translator }
Validator struct wraps the validator.Validate and provides additional methods for validation.
func (*Validator) RegisterTranslator ¶
func (v *Validator) RegisterTranslator(lang string, lt locales.Translator, regFunc func(v *validator.Validate, trans ut.Translator) error) error
RegisterTranslator registers a translator for a specific language and associates it with the Validator instance.
func (*Validator) TranslateError ¶
TranslateError translates validation errors and creates an error instance with translated details.
func (*Validator) ValidateStruct ¶
ValidateStruct validates a struct and returns an error with translated validation messages.
func (*Validator) ValidateTagNamer ¶
func (*Validator) ValidateTagNamer(fld reflect.StructField) string
ValidateTagNamer returns the validation tag name for a struct field.