grest

package module
v0.0.0-...-bc7e1ab Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: MIT Imports: 45 Imported by: 45

README

GREST

An instant, full-featured, and scalable REST APIs framework with go. Designed to make rapid development easy with clean code and best performance.

It takes care of a lot of the complexities of developing REST APIs so you can focus on the business logic of your app. Build prototypes in minutes and production-ready apps in days. Seriously.

GREST gives you the structure to build service oriented apps from day one. When you eventually need to split your app into microservices it’s an easy transition.

Feature

  • Getting Started
    • Prerequisites
    • CLI
    • Directory Structure
    • Configuration
    • Testing
    • Deployment
  • Basic
    • Routing
    • Middleware
    • Request
    • Response
    • Model
    • Validation
    • Error Handling
    • Logging
  • Database
    • Connecting to Database
    • CRUD
    • Query Builder
    • Migration
    • Seed
    • Cache
  • Security
    • Authentication
    • Authorization
    • Encryption
    • Hashing
    • JWT
    • OAuth
  • Client
    • HTTP Client
    • gRPC Client
  • Notification
    • Mail
    • Telegram
    • Slack
  • More
    • OpenAPI Documentation
    • Frontend Integration
    • File Storage
    • Translation
    • Websocket
    • gRPC Server
    • Scheduling
    • Queue
    • Event

Getting Started

Coming Soon...

Inspired By

Originally, GREST inspired by the following frameworks, however we did it with a different approach, complementing its features, making it easier to use and more flexible with optimal performance and of course with Go ways.

  • Feathers — A framework for real-time applications and REST APIs.
  • LoopBack — A highly extensible Node.js and TypeScript framework for building APIs and microservices.
  • Laravel — The PHP Framework for Web Artisans.
  • Django — A high-level Python web framework that encourages rapid development and clean, pragmatic design.

Library

GREST is REST APIs framework with a "batteries-included" philosophy, it means that GREST comes with most of the libraries and tools required for common use cases, out of the box, so you can focus on the business logic of your application instead of choosing libraries and tools or creating your own. Thanks to the following libraries and tools that help GREST realize that philosophy :

  • Fiber — An Express-inspired web framework written in Go.
  • GORM — The fantastic ORM library for Golang.
  • go-redis — Redis client for Golang.
  • Package validator — Package validator implements value validations for structs and individual fields based on tags.
  • zerolog — Zero Allocation JSON Logger.
  • @stoplight/elements — Beautiful API documentation powered by OpenAPI and Markdown.
  • MinIO Go Client SDK — MinIO Go Client SDK for Amazon S3 Compatible Cloud Storage
  • etc

Contribute

You can help to deliver a better GREST by the following ways:

  • Reporting issues
  • Suggesting new features or enhancements
  • Improve/fix documentation
  • Sending a pull request The core team is monitoring for pull requests. We will review your pull request and either merge it, request changes to it, or close it with an explanation. Pull request should have:
    • Test case
    • Documentation
    • Example (If it makes sense)
  • You can also contribute by:
    • Add a GitHub Star to the project.
    • Tweet about the project on your Twitter.
    • Write a review or tutorial on your youtube channel or personal blog.

By contributing to GREST, you agree that your contributions will be licensed under its MIT license.

License

GREST officialy created, used, and maintained by Zahir Core Team. GREST is free and open-source software licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	FmtReset uint8 = iota
	FmtBold
	FmtFaint
	FmtItalic
	FmtUnderline
	FmtBlinkSlow
	FmtBlinkRapid
	FmtReverseVideo
	FmtConcealed
	FmtCrossedOut
)

Base attributes

View Source
const (
	FmtBlack uint8 = iota + 30
	FmtRed
	FmtGreen
	FmtYellow
	FmtBlue
	FmtMagenta
	FmtCyan
	FmtWhite
)

Foreground text colors

View Source
const (
	FmtHiBlack uint8 = iota + 90
	FmtHiRed
	FmtHiGreen
	FmtHiYellow
	FmtHiBlue
	FmtHiMagenta
	FmtHiCyan
	FmtHiWhite
)

Foreground Hi-Intensity text colors

