app

package module
v1.23.8 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 23 Imported by: 111

README

App Starter

Go project version issues Go Report Card Source graph License

Admin 端口(默认 :6060

应用启用 Web 后,默认会在独立端口启动 admin listener(与业务 Web 端口分离):

路径 说明
GET /pprof/* Go pprof
GET /metrics Prometheus metrics
POST /cl 运行时改日志级别,body 示例:{"level":"debug"}

关闭 admin:builder.DisableAdmin()
重新开启:builder.EnableAdmin()
改监听地址:builder.SetAdminListen(":7070")(只改地址,不改变 enable)
SetAdminListen("") 等同于默认常量 :6060
SetWebLogLevel("DEBUG") 时,admin 启动也会打印 Gin 路由列表(与业务 Web 一致)。

New() 默认 adminEnable=trueSetAdminListen / EnableAdminRoutes 仅在 enable 时生效(同 dbEnabledbDebug)。

注册业务 Admin API

通过 EnableAdminRoutes 挂自定义路由。参数是 server.Router不要直接依赖 gin)。

框架会先注册 /pprof/metricsPOST /cl,再执行业务 Setup,业务路由不会覆盖框架 API。

import (
    "github.com/lishimeng/app-starter"
    "github.com/lishimeng/app-starter/server"
)

func RegisterAdmin(root server.Router) {
    root.Get("/demo/ping", func(ctx server.Context) {
        ctx.JSON(map[string]any{"ok": true})
    })
}

func main() {
    app.New().Start(func(ctx context.Context, builder *app.ApplicationBuilder) error {
        builder.
            EnableAdminRoutes(RegisterAdmin).
            EnableWeb(":9527", YourAPIRouter)
        return nil
    })
}

访问示例:

GET  http://localhost:6060/demo/ping
GET  http://localhost:6060/metrics
POST http://localhost:6060/cl   {"level":"debug"}

完整示例见 examples/web-basic(含 admin.Register 与测试)。

URL 尾斜杠

默认关闭。调用 EnableStripTrailingSlash() 后,业务 Web 与 admin 在进入路由前会去掉路径末尾的 /(根路径 / 除外),类似 nginx rewrite,不发 301

builder.EnableStripTrailingSlash()
/api/        →  /api
/demo/ping/  →  /demo/ping
/            →  /(不变)

开启后请把路由注册成不带尾斜杠的形式(如 GET /apiGET /demo/ping)。关闭时沿用 Gin 默认的尾斜杠重定向(RedirectTrailingSlash)。

Delete tag

$ git tag -d v0.4.0
Deleted tag 'v0.4.0' (was f74dcae)

$ git push origin :v0.4.0
To https://github.com/lishimeng/app-starter.git
 - [deleted]         3.3.0.1492

Documentation

Index

Constants

View Source
const (
	Disable = iota
	Enable
)

Variables

View Source
var WithDefaultCallback = func(configName string) (f func(loader etc.Loader)) {
	return func(loader etc.Loader) {
		loader.SetFileSearcher(configName, ".").SetEnvPrefix("").SetEnvSearcher()
	}
}

Functions

func GetCache added in v1.4.0

func GetCache() (c cache.C)

func GetMqtt added in v1.10.0

func GetMqtt() (session mqtt.Session)

func GetNamedOrm added in v1.6.9

func GetNamedOrm(aliaName string) *persistence.OrmContext

func GetOrm

func GetOrm() *persistence.OrmContext

func GetRedisClient added in v1.23.0

func GetRedisClient() *redis.Client

func GetWebServer added in v1.12.6

func GetWebServer() (s *server.Server)

func InjectEnv added in v1.21.22

func InjectEnv(key, value string)

InjectEnv key, value

func InjectEnvStr added in v1.21.22

func InjectEnvStr(s string)

InjectEnvStr key=value

func Query added in v1.6.6

func Query(h func(ctx persistence.OrmContext) (err error)) (err error)

func QueryPage added in v1.12.6

func QueryPage[Model any, Dto any](pager *SimplePager[Model, Dto]) (err error)

QueryPage 单表分页查询(默认pageNo=1 pageSize=10)

func Transaction added in v1.6.6

func Transaction(h func(ctx persistence.TxContext) error) (err error)

func WithEmbed added in v1.23.4

func WithEmbed(fs embed.FS) func() http.FileSystem

WithEmbed adapts embed.FS to EnableStaticWeb (files at FS root → URL /, /css/..., etc.).

func WithEmbedRoot added in v1.23.4

func WithEmbedRoot(fsys fs.FS, root string) func() http.FileSystem

WithEmbedRoot serves a subdirectory inside fsys at web root. Use when embedding with //go:embed all:static and paths are static/index.html, etc.

Types

type Application

type Application interface {
	Start(buildHandler func(ctx context.Context, builder *ApplicationBuilder) error, onTerminate ...func(string)) error
}

func New

func New() (instance Application)

type ApplicationBuilder added in v1.2.1

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

func (*ApplicationBuilder) ComponentAfter added in v1.2.1

func (h *ApplicationBuilder) ComponentAfter(component func(context.Context) (err error)) *ApplicationBuilder

func (*ApplicationBuilder) ComponentBefore added in v1.2.1

func (h *ApplicationBuilder) ComponentBefore(component func(context.Context) (err error)) *ApplicationBuilder

func (*ApplicationBuilder) DisableAdmin added in v1.23.7

func (h *ApplicationBuilder) DisableAdmin() *ApplicationBuilder

DisableAdmin disables the admin HTTP listener (pprof / metrics / admin routes).

func (*ApplicationBuilder) EnableAdmin added in v1.23.7

func (h *ApplicationBuilder) EnableAdmin() *ApplicationBuilder

EnableAdmin enables the admin HTTP listener (default listen :6060). On by default when created via New(); call after DisableAdmin to turn it back on.

func (*ApplicationBuilder) EnableAdminRoutes added in v1.23.5

func (h *ApplicationBuilder) EnableAdminRoutes(setup server.AdminSetup) *ApplicationBuilder

EnableAdminRoutes registers custom routes on the admin listener. Effective only when admin is enabled. Framework routes (/pprof, /metrics, POST /cl) are registered first; setup runs after. setup uses server.Router (not gin).

func (*ApplicationBuilder) EnableCache added in v1.4.0

func (h *ApplicationBuilder) EnableCache(cacheOpts cache.Options) *ApplicationBuilder

func (*ApplicationBuilder) EnableDatabase added in v1.2.1

func (h *ApplicationBuilder) EnableDatabase(config persistence.BaseConfig,
	models ...interface{}) *ApplicationBuilder

func (*ApplicationBuilder) EnableDatabaseLog added in v1.12.6

func (h *ApplicationBuilder) EnableDatabaseLog() *ApplicationBuilder

EnableDatabaseLog 鎵撳紑orm log杈撳嚭

func (*ApplicationBuilder) EnableDatabaseView added in v1.21.11

func (h *ApplicationBuilder) EnableDatabaseView(views ...interface{}) *ApplicationBuilder

func (*ApplicationBuilder) EnableEmbedStaticWeb added in v1.23.4

func (h *ApplicationBuilder) EnableEmbedStaticWeb(fsys fs.FS, root ...string) *ApplicationBuilder

EnableEmbedStaticWeb is shorthand for EnableStaticWeb(WithEmbedRoot(fs, root...)).

func (*ApplicationBuilder) EnableMqtt added in v1.10.0

func (h *ApplicationBuilder) EnableMqtt(options ...mqtt.ClientOption) *ApplicationBuilder

func (*ApplicationBuilder) EnableOrmLog added in v1.7.3

func (h *ApplicationBuilder) EnableOrmLog() *ApplicationBuilder

func (*ApplicationBuilder) EnableRedis added in v1.23.0

func (h *ApplicationBuilder) EnableRedis(opts redis.Options) *ApplicationBuilder

func (*ApplicationBuilder) EnableStaticWeb added in v1.2.1

func (h *ApplicationBuilder) EnableStaticWeb(assetFile func() http.FileSystem) *ApplicationBuilder

func (*ApplicationBuilder) EnableStripTrailingSlash added in v1.23.6

func (h *ApplicationBuilder) EnableStripTrailingSlash() *ApplicationBuilder

EnableStripTrailingSlash rewrites paths like /api/ → /api on web and admin before routing (nginx-style, no 301). Off by default.

func (*ApplicationBuilder) EnableTokenValidator added in v1.9.0

func (h *ApplicationBuilder) EnableTokenValidator(builder TokenValidatorBuilder) *ApplicationBuilder

EnableTokenValidator 楠岃瘉Token锛屼娇鐢≧edisTokenValidator鍓嶉渶瑕乪nableCache

func (*ApplicationBuilder) EnableWeb added in v1.2.1

func (h *ApplicationBuilder) EnableWeb(listen string, components ...server.Component) *ApplicationBuilder

func (*ApplicationBuilder) HealthyHandler added in v1.5.0

func (h *ApplicationBuilder) HealthyHandler(handler func() int) *ApplicationBuilder

func (*ApplicationBuilder) LoadConfig added in v1.2.1

func (h *ApplicationBuilder) LoadConfig(config interface{}, callback func(etc.Loader)) (err error)

func (*ApplicationBuilder) PrintVersion added in v1.7.3

func (h *ApplicationBuilder) PrintVersion() *ApplicationBuilder

func (*ApplicationBuilder) ReadyHandler added in v1.5.0

func (h *ApplicationBuilder) ReadyHandler(handler func() int) *ApplicationBuilder

func (*ApplicationBuilder) SetAdminListen added in v1.23.7

func (h *ApplicationBuilder) SetAdminListen(listen string) *ApplicationBuilder

SetAdminListen sets the admin listen address only (does not enable/disable). Empty listen uses server.DefaultAdminListen (":6060"). Effective only when adminEnable is true (same pattern as dbDebug under dbEnable).

func (*ApplicationBuilder) SetMonitorPrefix added in v1.5.0

func (h *ApplicationBuilder) SetMonitorPrefix(prefix string) *ApplicationBuilder

func (*ApplicationBuilder) SetWebLogLevel added in v1.3.3

func (h *ApplicationBuilder) SetWebLogLevel(lvl string) *ApplicationBuilder

type BasePager added in v1.12.6

type BasePager struct {
	Total     int `json:"total"`
	TotalPage int `json:"totalPage"` // 总页数
	PageSize  int `json:"pageSize"`  // 页面大小
	PageNum   int `json:"pageNum"`   // 页号
	More      int `json:"more"`      // 是否有下一页
}

func (*BasePager) Offset added in v1.12.6

func (p *BasePager) Offset() int

func (*BasePager) SetTotal added in v1.21.12

func (p *BasePager) SetTotal(count int64) int

type OperatorChangeInfo added in v1.10.15

type OperatorChangeInfo struct {
	OperatorInfo
	UpdateOperator int `gorm:"column:moperator"`
}

OperatorChangeInfo 不可与 OperatorInfo 同时使用

type OperatorInfo added in v1.10.15

type OperatorInfo struct {
	CreateOperator int `gorm:"column:coperator"`
}

type Pager added in v1.1.3

type Pager[Dto any] struct {
	BasePager
	Data []Dto `json:"items,omitempty"`
}

type PagerResponse added in v1.1.3

type PagerResponse struct {
	Response
}

type Pk added in v1.9.11

type Pk struct {
	// ID
	Id int `gorm:"primaryKey;autoIncrement;column:id"`
}

type Pk64 added in v1.22.1

type Pk64 struct {
	Id int64 `gorm:"primaryKey;autoIncrement;column:id"`
}

Pk64 主键为 bigint / bigserial 时使用;不可与 Pk 同时使用

type Response added in v1.1.3

type Response struct {
	Code    int         `json:"code,omitempty"`
	Success string      `json:"success,omitempty"`
	Message string      `json:"message,omitempty"`
	Status  interface{} `json:"status,omitempty"`
}

type ResponseWrapper added in v1.11.4

type ResponseWrapper struct {
	Response
	Data any `json:"data,omitempty"`
}

type SimplePager added in v1.12.6

type SimplePager[DbModel any, Dto any] struct {
	Pager[Dto]
	DataSet      []DbModel
	Transform    func(src DbModel, dst *Dto)
	OrderExp     []string // GORM order expressions, e.g. "id desc"
	QueryBuilder func(tx persistence.TxContext) persistence.Query
}

type TableChangeInfo added in v1.9.11

type TableChangeInfo struct {
	Status int `gorm:"column:status;default:0"`
	TableInfo
	UpdateTime time.Time `gorm:"autoUpdateTime;column:mtime"`
}

TableChangeInfo 不可与 TableInfo 同时使用

type TableInfo added in v1.9.11

type TableInfo struct {
	CreateTime time.Time `gorm:"autoCreateTime;column:ctime"`
}

type Tenant added in v1.10.15

type Tenant struct {
	Org int `gorm:"column:org"` // org为tenant标记
}

Tenant 多租户

type TenantPk added in v1.10.15

type TenantPk struct {
	Pk
	Tenant
}

TenantPk 不可与 Pk / Pk64 同时使用

type TenantPk64 added in v1.22.1

type TenantPk64 struct {
	Pk64
	Tenant
}

TenantPk64 不可与 Pk / Pk64 同时使用

type TokenValidatorBuilder added in v1.9.0

type TokenValidatorBuilder func(injectFunc TokenValidatorInjectFunc)

type TokenValidatorInjectFunc added in v1.9.0

type TokenValidatorInjectFunc func(storage token.Storage)

Directories

Path Synopsis
application
api
examples
web-basic command
midware
driver/mysql
Package mysql provides MysqlConfig and registers the GORM mysql dialector on import.
Package mysql provides MysqlConfig and registers the GORM mysql dialector on import.
driver/postgres
Package postgres provides PostgresConfig and registers the GORM postgres dialector on import.
Package postgres provides PostgresConfig and registers the GORM postgres dialector on import.
driver/sqlite
Package sqlite provides SqliteConfig and registers the GORM sqlite dialector on import.
Package sqlite provides SqliteConfig and registers the GORM sqlite dialector on import.
sse

Jump to

Keyboard shortcuts

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