gin_plus

package module
v4.4.7 Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: MIT Imports: 21 Imported by: 0

README

     

Gin-Plus

轻量增强 Gin 的工程化框架 — 保持 Gin 兼容性,提供 IoC、MVC、生命周期与模块化能力。目标是“增强,不改动”,帮助团队构建可维护、高可测、可扩展的 Go Web 服务。通过非侵入式扩展,把依赖注入、控制器化与工程化能力加入到 Gin 中,降低样板代码、提升项目规范与可测试性🚀。详细文档请访问 Gin-Plus 文档

特性

  • 🚀 与 Gin 无缝兼容:尽量不破坏原有 Gin 行为与调用习惯
  • 🧩 IoC / 依赖注入:自动装配服务、控制器与资源,降低手工 wiring 成本
  • 🏛 MVC 与控制器风格:约定式路由绑定,控制器方法直观映射 HTTP 接口
  • 🔌 中间件体系化:可配置、中继与组合的中间件注册方式
  • ♻️ 生命周期与资源管理:支持组件初始化、优雅关闭钩子(DB、缓存、任务等)
  • 📦 模块化/插件化:代码按模块组织,方便按需加载与复用
  • 🧰 工程化工具集:统一响应格式、全局错误处理、日志适配器、配置注入等
  • ⚡ 性能优先:增强体验同时尽量保持 Gin 的高性能和低延迟

安装

go get github.com/archine/gin-plus/v4@latest

快速开始

1、定义Service
package service

import (
	"github.com/archine/gin-plus/v4/component/ioc/bean"
	"github.com/archine/gin-plus/v4/component/ioc"
)

func init() {
	ioc.RegisterBeanDef(&TestService{})
}

type TestService struct {
	bean.Bean
	Age int `value:"${user.age:18}"`
}

func (t *TestService) GetAge() int {
	return t.Age
}
2、定义Controller
package controller

import (
	"fmt"
	"gin-plus-demo-v4/service"
	"github.com/archine/gin-plus/v4/component/ioc"
	"github.com/archine/gin-plus/v4/resp"
	"github.com/gin-gonic/gin"
)

func init() {
	ioc.RegisterBeanDef(&TestController{})
}

type TestController struct {
	testService *service.TestService `autowire:""`
}

func (t *TestController) SetRoutes(rootGroup *gin.RouterGroup) {
	rootGroup.GET("/test/hello", t.sayHello)
}

func (t *TestController) sayHello(ctx *gin.Context) {
	resp.Json(ctx, t.testService.GetAge())
}
3、启动应用
package main

import (
	_ "gin-plus-demo-v4/controller"
	ginplus "github.com/archine/gin-plus/v4"
)