View Source
const (
	FmtBgBlack uint8 = iota + 40
	FmtBgRed
	FmtBgGreen
	FmtBgYellow
	FmtBgBlue
	FmtBgMagenta
	FmtBgCyan
	FmtBgWhite
)

Background text colors

View Source
const (
	FmtBgHiBlack uint8 = iota + 100
	FmtBgHiRed
	FmtBgHiGreen
	FmtBgHiYellow
	FmtBgHiBlue
	FmtBgHiMagenta
	FmtBgHiCyan
	FmtBgHiWhite
)

Background Hi-Intensity text colors

View Source
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

View Source
const Version = "v0.0.1"

Version is the current version of the GREST.

Variables

View Source
var (
	CryptoKey  = "wAGyTpFQX5uKV3JInABXXEdpgFkQLPTf"
	CryptoSalt = "0de0cda7d2dd4937a1c4f7ddc43c580f"
	CryptoInfo = "info"
	JWTKey     = "f4cac8b77a8d4cb5881fac72388bb226"
)
View Source
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"
)

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

View Source
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 Find

func Find(db *gorm.DB, model ModelInterface, query url.Values) ([]map[string]any, error)

Find finds all records matching given conditions conds from model and query params

func Fmt

func Fmt(s string, attribute ...uint8) string

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

func LoadEnv(key string, value any)

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 NewMockDB

func NewMockDB() (*gorm.DB, sqlmock.Sqlmock, error)

NewMockDB creates a new mock database and returns the gorm.DB instance.

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) Clear

func (c *Cache) Clear() error

Clear removes all cached values from the cache.

func (*Cache) Configure

func (c *Cache) Configure() error

Configure initializes the Cache by setting up the Redis client and context.

func (*Cache) Delete

func (c *Cache) Delete(key string) error

Delete removes a cached value associated with a key.

func (*Cache) DeleteWithPrefix

func (c *Cache) DeleteWithPrefix(prefix string) error

DeleteWithPrefix removes all cached values with keys matching the specified prefix.

func (*Cache) Get

func (c *Cache) Get(key string, val any) error

Get retrieves a cached value associated with a key and stores the result in the value pointed to by val.

func (*Cache) Invalidate

func (c *Cache) Invalidate(prefix string, keys ...string)

Invalidate removes cached values with keys having the specified prefix and additional keys.

func (*Cache) Set

func (c *Cache) Set(key string, val any, e ...time.Duration) error

Set stores a value in the cache associated with a key and an optional expiration time.

type Crypto

type Crypto struct {
	Key    string
	Salt   string
	Info   string
	JWTKey string
}

Crypto is a crypto utility for managing cryptographic operations.

func NewCrypto

func NewCrypto(keys ...string) *Crypto

NewCrypto initializes a new Crypto instance with optional key values.

func (*Crypto) CompareHash

func (*Crypto) CompareHash(hashed, text string) error

CompareHash compares a hashed value with its plain text counterpart.

func (*Crypto) Decrypt

func (c *Crypto) Decrypt(text string) (string, error)

Decrypt decrypts an AES-encrypted text.

func (*Crypto) Encrypt

func (c *Crypto) Encrypt(text string) (string, error)

Encrypt encrypts a given text using AES in CBC mode.

func (*Crypto) GenerateKey

func (c *Crypto) GenerateKey() ([]byte, error)

GenerateKey generates a cryptographic key using HKDF.

func (*Crypto) NewHash

func (*Crypto) NewHash(text string, cost ...int) (string, error)

NewHash generates a new hash using bcrypt with an optional cost.

func (*Crypto) NewJWT

func (c *Crypto) NewJWT(claims any) (string, error)

NewJWT creates a new JSON Web Token.

func (*Crypto) PKCS5Padding

func (*Crypto) PKCS5Padding(ciphertext []byte, blockSize int) []byte

PKCS5Padding adds PKCS5-style padding to a block of bytes.

func (*Crypto) PKCS5Unpadding

func (*Crypto) PKCS5Unpadding(encrypt []byte) ([]byte, error)

PKCS5Unpadding removes PKCS5-style padding from a block of bytes.

func (*Crypto) ParseAndVerifyJWT

