core

package
v1.0.14 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const ModelDefaultName = "ModelDefaultName"

ModelDefaultName is the default name for the primary model group.

Variables

This section is empty.

Functions

func GetFilter added in v0.1.3

func GetFilter[T IFilter](c *Context) T

GetFilter retrieves a filter of the specified type from the context. Panics if the filter is not registered.

func GetModel

func GetModel[T IModel](c *Context) T

GetModel retrieves a model of the specified type from the context. Panics if the model is not registered.

func GetReNewModel added in v0.1.2

func GetReNewModel[T IModel](db *db.DB, c *Context) T

GetReNewModel retrieves a model of the specified type and creates a fresh instance with the given database connection, useful for transaction handling. Panics if the model is not registered.

func GetRunner added in v0.1.2

func GetRunner[T IRunner](c *Context) T

GetRunner retrieves a runner of the specified type from the context. Panics if the runner is not registered.

func GetService added in v0.1.1

func GetService[T IService](c *Context) T

GetService retrieves a service of the specified type from the context. Panics if the service is not registered.

func UnmarshalKeyConfig added in v0.1.3

func UnmarshalKeyConfig[T any](key string, c *Context) (T, error)

UnmarshalKeyConfig unmarshals configuration under the given key into the specified type.

Types

type Context

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

Context is the core dependency injection container for the framework. It embeds context.Context for lifecycle control and manages all services, models, runners, and filters.

func NewContext added in v0.1.2

func NewContext(config config2.IConfig, ctx context.Context) *Context

NewContext creates a new Context with the given server, config, and parent context.

func (*Context) AddModel

func (c *Context) AddModel(model ...IModel)

AddModel registers one or more models into the context.

func (*Context) AddModelGroup added in v0.1.3

func (c *Context) AddModelGroup(modelGroup ...IModelGroup)

AddModelGroup registers one or more model groups into the context.

func (*Context) AddRunner added in v0.1.2

func (c *Context) AddRunner(runner ...IRunner)

AddRunner registers one or more background runners into the context.

func (*Context) AddService

func (c *Context) AddService(services ...IService)

AddService registers one or more services into the context.

func (*Context) Any added in v0.1.2

func (c *Context) Any(relativePath string, handlers ...web.HandlerFunc) *web.Route

Any registers a route handler for all HTTP methods and returns the route.

func (*Context) Copy

func (c *Context) Copy(server *web.Server, filters []IFilter) *Context

Copy creates a shallow copy of the Context with a new server and filters, sharing all maps and locks with the original for concurrent access.

func (*Context) DefaultModelGroup added in v0.1.3

func (c *Context) DefaultModelGroup() IModelGroup

DefaultModelGroup returns the default model group registered under ModelDefaultName.

func (*Context) Delete added in v0.1.2

func (c *Context) Delete(relativePath string, handlers ...web.HandlerFunc) *web.Route

Delete registers a DELETE route handler and returns the route.

func (*Context) Get

func (c *Context) Get(relativePath string, handlers ...web.HandlerFunc) *web.Route

Get registers a GET route handler and returns the route.

func (*Context) GetConfig

func (c *Context) GetConfig() config2.IConfig

GetConfig returns the configuration object associated with this context.

func (*Context) GetFilter added in v0.1.3

func (c *Context) GetFilter(f func(m IFilter) bool) IFilter

GetFilter finds the first filter matching the predicate.

func (*Context) GetModel

func (c *Context) GetModel(f func(m IModel) bool) IModel

GetModel finds the first model matching the predicate.

func (*Context) GetModelGroup added in v0.1.3

func (c *Context) GetModelGroup(name string) IModelGroup

GetModelGroup returns the model group with the given name, or nil if not found.

func (*Context) GetRunner added in v0.1.2

func (c *Context) GetRunner(f func(m IRunner) bool) IRunner

GetRunner finds the first runner matching the predicate function.

func (*Context) GetRunners added in v0.9.10

func (c *Context) GetRunners() []IRunner

GetRunners returns all registered runners in the context.

func (*Context) GetService

func (c *Context) GetService(f func(m IService) bool) IService

GetService finds the first service (including runners and model groups) matching the predicate.

func (*Context) GetTransaction

func (c *Context) GetTransaction() *model.Transaction

GetTransaction returns the transaction manager for the default model group.

func (*Context) GetTransactionByName added in v0.7.1

func (c *Context) GetTransactionByName(name string) *model.Transaction

GetTransactionByName returns the transaction manager for the named model group.

func (*Context) Go added in v0.1.3

func (c *Context) Go(f func(c *Context))

Go runs the given function in a goroutine with panic recovery. Errors are logged instead of crashing the application.

func (*Context) Handle added in v0.1.2