func main() {
	ginplus.New().Run(ginplus.ServerMode)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

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

func New

func New() *App

New creates a new instance of the App with optional configurations.

func (*App) IsRunning added in v4.0.5

func (a *App) IsRunning() bool

IsRunning returns whether the application is currently running

func (*App) Run

func (a *App) Run(mode RunMode)

Run starts the application in the specified mode. Args:

  • mode: The run mode of the application (InitializeMode, ContainerMode, or ServerMode).

func (*App) With

func (a *App) With(opts ...Option) *App

With adds options to the App instance. This method allows you to configure the App instance with various options.

type AppEvent added in v4.3.7

type AppEvent interface {
	// Order returns the order of the event.
	// Lower numbers indicate higher priority.
	Order() int
}

AppEvent is the base interface for all app events.

type ConfigEvent added in v4.1.0

type ConfigEvent interface {
	AppEvent
	// OnConfigLoaded is called after all configuration files have been successfully loaded.
	OnConfigLoaded(cp config.Provider)
}

ConfigEvent is the interface for events related to configuration loading.

type ContainerRefreshAfterEvent

type ContainerRefreshAfterEvent interface {
	AppEvent
	// OnContainerRefreshAfter is called after the IoC container has completed its refresh process.
	// At this point, all beans have been created, dependencies injected, and the container is ready for use.
	// This is the ideal place to perform post-refresh tasks such as:
	//
	//  - Validating bean initialization results
	//  - Performing cross-bean validations
	//  - Starting background services that depend on beans
	//  - Logging container status and statistics
	//  - Triggering application-specific initialization logic
	//
	// Note: The container state should not be modified at this point.
	OnContainerRefreshAfter()
}

ContainerRefreshAfterEvent is called after the IoC container refresh process. Implement this interface to perform post-refresh tasks.

type ContainerRefreshBeforeEvent

type ContainerRefreshBeforeEvent interface {
	AppEvent
	// OnContainerRefreshBefore is called before the IoC container begins its refresh process.
	// This is the ideal place to perform container preparation tasks such as:
	//
	//  - Registering additional bean definitions
	//  - Registering pre-configured bean instances
	//  - Modifying container configuration
	//  - Performing pre-refresh validations
	//  - Setting up custom bean processors
	OnContainerRefreshBefore()
}

ContainerRefreshBeforeEvent is called before the IoC container refresh process. Implement this interface to perform container preparation tasks.

type Option

type Option func(app *App)

Option defines a function type for configuring App instances. This follows the functional options pattern, allowing flexible and extensible configuration during App creation via the New() function.

func WithBanner

func WithBanner(banner string) Option

WithBanner sets a custom banner for the application.

func WithConfigProvider added in v4.0.5

func WithConfigProvider(providerFunc func() config.Provider) Option

WithConfigProvider sets the application's configuration provider. If not specified, the default provider will be used. Note: Calling this multiple times will overwrite the previous provider.

func WithEvent

func WithEvent(events ...AppEvent) Option

WithEvent registers application lifecycle events. Events are managed by the event manager and triggered during app lifecycle.

func WithLogger

func WithLogger(loggerFunc func(cp config.Provider) gplog.Logger) Option

WithLogger sets a custom log for the application. The log function receives the application configuration and should return a configured log instance. This allows the log to be configured based on the loaded configuration settings.

Note: Calling this multiple times will overwrite the previous provider.

func WithMiddleware

func WithMiddleware(middlewares ...gin.HandlerFunc) Option

WithMiddleware registers Gin middlewares to the application. Middlewares are executed in the order they are added.

type RunMode added in v4.0.5

type RunMode int

RunMode defines the application's running mode.

const (
	// InitializeMode initializes configuration and logger only.
	// Useful for configuration validation or testing.
	InitializeMode RunMode = iota

	// ContainerMode extends InitializeMode by creating and injecting dependencies
	// into the container, while keeping the HTTP server inactive.
	ContainerMode

	// ServerMode fully operational mode where the application starts the HTTP server
	// after completing all initializations.
	ServerMode
)

type ShutdownSignal added in v4.4.6

type ShutdownSignal interface {
	// Done returns a receive-only channel that is closed when the application
	// starts shutting down.
	Done() <-chan struct{}
}

ShutdownSignal exposes an application-level shutdown notification. Long-lived handlers and workers can listen on Done to exit before the HTTP server waits for all active requests to complete.

type StartedEvent added in v4.1.3

type StartedEvent interface {
	AppEvent

	// OnStarted is called after the application has started successfully.
	// Use this method to perform post-start tasks, such as:
	//   - Starting background workers or schedulers
	//   - Sending startup notifications
	//   - Performing warm-up operations
	//   - Logging startup completion status
	//   - Triggering external system notifications
	// Note: At this point, the HTTP server is running and ready to accept requests.
	OnStarted()
}

StartedEvent is called after the application has started successfully. Implement this interface to perform post-start tasks.

type StartingEvent added in v4.1.3

type StartingEvent interface {
	AppEvent

	// OnStarting is called before the application starts.
	// Use this method to perform initialization tasks, such as:
	//   - Validating configuration
	//   - Initializing external connections (databases, caches, etc.)
	//   - Setting up monitoring and health checks
	//   - Performing pre-flight checks
	//   - Registering middleware or routes
	OnStarting()
}

StartingEvent is called before the application starts. Implement this interface to perform initialization tasks.

type StoppedEvent added in v4.1.3

type StoppedEvent interface {
	AppEvent

	// OnStopped is called after the HTTP server has stopped accepting new requests.
	// Use this method to perform cleanup tasks, such as:
	//   - Closing database connections
	//   - Stopping background workers or schedulers
	//   - Releasing resources
	// Args:
	//   - ctx: The context for the shutdown process, which can be used to perform graceful shutdown operations.
	OnStopped(ctx context.Context)
}

StoppedEvent is called after the HTTP server has stopped. Implement this interface to perform cleanup tasks.

Jump to

Keyboard shortcuts

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