func (c *Crypto) ParseAndVerifyJWT(token string, claims any) error

ParseAndVerifyJWT parses and verifies a JSON Web Token.

type DB

type DB struct {
	Conns      map[string]*gorm.DB
	Migrations map[string]map[string]Table
	Seeders    map[string]map[string]any
}

DB is a DB utility to manage database connections, migrations, and seeders.

func (*DB) Close

func (db *DB) Close()

Close closes all registered database connections.

func (*DB) CloseConn

func (db *DB) CloseConn(connName string) error

CloseConn closes a registered database connection.

func (*DB) Conn

func (db *DB) Conn(connName string) (*gorm.DB, error)

Conn retrieves a registered database connection.

func (*DB) MigrateTable

func (db *DB) MigrateTable(tx *gorm.DB, connName string, mTable MigrationTable) error

MigrateTable performs migrations for a specific table.

func (*DB) RegisterConn

func (db *DB) RegisterConn(connName string, conn *gorm.DB)

RegisterConn registers a database connection.

func (*DB) RegisterSeeder

func (db *DB) RegisterSeeder(connName, seederKey string, seederHandler any) error

RegisterSeeder registers a seeder for a specific connection.

func (*DB) RegisterTable

func (db *DB) RegisterTable(connName string, t Table) error

RegisterTable registers a table for migration.

func (*DB) RunSeeder

func (db *DB) RunSeeder(tx *gorm.DB, connName string, seederTable SeederTable) error

RunSeeder runs seeders for a specific connection and seeder table.

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

func (d *DBConfig) ClickhouseDSN() string

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) DSN

func (d *DBConfig) DSN() string

DSN generates the Data Source Name (DSN) for the database connection.

func (*DBConfig) FirebirdDSN

func (d *DBConfig) FirebirdDSN() string

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

func (d *DBConfig) MySqlDSN() string

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

func (d *DBConfig) PostgreSqlDSN() string

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

func (d *DBConfig) SqlServerDSN() string

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

func (*DBConfig) SqliteDSN

func (d *DBConfig) SqliteDSN() string

SqliteDSN generates the SQLite-specific DSN.

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

func (q *DBQuery) Find(schema map[string]any, qry ...url.Values) ([]map[string]any, error)

Find finds all records matching given conditions conds from schema and query params

func (*DBQuery) GetPageLimit

func (q *DBQuery) GetPageLimit(qry ...url.Values) (int, int)

GetPageLimit return desire page & limit from query params

func (DBQuery) NewUUIDSQL

func (q DBQuery) NewUUIDSQL() string

NewUUIDSQL returns uuid SQL string

func (*DBQuery) Prepare

func (q *DBQuery) Prepare(db *gorm.DB, schema map[string]any, query url.Values) (*gorm.DB, error)

Prepare prepare gorm.DB for querying with schema & query params

func (DBQuery) Quote

func (q DBQuery) Quote(text string) string

Quote returns quoted SQL string

func (DBQuery) QuoteJSON

func (q DBQuery) QuoteJSON(column, jsonKey string) string

QuoteJSON returns quoted json extract SQL string for json column with json key

func (*DBQuery) SetGroup