func (c *Context) Handle(httpMethod string, relativePath string, handlers ...web.HandlerFunc) *web.Route

Handle registers a route handler for the given HTTP method and returns the route.

func (*Context) IsServiceRegistered added in v1.0.4

func (c *Context) IsServiceRegistered(s IService) bool

IsServiceRegistered reports whether the given value is registered in the service map (i.e. added via AddService). Used to avoid double-initializing services that also implement IRunner, since they are initialized in the services loop and would otherwise be initialized again in the runners loop.

func (*Context) Post

func (c *Context) Post(relativePath string, handlers ...web.HandlerFunc) *web.Route

Post registers a POST route handler and returns the route.

func (*Context) Put added in v0.1.2

func (c *Context) Put(relativePath string, handlers ...web.HandlerFunc) *web.Route

Put registers a PUT route handler and returns the route.

func (*Context) ReverseProxy added in v0.6.1

func (c *Context) ReverseProxy(relativePath string, targetUrl string) *web.Route

ReverseProxy registers a reverse proxy to the target URL and returns the route.

func (*Context) SSE added in v0.7.1

func (c *Context) SSE(relativePath string, handler web.SSEHandler) *web.Route

SSE registers a Server-Sent Events endpoint and returns the route.

func (*Context) Server added in v1.0.4

func (c *Context) Server() *web.Server

Server returns the web2 server for this context.

func (*Context) Static added in v0.6.1

func (c *Context) Static(relativePath string, filepath string) *web.Route

Static registers a static file serving route and returns the route.

func (*Context) StaticFs added in v0.6.1

func (c *Context) StaticFs(relativePath string, fs http.FileSystem) *web.Route

StaticFs registers a static file serving route with a custom http.FileSystem and returns the route.

func (*Context) WebSocket added in v0.7.1

func (c *Context) WebSocket(relativePath string, handler web.WebSocketHandler) *web.Route

WebSocket registers a WebSocket endpoint and returns the route.

type IConverter added in v0.1.3

type IConverter interface {
	IService
	web.Converter
}

IConverter is the response converter interface, extending IService.

Converters transform service return values into HTTP responses. Custom formats like JSON, XML, Protocol Buffers can be implemented.

Example:

type CustomConverter struct {
    core.IConverter
}

func (c *CustomConverter) Init(ctx *Context) error {
    return nil
}

func (c *CustomConverter) Request(fc web.FilterChain, req *web.Request) {
    result, err := fc.Next()
    // custom response handling
}

type IFilter added in v0.1.3

type IFilter interface {
	IService
	web.Filter
}

IFilter is the HTTP filter/middleware interface, extending IService.

Filters are executed in the request processing chain for cross-cutting concerns such as authentication, logging, and rate limiting.

Example:

type AuthFilter struct {
    core.IFilter
}

func (f *AuthFilter) Init(ctx *Context) error {
    return nil
}

func (f *AuthFilter) Handle(fc web.FilterChain, req *web.Request) (any, error) {
    token := req.GetHeader("Authorization")
    if token == "" {
        return nil, errors.New("unauthorized")
    }
    return fc.Next()
}

type IModel

type IModel interface {
	// Init initializes the model with the given database and context.
	Init(db *db.DB, c *Context) error

	// IsExist reports whether the database table exists.
	IsExist() (bool, error)

	// CreateTable creates the database table if it does not exist.
	CreateTable() error

	// DeleteTable deletes all rows from the table (does not drop the table structure).
	DeleteTable() error

	// DropTable drops the database table, removing the table structure and all data.
	DropTable() error

	// GetTableName returns the database table name.
	GetTableName() string

	// ReNew creates a new model instance with the given database connection,
	// useful for transaction handling.
	ReNew(db *db.DB, c *Context) IModel
}

IModel is the data access layer interface providing database operations.

Models implementing this interface are automatically registered in the DI container.

Example:

type UserModel struct {
    *model.Model[*User]
}

func (m *UserModel) Init(db *db.DB, c *Context) error {
    m.Model = model.NewModel[*User](db, "t_user")
    return m.CreateTable()
}

type IModelGroup added in v0.1.3

type IModelGroup interface {
	IService
	// AddModel adds one or more models to the group.
	AddModel(model ...IModel)

	// GetModel returns all models in this group.
	GetModel() []IModel

	// AutoCreateTable sets whether tables should be auto-created during init.
	AutoCreateTable(autoCreateTable bool)

	// SwitchDB replaces the database connection and reinitializes all models.
	SwitchDB(db *db.DB, context *Context) error

	// SetDefaultDB sets the default database connection for this group.
	SetDefaultDB(db *db.DB)

	// Name returns the model group name.
	Name() string

	// GetTransaction returns the transaction manager for this group.
	GetTransaction() *model.Transaction
}

