Documentation
¶
Index ¶
- Variables
- type Cache
- type ControllerConfig
- type ControllerContext
- type Database
- type DatabaseContext
- type DatabaseOption
- type DistributedCache
- type ESDocumenter
- type Initalizer
- type Logger
- type Model
- type ModelContext
- type RBAC
- type Request
- type Response
- type Service
- type ServiceContext
- func (sc *ServiceContext) Context() context.Context
- func (sc *ServiceContext) Cookie(name string) (string, error)
- func (sc *ServiceContext) Data(code int, contentType string, data []byte)
- func (sc *ServiceContext) DatabaseContext() *DatabaseContext
- func (sc *ServiceContext) GetPhase() consts.Phase
- func (sc *ServiceContext) HTML(code int, name string, obj any)
- func (sc *ServiceContext) Redirect(code int, location string)
- func (sc *ServiceContext) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
- func (sc *ServiceContext) SetPhase(phase consts.Phase)
- func (sc *ServiceContext) WithPhase(phase consts.Phase) *ServiceContext
- type ServiceError
- type StandardLogger
- type StructuredLogger
- type ZapLogger
Constants ¶
This section is empty.
Variables ¶
var ErrEntryNotFound = errors.New("cache entry not found")
ErrEntryNotFound is returned when a cache entry is not found.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache[T any] interface { // Get retrieves a value from the cache by key. // Returns ErrEntryNotFound if the key does not exist. Get(key string) (T, error) // Peek retrieves a value from the cache by key without affecting its position or access time. // Returns ErrEntryNotFound if the key does not exist. Peek(key string) (T, error) // Set stores a value in the cache with the specified TTL. // A zero TTL means the entry will not expire. Set(key string, value T, ttl time.Duration) error // Delete removes a key from the cache. // Returns ErrEntryNotFound if the key does not exist. Delete(key string) error // Exists checks if a key exists in the cache. // Returns true if the key exists, false otherwise. Exists(key string) bool // Len returns the number of entries currently stored in the cache. Len() int // Clear removes all entries from the cache. Clear() // WithContext replaces the cache internal context that used to propagate span context. WithContext(ctx context.Context) Cache[T] }
Cache interface provides a unified caching abstraction with consistent error handling. This interface supports various cache operations with proper error reporting and distributed tracing capabilities.
Generic type T can be any serializable data type.
Error Handling:
All operations return an error to provide comprehensive error information. For Get/Peek operations, ErrEntryNotFound is returned when the key doesn't exist. This design follows Go best practices and aligns with standard library patterns.
Operations:
- Set: Store value with TTL, returns error on failure
- Get: Retrieve value and mark as accessed, returns ErrEntryNotFound if key doesn't exist
- Peek: Retrieve value without affecting access order, returns ErrEntryNotFound if key doesn't exist
- Delete: Remove specific key, returns error on failure
- Exists: Check if key exists, returns bool
- Len: Get current number of cached items, returns int
- Clear: Remove all cached items
- WithContext: Returns cache instance with tracing context for distributed tracing
Key features:
- Type-safe operations with generics
- Consistent error handling across all operations
- TTL support for expirable entries
- Context-aware operations for tracing
- Thread-safe operations
Error handling:
- Returns ErrEntryNotFound when cache entries are not found
- All operations return errors for proper error handling
- Supports graceful degradation in distributed environments
type ControllerConfig ¶
type ControllerContext ¶
type ControllerContext struct {
Username string // currrent login user.
UserID string // currrent login user id
Route string
Params map[string]string
Query map[string][]string
RequestID string
TraceID string
PSpanID string
SpanID string
Seq int
}
func NewControllerContext ¶
func NewControllerContext(c *gin.Context) *ControllerContext
NewControllerContext creates a ControllerContext from gin.Context
type Database ¶
type Database[M Model] interface { // Create one or multiple record. // Pass M to create one record, // Pass []M to create multiple record. // It will update the "created_at" and "updated_at" field. Create(objs ...M) error // Delete one or multiple record. // Pass M to delete one record. // Pass []M to delete multiple record. Delete(objs ...M) error // Update one or multiple record, if record doesn't exist, it will be created. // Pass M to update one record. // Pass []M to update multiple record. // It will just update the "updated_at" field. Update(objs ...M) error // UpdateById only update one record with specific id. // its not invoke model hook. UpdateById(id string, key string, value any) error // List all records and write to dest. List(dest *[]M, cache ...*[]byte) error // Get one record with specific id and write to dest. Get(dest M, id string, cache ...*[]byte) error // First finds the first record ordered by primary key. First(dest M, cache ...*[]byte) error // Last finds the last record ordered by primary key Last(dest M, cache ...*[]byte) error // Take finds the first record returned by the database in no specified order. Take(dest M, cache ...*[]byte) error // Count returns the total number of records with the given query condition. Count(*int64) error // Cleanup delete all records that column 'deleted_at' is not null. Cleanup() error // Health checks the database connectivity and basic operations. // It returns nil if the database is healthy, otherwise returns an error. Health() error DatabaseOption[M] }
Database interface provides comprehensive database operations for any model type. This interface is constrained by the Model interface, ensuring type safety for database operations across different model implementations.
Generic constraint:
M must implement the Model interface (typically by embedding model.Base)
Core operations:
- CRUD operations with automatic timestamp management
- Flexible querying with various finder methods
- Health monitoring and cleanup capabilities
- Optional caching support for improved performance
The interface embeds DatabaseOption[M] to provide chainable query building.
type DatabaseContext ¶
type DatabaseContext struct {
Username string // currrent login user.
UserID string // currrent login user id
Route string
Params map[string]string
Query map[string][]string
RequestID string
TraceID string
PSpanID string
SpanID string
Seq int
// contains filtered or unexported fields
}
func NewDatabaseContext ¶
func NewDatabaseContext(c *gin.Context, ctxs ...context.Context) *DatabaseContext
NewDatabaseContext creates a DatabaseContext from gin.Context
You can pass the custom context.Context to propagate span tracing, otherwise use the c.Request.Context().
func (*DatabaseContext) Context ¶
func (dc *DatabaseContext) Context() context.Context
Context converts *DatabaseContext to context.Context. It starts from the underlying ctx.context and conditionally injects extra metadata.
type DatabaseOption ¶
type DatabaseOption[M Model] interface { // WithDB returns a new database manipulator, only support *gorm.DB. WithDB(any) Database[M] // WithTable multiple custom table, always used with the method `WithDB`. WithTable(name string) Database[M] // WithDebug setting debug mode, the priority is higher than config.Server.LogLevel and default value(false). WithDebug() Database[M] // WithQuery is where condition. WithQuery(query M, fuzzyMatch ...bool) Database[M] // WithQueryRaw is where condition. // database.WithQueryRaw(xxx) same as database.WithQuery(xxx) and provides more flexible query. // Examples: // - WithQueryRaw("name = ?", "hybfkuf") // - WithQueryRaw("name <> ?", "hybfkuf") // - WithQueryRaw("name IN (?)", []string{"hybfkuf", "hybfkuf 2"}) // - WithQueryRaw("name LIKE ?", "%hybfkuf%") // - WithQueryRaw("name = ? AND age >= ?", "hybfkuf", "100") // - WithQueryRaw("updated_at > ?", lastWeek) // - WithQueryRaw("created_at BETWEEN ? AND ?", lastWeek, today) WithQueryRaw(query any, args ...any) Database[M] // WithCursor enables cursor-based pagination. // cursorValue is the value of the last record in the previous page. // next indicates the direction of pagination: // - true: fetch records after the cursor (next page) // - false: fetch records before the cursor (previous page) // // Example: // // // First page (no cursor) // database.Database[*model.User]().WithLimit(10).List(&users) // // Next page (using last user's ID as cursor) // lastID := users[len(users)-1].ID // database.Database[*model.User]().WithCursor(lastID, true).WithLimit(10).List(&nextUsers) // // Next page (using last user id as cursor) // database.Database[*model.User]().WithCursor(lastID, true, "user_id").WithLimit(10).List(&nextUsers) WithCursor(string, bool, ...string) Database[M] // WithAnd with AND query condition(default). // It must be called before WithQuery. WithAnd(...bool) Database[M] // WithAnd with OR query condition. // It must be called before WithQuery. WithOr(...bool) Database[M] // WithTimeRange applies a time range filter to the query based on the specified column name. // It restricts the results to records where the column's value falls within the specified start and end times. // This method is designed to be used in a chainable manner, allowing for the construction of complex queries. // // Parameters: // - columnName: The name of the column to apply the time range filter on. This should be a valid date/time column in the database. // - startTime: The beginning of the time range. Records with the column's value equal to or later than this time will be included. // - endTime: The end of the time range. Records with the column's value equal to or earlier than this time will be included. // // Returns: A modified Database instance that includes the time range filter in its query conditions. WithTimeRange(columnName string, startTime time.Time, endTime time.Time) Database[M] // WithSelect specify fields that you want when querying, creating, updating // default select all fields. WithSelect(columns ...string) Database[M] // WithSelectRaw WithSelectRaw(query any, args ...any) Database[M] // WithIndex use specific index to query. WithIndex(index string) Database[M] // WithTransaction executes operations within a transaction. WithTransaction(tx any) Database[M] // WithJoinRaw WithJoinRaw(query string, args ...any) Database[M] // WithLock adds locking clause to SELECT statement. // It must be used within a transaction (WithTransaction). WithLock(mode ...string) Database[M] // WithBatchSize set batch size for bulk operations. affects Create, Update, Delete. WithBatchSize(size int) Database[M] // WithScope applies pagination parameters to the query, useful for retrieving data in pages. // This method enables front-end applications to request a specific subset of records, // based on the desired page number and the number of records per page. // // Parameters: // - page: The page number being requested. Page numbers typically start at 1. // - size: The number of records to return per page. This determines the "size" of each page. // // The pagination logic calculates the offset based on the page number and size, // and applies it along with the limit (size) to the query. This facilitates efficient // data fetching suitable for front-end pagination displays. // // Returns: A modified Database instance that includes pagination parameters in its query conditions. WithScope(page, size int) Database[M] // WithLimit determines how much record should retrieve. // limit is 0 or -1 means no limit. WithLimit(limit int) Database[M] // WithExclude excludes records that matchs a condition within a list. // For example: // - If you want exlcude users with specific ids from your query, // you can use WithExclude(excludes), // excludes: "id" as key, ["myid1", "myid2", "myid3"] as value. // - If you want excludes users that id not ["myid1", "myid2"] and not not ["root", "noname"], // the `excludes` should be: // excludes := make(map[string][]any) // excludes["id"] = []any{"myid1", "myid2"} // excludes["name"] = []any{"root", "noname"}. WithExclude(map[string][]any) Database[M] // WithOrder // For example: // - WithOrder("name") // default ASC. // - WithOrder("name desc") // - WithOrder("created_at") // - WithOrder("updated_at desc") // NOTE: you cannot using the mysql keyword, such as: "order", "limit". WithOrder(order string) Database[M] // WithExpand, for "foreign key". WithExpand(expand []string, order ...string) Database[M] // WithPurge tells the database manipulator to delete resource in database permanently. WithPurge(...bool) Database[M] // WithCache tells the database manipulator to retrieve resource from cache. WithCache(...bool) Database[M] // WithOmit omit specific columns when create/update. WithOmit(...string) Database[M] // WithTryRun only executes model hooks without performing actual database operations. // Also logs the SQL statements that would have been executed. WithTryRun(...bool) Database[M] // WithoutHook tells the database manipulator not invoke model hooks. WithoutHook() Database[M] }
DatabaseOption interface. WithXXX setting database options.
type DistributedCache ¶
type DistributedCache[T any] interface { Cache[T] // SetWithSync stores a value in both local and distributed cache with synchronization. // // Operation flow: // 1. Set value in local cache with localTTL expiration // 2. Send 'Set' event to state node // 3. State node sets Redis cache with remoteTTL expiration (Cache.Set method does not set Redis cache) // 4. State node sends 'SetDone' event // 5. Current node updates local cache SetWithSync(key string, value T, localTTL time.Duration, remoteTTL time.Duration) error // GetWithSync retrieves a value from local cache first, then from distributed cache if not found. // // Operation flow: // 1. Retrieve from local cache // 2. If not found in local cache, retrieve from Redis // 3. If found in Redis, backfill to local cache with localTTL expiration // Note: Backfilling local cache does not send 'Set' event to state node GetWithSync(key string, localTTL time.Duration) (T, error) // DeleteWithSync removes a value from both local and distributed cache with synchronization. // // Operation flow: // 1. Delete from local cache // 2. Send 'Del' event to state node // 3. State node deletes Redis cache (Cache.Delete method does not delete Redis cache) // 4. State node sends 'DelDone' event // 5. Current node deletes from local cache DeleteWithSync(key string) error }
DistributedCache defines a two-level distributed caching system that combines local memory cache with Redis backend for high-performance, synchronized caching across multiple nodes.
Architecture:
- Local Cache: High-speed in-memory cache for immediate access
- Redis Cache: Distributed persistent storage for cross-node data sharing
- Kafka Events: Real-time cache synchronization and invalidation across nodes
- State Node: Coordinates cache operations and ensures consistency
Key Features:
- Automatic cache synchronization across multiple application instances
- Configurable TTL for both local and distributed cache layers
- Event-driven cache invalidation using Kafka messaging
- Performance metrics tracking (hits, misses, operations)
- Goroutine pool for efficient concurrent operations
- Type-safe generic implementation
Usage Patterns:
- Use SetWithSync/GetWithSync/DeleteWithSync for data that needs cross-node synchronization
- Use regular Cache[T] methods (Set/Get/Delete) for local-only operations
- Configure appropriate TTL values: localTTL <= remoteTTL for optimal performance
Thread Safety:
- All operations are thread-safe and can be called concurrently
- Internal synchronization handles concurrent access to cache maps
Performance Considerations:
- Local cache provides sub-microsecond access times
- Redis operations add network latency but ensure data consistency
- Kafka events enable near real-time cache synchronization
- Goroutine pool prevents resource exhaustion under high load
type ESDocumenter ¶
type ESDocumenter interface {
// Document returns a map representing an Elasticsearch document.
// The returned map should contain all fields to be indexed, where:
// - keys are field names (string type)
// - values are field values (any type)
//
// Implementation notes:
// 1. The returned map should only contain JSON-serializable values.
// 2. Field names should match those defined in the Elasticsearch mapping.
// 3. Complex types (like nested objects or arrays) should be correctly
// represented in the returned map.
//
// Example:
// return map[string]any{
// "id": "1234",
// "title": "Sample Document",
// "tags": []string{"tag1", "tag2"},
// }
Document() map[string]any
// GetID returns a string that uniquely identifies the document.
// This ID is typically used as the Elasticsearch document ID.
//
// Implementation notes:
// 1. The ID should be unique within the index.
// 2. If no custom ID is needed, consider returning an empty string
// to let Elasticsearch auto-generate an ID.
// 3. The ID should be a string, even if it's originally a numeric value.
//
// Example:
// return "user_12345"
GetID() string
}
ESDocumenter represents a document that can be indexed into Elasticsearch. Types implementing this interface should be able to convert themselves into a document format suitable for Elasticsearch indexing.
type Initalizer ¶
type Initalizer interface {
Init() error
}
Initalizer interface is used to initialize configuration, flag arguments, logger, or other components. This interface is commonly implemented by bootstrap components that need to perform initialization tasks during application startup.
Example implementations:
- Configuration loaders
- Logger initializers
- Database connection setup
- Cache initialization
type Logger ¶
type Logger interface {
With(fields ...string) Logger
WithObject(name string, obj zapcore.ObjectMarshaler) Logger
WithArray(name string, arr zapcore.ArrayMarshaler) Logger
WithControllerContext(*ControllerContext, consts.Phase) Logger
WithServiceContext(*ServiceContext, consts.Phase) Logger
WithDatabaseContext(*DatabaseContext, consts.Phase) Logger
StandardLogger
StructuredLogger
ZapLogger
}
Logger interface combines all logging capabilities into a unified interface. This interface provides comprehensive logging functionality by embedding StandardLogger, StructuredLogger, and ZapLogger interfaces, along with context-aware logging methods.
Key features:
- Standard logging (Debug, Info, Warn, Error, Fatal)
- Structured logging with key-value pairs (Debugw, Infow, etc.)
- Zap-specific structured logging with typed fields
- Context-aware logging for controllers, services, and database operations
- Support for complex object and array marshaling
This unified approach allows flexible logging usage throughout the application.
type Model ¶
type Model interface {
GetTableName() string // GetTableName returns the table name.
GetID() string
SetID(id ...string) // SetID method will automatically set the id if id is empty.
ClearID() // ClearID always set the id to empty.
GetCreatedBy() string
GetUpdatedBy() string
GetCreatedAt() time.Time
GetUpdatedAt() time.Time
SetCreatedBy(string)
SetUpdatedBy(string)
SetCreatedAt(time.Time)
SetUpdatedAt(time.Time)
Expands() []string // Expands returns the foreign keys should preload.
Excludes() map[string][]any
MarshalLogObject(zapcore.ObjectEncoder) error // MarshalLogObject implement zap.ObjectMarshaler
CreateBefore(*ModelContext) error
CreateAfter(*ModelContext) error
DeleteBefore(*ModelContext) error
DeleteAfter(*ModelContext) error
UpdateBefore(*ModelContext) error
UpdateAfter(*ModelContext) error
ListBefore(*ModelContext) error
ListAfter(*ModelContext) error
GetBefore(*ModelContext) error
GetAfter(*ModelContext) error
}
Model interface defines the contract for all data models in the framework. This interface ensures consistent behavior across different model implementations and provides comprehensive functionality for database operations, logging, and lifecycle hooks.
Implementation requirements:
- Must be a pointer to a struct (e.g., *User, not User) - otherwise causes panic
- Must have an "ID" field as the primary key in the database
- Should embed model.Base to inherit common fields and methods
Example implementation:
type User struct {
model.Base
Name string `json:"name"`
Email string `json:"email"`
}
func (u *User) GetTableName() string {
return "users"
}
Core functionality:
- Table and ID management for database operations
- Audit trail with created/updated timestamps and user tracking
- Relationship management through Expands() for foreign key preloading
- Query filtering through Excludes() for conditional operations
- Structured logging support via zap.ObjectMarshaler
- Lifecycle hooks for custom business logic during CRUD operations
type ModelContext ¶
type ModelContext struct {
// contains filtered or unexported fields
}
func NewModelContext ¶
func NewModelContext(dbctx *DatabaseContext, ctx context.Context) *ModelContext
func (*ModelContext) Context ¶
func (mc *ModelContext) Context() context.Context
func (*ModelContext) DatabaseContext ¶
func (mc *ModelContext) DatabaseContext() *DatabaseContext
type RBAC ¶
type RBAC interface {
AddRole(name string) error
RemoveRole(name string) error
GrantPermission(role string, resource string, action string) error
RevokePermission(role string, resource string, action string) error
AssignRole(subject string, role string) error
UnassignRole(subject string, role string) error
}
RBAC interface defines comprehensive role-based access control operations. This interface provides a complete RBAC system supporting roles, permissions, and subject assignments with flexible resource and action management.
RBAC Model Components:
- Subject: Users or entities that need access (e.g., "user:123", "service:api")
- Role: Named collection of permissions (e.g., "admin", "editor", "viewer")
- Resource: Protected objects or endpoints (e.g., "users", "posts", "/api/v1/users")
- Action: Operations on resources (e.g., "read", "write", "delete", "create")
Permission Model:
- Permissions are defined as (role, resource, action) tuples
- Subjects are assigned roles, inheriting all role permissions
- Supports hierarchical roles and resource patterns
Implementation:
- Typically backed by Casbin for policy enforcement
- Supports both file-based and database-backed policy storage
- Can integrate with external identity providers
Usage patterns:
- API endpoint authorization
- Resource-level access control
- Multi-tenant permission management
type Service ¶
type Service[M Model, REQ Request, RSP Response] interface { Create(*ServiceContext, REQ) (RSP, error) Delete(*ServiceContext, REQ) (RSP, error) Update(*ServiceContext, REQ) (RSP, error) Patch(*ServiceContext, REQ) (RSP, error) List(*ServiceContext, REQ) (RSP, error) Get(*ServiceContext, REQ) (RSP, error) CreateMany(*ServiceContext, REQ) (RSP, error) DeleteMany(*ServiceContext, REQ) (RSP, error) UpdateMany(*ServiceContext, REQ) (RSP, error) PatchMany(*ServiceContext, REQ) (RSP, error) CreateBefore(*ServiceContext, M) error CreateAfter(*ServiceContext, M) error DeleteBefore(*ServiceContext, M) error DeleteAfter(*ServiceContext, M) error UpdateBefore(*ServiceContext, M) error UpdateAfter(*ServiceContext, M) error PatchBefore(*ServiceContext, M) error PatchAfter(*ServiceContext, M) error ListBefore(*ServiceContext, *[]M) error ListAfter(*ServiceContext, *[]M) error GetBefore(*ServiceContext, M) error GetAfter(*ServiceContext, M) error CreateManyBefore(*ServiceContext, ...M) error CreateManyAfter(*ServiceContext, ...M) error DeleteManyBefore(*ServiceContext, ...M) error DeleteManyAfter(*ServiceContext, ...M) error UpdateManyBefore(*ServiceContext, ...M) error UpdateManyAfter(*ServiceContext, ...M) error PatchManyBefore(*ServiceContext, ...M) error PatchManyAfter(*ServiceContext, ...M) error Import(*ServiceContext, io.Reader) ([]M, error) Export(*ServiceContext, ...M) ([]byte, error) Filter(*ServiceContext, M) M FilterRaw(*ServiceContext) string Logger }
Service interface provides comprehensive business logic operations for model types. This interface defines the service layer that sits between controllers and database operations, implementing business rules, validation, complex operations, and lifecycle management.
Implementation requirements:
- The implementing object must be a pointer to struct
Generic constraints:
- M: Must implement the Model interface
- REQ: Request type (typically DTOs or request structures)
- RSP: Response type (typically DTOs or response structures)
Core operations:
- CRUD operations: Create, Delete, Update, Patch, List, Get
- Batch operations: CreateMany, DeleteMany, UpdateMany, PatchMany
- Lifecycle hooks: Before/After methods for each operation
- Data operations: Import/Export for bulk data management
- Filtering: Custom filtering logic for queries
ServiceContext provides:
- HTTP request/response context
- Database transaction management
- User authentication and authorization context
- Request validation and data binding
- Logging and tracing capabilities
Hook methods allow custom business logic:
- Before hooks: Validation, authorization, data transformation
- After hooks: Notifications, caching, audit logging, cleanup
type ServiceContext ¶
type ServiceContext struct {
Method string // http method
Request *http.Request // http request
URL *url.URL // request url
Header http.Header // http request header
WriterHeader http.Header // http writer header
ClientIP string // client ip
UserAgent string // user agent
Writer http.ResponseWriter
// route parameters,
//
// eg: PUT /api/gists/:id/star
// Params: map[string]string{"id": "xxxxx-mygistid-xxxxx"}
//
// eg: DELETE /api/user/:userid/shelf/shelfid/book
// Params: map[string]string{"userid": "xxxxx-myuserid-xxxxx", "shelfid": "xxxxx-myshelfid-xxxxx"}
Params map[string]string
Query map[string][]string
SessionID string // session id
Username string // currrent login user.
UserID string // currrent login user id
Route string
RequestID string
TraceID string
PSpanID string
SpanID string
Seq int
// contains filtered or unexported fields
}
func NewServiceContext ¶
func NewServiceContext(c *gin.Context, ctxs ...context.Context) *ServiceContext
NewServiceContext creates ServiceContext from gin.Context. Including request details, headers and user information.
You can pass the custom context.Context to propagate span tracing, otherwise use the c.Request.Context().
func (*ServiceContext) Context ¶
func (sc *ServiceContext) Context() context.Context
Context converts *ServiceContex to context.Context. It starts from the underlying ctx.context and conditionally injects extra metadata.
func (*ServiceContext) Data ¶
func (sc *ServiceContext) Data(code int, contentType string, data []byte)
func (*ServiceContext) DatabaseContext ¶
func (sc *ServiceContext) DatabaseContext() *DatabaseContext
func (*ServiceContext) GetPhase ¶
func (sc *ServiceContext) GetPhase() consts.Phase
func (*ServiceContext) Redirect ¶
func (sc *ServiceContext) Redirect(code int, location string)
func (*ServiceContext) SetCookie ¶
func (sc *ServiceContext) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
func (*ServiceContext) SetPhase ¶
func (sc *ServiceContext) SetPhase(phase consts.Phase)
func (*ServiceContext) WithPhase ¶
func (sc *ServiceContext) WithPhase(phase consts.Phase) *ServiceContext
type ServiceError ¶
ServiceError represents an error with a custom HTTP status code that can be returned from service layer methods
func NewServiceError ¶
func NewServiceError(statusCode int, message string) *ServiceError
NewServiceError creates a new ServiceError with the given status code and message
func NewServiceErrorWithCause ¶
func NewServiceErrorWithCause(statusCode int, message string, err error) *ServiceError
NewServiceErrorWithCause creates a new ServiceError with the given status code, message and underlying error
func (*ServiceError) Error ¶
func (e *ServiceError) Error() string
Error implements the error interface
func (*ServiceError) Unwrap ¶
func (e *ServiceError) Unwrap() error
Unwrap returns the underlying error for error unwrapping
type StandardLogger ¶
type StandardLogger interface {
Debug(args ...any)
Info(args ...any)
Warn(args ...any)
Error(args ...any)
Fatal(args ...any)
Debugf(format string, args ...any)
Infof(format string, args ...any)
Warnf(format string, args ...any)
Errorf(format string, args ...any)
Fatalf(format string, args ...any)
}
StandardLogger interface provides standard logging methods for custom logger implementations. This interface follows the traditional logging pattern with both simple and formatted logging methods.
Usage:
- Implement this interface to create custom loggers
- Use Debug/Info/Warn/Error for simple logging
- Use Debugf/Infof/Warnf/Errorf for formatted logging
- Fatal methods should terminate the program after logging
type StructuredLogger ¶
type StructuredLogger interface {
Debugw(msg string, keysAndValues ...any)
Infow(msg string, keysAndValues ...any)
Warnw(msg string, keysAndValues ...any)
Errorw(msg string, keysAndValues ...any)
Fatalw(msg string, keysAndValues ...any)
}
StructuredLogger interface provides structured logging methods with key-value pairs. This interface is designed for structured logging where additional context can be attached to log messages as key-value pairs.
Usage:
logger.Infow("User login", "userID", 123, "ip", "192.168.1.1")
logger.Errorw("Database error", "error", err, "query", sql)
The 'w' suffix stands for "with" (structured data).
type ZapLogger ¶
type ZapLogger interface {
Debugz(msg string, fields ...zap.Field)
Infoz(msg string, fields ...zap.Field)
Warnz(msg string, fields ...zap.Field)
Errorz(msg string, fields ...zap.Field)
Fatalz(msg string, fields ...zap.Field)
}
ZapLogger interface provides zap-specific logging methods with structured fields. This interface is designed for integration with the uber-go/zap logging library, offering high-performance structured logging capabilities.
Usage:
logger.Infoz("Request processed", zap.String("method", "GET"), zap.Int("status", 200))
logger.Errorz("Database connection failed", zap.Error(err), zap.String("host", dbHost))
The 'z' suffix distinguishes these methods from other logging interfaces.