func (q *DBQuery) SetGroup(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB

SetGroup specify the group method when querying

func (*DBQuery) SetJoin

func (q *DBQuery) SetJoin(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB

SetJoin specify the join method when querying

func (*DBQuery) SetOrder

func (q *DBQuery) SetOrder(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB

SetOrder specify order method when retrieve records

func (*DBQuery) SetPagination

func (q *DBQuery) SetPagination(db *gorm.DB, query url.Values) *gorm.DB

SetPagination specify limit & offset method when retrieve records

func (*DBQuery) SetSelect

func (q *DBQuery) SetSelect(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB

SetSelect specify fields that you want when querying

func (*DBQuery) SetTable

func (q *DBQuery) SetTable(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB

SetTable specify the table you would like to run db operations

func (*DBQuery) SetWhere

func (q *DBQuery) SetWhere(db *gorm.DB, schema map[string]any, query url.Values) *gorm.DB

SetWhere specify the where method when querying

func (*DBQuery) ToSQL

func (q *DBQuery) ToSQL(schema map[string]any, qry ...url.Values) string

ToSQL generate SQL string from schema and query params

type Error

type Error struct {
	Code    int
	Message string
	Detail  any
	PCs     []uintptr
}

Error is an implementation of the error interface with trace and other details.

func NewError

func NewError(statusCode int, message string, detail ...any) *Error

NewError returns an error with the specified status code, message, and optional detail.

func (*Error) Body

func (e *Error) Body() map[string]any

Body returns the error details in a structured format suitable for response bodies.

func (*Error) Error

func (e *Error) Error() string

Error returns the error message, makes it compatible with the `error` interface.

func (*Error) GetError

func (e *Error) GetError(err any) *Error

GetError return *Error from any type err

func (*Error) New

func (e *Error) New(code int, message string, detail ...any) *Error

New return new *Error

func (*Error) OriginalMessage

func (e *Error) OriginalMessage() string

OriginalMessage return error message or error.detail.message if exists

func (*Error) StatusCode

func (e *Error) StatusCode() int

StatusCode returns the HTTP status code associated with the error.

func (*Error) Trace

func (e *Error) Trace() []map[string]any

Trace returns a slice of maps containing trace information about the error's origin.

func (*Error) TraceSimple

func (e *Error) TraceSimple() map[string]string

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

type JSON struct {
	Data       any
	IsMerge    bool
	IsRootOnly bool
}

JSON is a struct that handles JSON data manipulation.

func NewJSON

func NewJSON(data any, isKeepOriginalData ...bool) JSON

NewJSON creates a new JSON instance with provided data and optional options.

func (JSON) FillMap

func (j JSON) FillMap(data map[string]any, key string, val any) any

FillMap fills a map with nested keys and values.

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) Marshal

func (j JSON) Marshal() ([]byte, error)

Marshal converts JSON data to a JSON byte slice.

func (JSON) MarshalIndent

func (j JSON) MarshalIndent(indent string) ([]byte, error)

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

func (j JSON) ToStructuredMap(m map[string]any, sep JSONSeparator) map[string]any

ToStructuredMap converts nested JSON data to a structured map using a separator.

func (JSON) Unmarshal

func (j JSON) Unmarshal(v any) error

Unmarshal decodes JSON data to a provided target structure.

type JSONSeparator

type JSONSeparator struct {
	Before string
	After  string
}

JSONSeparator defines separators for flattening JSON keys.

type LoggerInterface

type LoggerInterface interface {
	Debug(msg string, attrs ...any)
	Info(msg string, attrs ...any)
	Warn(msg string, attrs ...any)
	Error(msg string, attrs ...any)
}

type MapSlice

type MapSlice []map[string]any

MapSlice of map items.

func (MapSlice) MarshalJSON

func (ms MapSlice) MarshalJSON() ([]byte, error)

MarshalJSON for map slice.

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 :

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

func (m *Model) AddArrayField(fieldKey string, fieldOpt map[string]any)

AddArrayField adds an array field to the model if it doesn't exist.

func (*Model) AddField

func (m *Model) AddField(fieldKey string, fieldOpt map[string]any)

AddField adds a field to the model if it doesn't exist.

func (*Model) AddFilter

func (m *Model) AddFilter(filter map[string]any)

AddFilter adds a filter to the model.

func (*Model) AddGroup

func (m *Model) AddGroup(fieldKey string, fieldName string)

AddGroup adds a field to the specified group.

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) AddSort

func (m *Model) AddSort(sort map[string]any)

AddSort adds a sort order to the model.

func (*Model) Bind

func (*Model) Bind(m ModelInterface, data []byte) error

Bind binds JSON data to the model.

func (*Model) GetArrayFieldOrder

func (m *Model) GetArrayFieldOrder() []string

GetArrayFieldOrder returns the order of array fields.

func (*Model) GetArrayFields

func (m *Model) GetArrayFields() map[string]map[string]any

GetArrayFields returns the array fields of the model.

func (*Model) GetData

func (m *Model) GetData() any

GetData retrieves the data after querying the database.

func (*Model) GetFieldOrder

func (m *Model) GetFieldOrder() []string

GetFieldOrder returns the order of model fields.

func (*Model) GetFields

func (m *Model) GetFields() map[string]map[string]any

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

func (m *Model) GetFilters() []map[string]any

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) GetGroups

func (m *Model) GetGroups() map[string]string

GetGroups returns the field groups.

func (*Model) GetOpenAPISchema

func (m *Model) GetOpenAPISchema() map[string]any

SetOpenAPISchema sets the OpenAPI schema for the model.

func (*Model) GetRelationOrder

func (m *Model) GetRelationOrder() []string

GetRelationOrder returns the order of relations.

func (*Model) GetRelations

func (m *Model) GetRelations() map[string]map[string]any

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) GetSchema

func (m *Model) GetSchema() map[string]any

GetSchema returns the model schema.

func (*Model) GetSorts

func (m *Model) GetSorts() []map[string]any

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) IsFlat