IModelGroup is the interface for managing collections of related models.

Model groups can batch-manage multiple models, supporting auto table creation and transaction management.

Example:

userModel := &UserModel{}
group := app.NewModelGroup(db, "user_group")
group.AddModel(userModel)
group.AutoCreateTable(true)

type IRest

type IRest interface {
	IService
}

IRest is the REST controller interface, extending IService.

Example:

type UserController struct {
    core.IRest
}

func (c *UserController) Init(ctx *Context) error {
    ctx.Get("/users", c.GetUsers)
    ctx.Get("/users/:id", c.GetUser)
    ctx.Post("/users", c.CreateUser)
    return nil
}

type IRunner added in v0.1.2

type IRunner interface {
	IService
	// Run executes the background task. Lifecycle is controlled by the server's context pool.
	Run() error
}

IRunner is the background task interface, extending IService.

Tasks implementing this interface run in the background after application startup. The lifecycle is managed by the server's context pool. Suitable for scheduled tasks, message consumers, data synchronization, etc.

Example:

type BackgroundTask struct {
    core.IRunner
    ctx *core.Context
}

func (t *BackgroundTask) Init(ctx *Context) error {
    t.ctx = ctx
    return nil
}

func (t *BackgroundTask) Run() error {
    ticker := time.NewTicker(5 * time.Second)
    defer ticker.Stop()
    for {
        select {
        case <-ticker.C:
            // perform task
        }
    }
}

type IService

type IService interface {
	// Init is called during application startup to initialize the service.
	// ctx: dependency injection context for accessing other services.
	// Returns error if initialization fails.
	Init(ctx *Context) error
}

IService is the base interface for all framework services.

Services implementing this interface are automatically managed by the DI container, and Init is called during application startup.

Example:

type UserService struct {
    core.IService
}

func (s *UserService) Init(ctx *Context) error {
    // initialization logic
    return nil
}

type ModelGroup added in v0.1.3

type ModelGroup struct {
	// contains filtered or unexported fields
}

ModelGroup manages a collection of related models sharing a database connection. It handles initialization, table creation, and transaction management.

func EmptyModelGroup added in v0.1.3

func EmptyModelGroup(name string) *ModelGroup
func DefaultModelGroup() *ModelGroup {
	return &ModelGroup{
		db:     nil,
		name:   DefaultName,
		models: make([]IModel, 0),
	}
}

EmptyModelGroup creates a model group with no database, useful for testing or placeholder purposes.

func (*ModelGroup) AddModel added in v0.1.3

func (m *ModelGroup) AddModel(model ...IModel)

AddModel adds one or more models to this group.

func (*ModelGroup) AutoCreateTable added in v0.1.4

func (m *ModelGroup) AutoCreateTable(autoCreateTable bool)

AutoCreateTable sets whether tables should be auto-created during initialization.

func (*ModelGroup) GetModel added in v0.1.3

func (m *ModelGroup) GetModel() []IModel

GetModel returns all models in this group.

func (*ModelGroup) GetTransaction added in v0.1.3

func (m *ModelGroup) GetTransaction() *model.Transaction

GetTransaction returns a new transaction manager for this group's database. Panics if no database is configured.

func (*ModelGroup) Init added in v0.1.3

func (m *ModelGroup) Init(context *Context) error

Init initializes all models in the group, optionally creating tables.

func (*ModelGroup) Name added in v0.1.3

func (m *ModelGroup) Name() string

Name returns the name of this model group.

func (*ModelGroup) SetDefaultDB added in v0.1.4

func (m *ModelGroup) SetDefaultDB(db *db.DB)

SetDefaultDB sets the default database connection for this model group.

func (*ModelGroup) SwitchDB added in v0.1.3

func (m *ModelGroup) SwitchDB(db *db.DB, context *Context) error

SwitchDB replaces the database connection and reinitializes all models.

type ModelGroupBuilder added in v0.7.1

type ModelGroupBuilder struct {
	// contains filtered or unexported fields
}

ModelGroupBuilder provides a fluent API for constructing ModelGroup configurations.

func NewModelGroupBuilder added in v0.7.1

func NewModelGroupBuilder() *ModelGroupBuilder

NewModelGroupBuilder creates a new ModelGroupBuilder for fluent model group construction.

func (*ModelGroupBuilder) AutoCreateTable added in v0.7.1

func (m *ModelGroupBuilder) AutoCreateTable(auto bool) *ModelGroupBuilder

AutoCreateTable enables or disables automatic table creation during initialization.

func (*ModelGroupBuilder) Build added in v0.7.1