func (m *Model) IsFlat() bool

IsFlat returns whether the model is flat or not.

func (*Model) OpenAPISchemaName

func (m *Model) OpenAPISchemaName() string

OpenAPISchemaName returns the OpenAPI schema name.

func (*Model) SetFields

func (m *Model) SetFields(p any)

SetFields sets the fields of the model based on struct tags.

func (*Model) SetOpenAPISchema

func (m *Model) SetOpenAPISchema(p any) map[string]any

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

func (m *Model) TableAliasName() string

TableAliasName returns the table alias name.

func (*Model) TableName

func (m *Model) TableName() string

TableName returns the name of the table associated with the model.

func (*Model) TableSchema

func (m *Model) TableSchema() map[string]any

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

func (m *Model) TableVersion() string

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

type NullBool struct {
	sql.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) IsZero

func (n NullBool) IsZero() bool

IsZero returns true for invalid bool, for omitempty support

func (NullBool) MarshalJSON

func (n NullBool) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

  • It will encode null if this Bool is null, not false.

func (NullBool) MarshalText

func (n NullBool) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

  • It will encode blank if this NullBool is null, not false.

func (*NullBool) Scan

func (n *NullBool) Scan(value any) error

Scan implements the Scanner interface.

func (*NullBool) Set

func (n *NullBool) Set(val bool)

Set sets the value for a NullBool.

func (*NullBool) UnmarshalJSON

func (n *NullBool) UnmarshalJSON(data []byte) error

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

func (n *NullBool) UnmarshalText(text []byte) error

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.

func (*NullBool) Val

func (n *NullBool) Val() bool

Val returns the value of a NullBool.

func (NullBool) Value

func (n NullBool) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type NullDate

type NullDate struct {
	NullDateTime
}

NullDate is a nullable date.

  • It supports SQL and JSON serialization.

func (NullDate) GormDBDataType

func (NullDate) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType returns gorm DB data type based on the current using database.

func (NullDate) GormDataType

func (NullDate) GormDataType() string

GormDataType returns gorm common data type. This type is used for the field's column type.

func (NullDate) MarshalJSON

func (n NullDate) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

  • It will encode null if this NullDate is null.

func (*NullDate) Scan

func (n *NullDate) Scan(value any) error

Scan implements sql.Scanner interface and scans value into Date

func (*NullDate) UnmarshalJSON

func (n *NullDate) 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 (NullDate) Value

func (n NullDate) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type NullDateTime

type NullDateTime struct {
	sql.NullTime
}

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

type NullInt64 struct {
	sql.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) IsZero

func (n NullInt64) IsZero() bool

IsZero returns true for invalid int64, for omitempty support

func (NullInt64) MarshalJSON

func (n NullInt64) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

  • It will encode null if this NullInt64 is null.

func (NullInt64) MarshalText

func (n NullInt64) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

  • It will encode a blank string if this NullInt64 is null.

func (*NullInt64) Set

func (n *NullInt64) Set(val int64)

Set sets the value for a NullInt64.

func (*NullInt64) UnmarshalJSON

func (n *NullInt64) UnmarshalJSON(data []byte) error

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

func (n *NullInt64) UnmarshalText(text []byte) error

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.

func (*NullInt64) Val

func (n *NullInt64) Val() int64

Val returns the value of a NullInt64.

type NullJSON

type NullJSON struct {
	String string `json:"-"`
	Valid  bool   `json:"-"`
	Data   any
}

NullJSON represents a nullable JSON value.

  • It supports SQL and JSON serialization.

func (NullJSON) GormDBDataType

func (NullJSON) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType returns gorm DB data type based on the current using database.

func (NullJSON) GormDataType

func (NullJSON) GormDataType() string

GormDataType returns gorm common data type. This type is used for the field's column type.

func (NullJSON) IsZero

func (n NullJSON) IsZero() bool

IsZero returns true for invalid string, for omitempty support

func (NullJSON) MarshalJSON

func (n NullJSON) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*NullJSON) Scan

func (n *NullJSON) Scan(value any) error

Scan implements the Scanner interface.

func (*NullJSON) Set

func (n *NullJSON) Set(val any)

Set sets the value for a NullJSON.

func (*NullJSON) UnmarshalJSON

func (n *NullJSON) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*NullJSON) Val

func (n *NullJSON) Val() string

Val returns the value of a NullJSON.

func (NullJSON) Value

func (n NullJSON) Value() (driver.Value, error)

Value implements the driver Valuer interface.

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) Set

func (n *NullString) Set(val string)

Set sets the value for a NullString.

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.

func (*NullString) Val

func (n *NullString) Val() string

Val returns the value of a NullString.

type NullText

type NullText struct {
	NullString
}

NullText represents a nullable text value.

func (NullText) GormDBDataType

func (NullText) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType returns gorm DB data type based on the current using database.

func (NullText) GormDataType

func (NullText) GormDataType() string

GormDataType returns gorm common data type. This type is used for the field's column type.

func (*NullText) Set

func (n *NullText) Set(val string)

Set sets the value for a NullText.

func (*NullText) Val

func (n *NullText) Val() string

Val returns the value of a NullText.

type NullTime

type NullTime struct {
	NullString
}

NullTime is a nullable time.

  • It supports SQL and JSON serialization.

func (NullTime) GormDBDataType

func (NullTime) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType returns gorm DB data type based on the current using database.

func (NullTime) GormDataType

func (NullTime) GormDataType() string

GormDataType returns gorm common data type. This type is used for the field's column type.

func (NullTime) IsZero

func (n NullTime) IsZero() bool

IsZero returns true for zero time, for omitempty support

func (*NullTime) Scan

func (t *NullTime) Scan(value any) error

Scan implements sql.Scanner interface and scans value into Time

func (*NullTime) Set

func (n *NullTime) Set(val string)

Set sets the value for a NullTime.

func (*NullTime) UnmarshalJSON

func (n *NullTime) 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 (*NullTime) Val

func (n *NullTime) Val() string

Val returns the value of a NullTime.

type NullUUID

type NullUUID struct {
	NullString
}

NullUUID represents a nullable UUID value.

func (NullUUID) GormDBDataType

func (NullUUID) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType returns gorm DB data type based on the current using database.

func (NullUUID) GormDataType

func (NullUUID) GormDataType() string

GormDataType returns gorm common data type. This type is used for the field's column type.

func (*NullUUID) Set

func (n *NullUUID) Set(val ...string)

Set sets the value for a NullUUID.

func (*NullUUID) Val

func (n *NullUUID) Val() string

Val returns the value of a NullUUID.

type NullUnixTime

type NullUnixTime struct {
	NullDateTime
}

NullUnixTime is a nullable date.

  • It supports SQL and JSON serialization.

func (NullUnixTime) GormDBDataType

func (NullUnixTime) GormDBDataType(db *gorm.DB, field *schema.Field) string

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.

func (NullUnixTime) Value

func (n NullUnixTime) Value() (driver.Value, error)

Value implements the driver Valuer interface.

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

func (o *OpenAPI) AddComponent(key string, val any)

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) AddPath

func (o *OpenAPI) AddPath(key, method string, operationObject any)

AddPath adds a path to the OpenAPI specification.

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

func (o *OpenAPI) AddServer(server map[string]any)

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

func (o *OpenAPI) AddTag(tag map[string]any)

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