func (m *ModelGroupBuilder) Build() *ModelGroup

Build creates a ModelGroup from the builder configuration.

func (*ModelGroupBuilder) DB added in v0.7.1

DB sets the database connection for the model group.

func (*ModelGroupBuilder) Model added in v0.7.1

func (m *ModelGroupBuilder) Model(model ...IModel) *ModelGroupBuilder

Model adds one or more models to the group.

func (*ModelGroupBuilder) Name added in v0.7.1

Name sets the name of the model group.

type RestGroup

type RestGroup struct {
	ContextPath string
	// contains filtered or unexported fields
}

RestGroup groups REST controllers, filters, and converter for a single HTTP server.

func (*RestGroup) AddFilter added in v0.1.3

func (rg *RestGroup) AddFilter(filter ...IFilter) *RestGroup

AddFilter adds one or more filters/middleware to this group.

func (*RestGroup) AddRest

func (rg *RestGroup) AddRest(rest ...IRest) *RestGroup

AddRest adds one or more REST controllers to this group.

func (*RestGroup) Converter added in v0.1.3

func (rg *RestGroup) Converter(converter IConverter) *RestGroup

Converter sets the response converter for this group.

func (*RestGroup) Merge added in v0.1.2

func (rg *RestGroup) Merge(restGroup *RestGroup) *RestGroup

Merge combines another RestGroup into this one, merging rests, filters, and server config.

func (*RestGroup) Port added in v0.1.2

func (rg *RestGroup) Port() int

Port returns the HTTP server port for this REST group.

type RestGroupBuilder added in v0.7.1

type RestGroupBuilder struct {
	// contains filtered or unexported fields
}

RestGroupBuilder provides a fluent API for constructing RestGroup configurations.

func NewRestGroupBuilder added in v0.7.1

func NewRestGroupBuilder() *RestGroupBuilder

NewRestGroupBuilder creates a new RestGroupBuilder for fluent REST group construction.

func (*RestGroupBuilder) Build added in v0.7.1

func (b *RestGroupBuilder) Build() *RestGroup

Build creates a RestGroup from the builder configuration. Applies defaults for any unset fields (default server config, converter, etc.).

func (*RestGroupBuilder) ContextPath added in v0.7.2

func (b *RestGroupBuilder) ContextPath(contextPath string) *RestGroupBuilder

ContextPath sets the URL prefix for all routes in this REST group.

func (*RestGroupBuilder) Converter added in v0.7.1

func (b *RestGroupBuilder) Converter(converter IConverter) *RestGroupBuilder

Converter sets a custom response converter for this REST group.

func (*RestGroupBuilder) Filter added in v0.7.1

func (b *RestGroupBuilder) Filter(filters ...IFilter) *RestGroupBuilder

Filter adds one or more filters/middleware to this REST group.

func (*RestGroupBuilder) Handles added in v0.7.1

func (b *RestGroupBuilder) Handles(handles *web.Handles) *RestGroupBuilder

Handles is kept for backward compatibility but is now a no-op. Routes are registered directly on the server during Init.

func (*RestGroupBuilder) Port added in v0.7.1

func (b *RestGroupBuilder) Port(port int) *RestGroupBuilder

Port sets the HTTP server port for this REST group.

func (*RestGroupBuilder) Rest added in v0.7.1

func (b *RestGroupBuilder) Rest(rest ...IRest) *RestGroupBuilder

Rest adds one or more REST controllers to this REST group.

func (*RestGroupBuilder) ServerConfig added in v0.7.1

func (b *RestGroupBuilder) ServerConfig(serverConfig *web.ServerConfig) *RestGroupBuilder

ServerConfig sets the HTTP server configuration for this REST group.

type Server added in v0.1.2

type Server struct {
	// contains filtered or unexported fields
}

Server manages HTTP servers and background runners. It initializes REST groups, filters, converters, and runs them concurrently.

func NewServer added in v0.1.2

func NewServer(ctx *Context) *Server

NewServer creates a new Server with the given REST groups and runners.

func (*Server) AddIRunner added in v1.0.12

func (server *Server) AddIRunner(runner ...IRunner)

func (*Server) AddRestGroup added in v1.0.12

func (server *Server) AddRestGroup(restGroups ...*RestGroup)

func (*Server) GetHandler added in v1.0.11

func (server *Server) GetHandler() http.Handler

GetHandler returns an http.Handler for testing. Routes, filters, and ContextPath of each underlying Server are fully preserved.

func (*Server) Run added in v0.1.2

func (server *Server) Run() error

Run starts all HTTP servers and background runners concurrently. It uses a goroutine pool with the server's context for lifecycle management. Returns when any component fails or the context is cancelled.

Jump to

Keyboard shortcuts

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