func (o *OpenAPI) AddWebhook(key string, val any)

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) Generate

func (o *OpenAPI) Generate(p ...string) error

Generate generates the OpenAPI specification and writes it to a file.

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

type OpenAPILicense struct {
	Name string `json:"name"`
	Url  string `json:"url,omitempty"`
}

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

type SettingTable interface {
	Table
	KeyField() string
	ValueField() string
}

SettingTable is an interface for setting-related tables.

type String

type String struct{}

String represents utility functions for string manipulation.

func (String) AddSlashes

func (String) AddSlashes(str string) string

AddSlashes adds slashes before characters that need to be escaped. These characters are:

  • single quote (')
  • double quote (")
  • and backslash (\)

func (String) CamelCase

func (s String) CamelCase(str string, startWithUpper ...bool) string

CamelCase converts a string to camelCase.

func (String) FirstAlphaNumericRuneIndex

func (s String) FirstAlphaNumericRuneIndex(sr []rune, start int) int

FirstAlphaNumericRuneIndex finds the index of the first alphanumeric rune.

func (String) FirstAlphaRuneIndex

func (s String) FirstAlphaRuneIndex(sr []rune, start int) int

FirstAlphaRuneIndex finds the index of the first alphabetic rune.

func (String) GetVars

func (String) GetVars(str, before, after string) []string

GetVars extracts variables from a string using specified before and after delimiters.

func (String) IsAlphaNumericRune

func (s String) IsAlphaNumericRune(r rune) bool

IsAlphaNumericRune checks if a rune is an alphanumeric character.

func (String) IsLowerAlphaRune

func (String) IsLowerAlphaRune(r rune) bool

IsLowerAlphaRune checks if a rune is a lowercase alphabetic character.

func (String) IsNumericRune

func (String) IsNumericRune(r rune) bool

IsNumericRune checks if a rune is a numeric character.

func (String) IsUpperAlphaRune

func (String) IsUpperAlphaRune(r rune) bool

IsUpperAlphaRune checks if a rune is an uppercase alphabetic character.

func (String) KebabCase

func (s String) KebabCase(str string) string

KebabCase converts a string to kebab-case.

func (String) PascalCase

func (s String) PascalCase(str string) string

PascalCase converts a string to PascalCase.

func (String) SnakeCase

func (s String) SnakeCase(str string) string

SnakeCase converts a string to snake_case.

func (String) SpecialCase

func (s String) SpecialCase(str string, delimiter rune) string

SpecialCase converts a string to snake_case, kebab-case, or other formats based on the delimiter.

func (String) StripSlashes

func (String) StripSlashes(str string) string

StripSlashes un-quotes a quoted string.

func (String) ToLowerAlphaRune

func (s String) ToLowerAlphaRune(r rune) rune

ToLowerAlphaRune converts an uppercase alphabetic rune to lowercase.

func (String) ToUpperAlphaRune

func (s String) ToUpperAlphaRune(r rune) rune

ToUpperAlphaRune converts a lowercase alphabetic rune to uppercase.

type StructTag

type StructTag struct {
	Key   string
	Value string
}

StructTag represents a key-value pair within a struct tag.

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

func (t *Telegram) AddMessage(text string)

AddMessage sets the text message to be sent.

func (*Telegram) Send

func (t *Telegram) Send() error

Send sends the message with attachments to the specified chat.

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.

func (Translator) Trans

func (t Translator) Trans(lang, key string, params ...map[string]string) string

Trans translates a message based on the language and translation key, with optional parameter replacement.

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) IsValid

func (v *Validator) IsValid(val any, tag string) bool

IsValid checks if a value is valid based on a validation tag.

func (*Validator) New

func (v *Validator) New()

New initializes a new instance of the Validator.

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

func (v *Validator) TranslateError(err error, lang string) error

TranslateError translates validation errors and creates an error instance with translated details.

func (*Validator) ValidateStruct

func (v *Validator) ValidateStruct(val any, lang string) error

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.

func (*Validator) ValidateValuer

func (*Validator) ValidateValuer(field reflect.Value) any

ValidateValuer attempts to retrieve the value for validation from a Valuer interface.

Jump to

Keyboard shortcuts

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