mago

package module
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Feb 29, 2024 License: MIT Imports: 24 Imported by: 0

README

Mago

简介
  • 这是一个maliboot框架的golang版本。
  • 为了满足phper的使用习惯,组件设计、注解(基于google/wire)尽可能的使用了hyperf的许多规范。
  • 路由组件使用的是hertz,数据库组件使用了gorm
准备
  • golang >= 1.21
  • make
安装
go install github.com/maliboot/mago/mali@latest
创建新项目(模块)
  • 初始化项目
mkdir mago-skeleton
cd mago-skeleton
go mod init
  • 初始化maliboot骨架
cd mago-skeleton
mali init
  • 生成文件如下
.
├── Makefile
├── README.md
├── conf.yml
├── config
│   ├── autoload
│   ├── config.go
│   └── server.go
├── go.mod
├── internal
│   ├── adapter
│   ├── app
│   ├── client
│   ├── domain
│   └── infra
├── main.go
└── wire.go

批量生成CURD代码
  • 修改数据库配置 mago-skeleton/conf.yml
app_name: example
app_env: dev
server:
  http:
    port: 9501
logger:
  log_dir:
databases:
  ## example为数据库名称
  example:
    dsn: root:root@tcp(127.0.0.1:3306)/example?&parseTime=true&loc=Local
    singular_table: true
redis:
  host: 127.0.0.1
  port: 6379
  db: 1
  • 使用cli工具批量生成cola代码
cd mago-skeleton
## example为数据库名称,uss_message_tpl_var为表名。当无数据库名称时,会默认取`mago-skeleton/conf.yml`里第一个数据库
mali curd -t=example.uss_message_tpl_var

注意:当使用了注解路由时,需要在mago-skeleton/main.go中解开*Container注释。另外,mali curd默认生成的是注解路由

package main

import (
    "flag"
    
    "github.com/maliboot/mago"
    "github.com/maliboot/mago/config"
)

var (
	flagConf string
)

func init() {
	flag.StringVar(&flagConf, "f", "./conf.yml", "config path, eg: -f conf.yml")
}

func NewApp(
	c *config.Conf,
	hs *mago.Http,
	// container *Container, // ====================================使用注解路由时需要解开注释,否则编译报错
) *mago.App {
	// inject
	// container.Inject(hs) // =====================================使用注解路由时需要解开注释,否则编译报错

	// app
	return mago.New(
		c.AppName,
		[]mago.Server{hs},
	)
}

func main() {
	flag.Parse()

	// 配置
	c := config.NewConf(config.WithConfFile(flagConf))
	if err := c.Bootstrap(); err != nil {
		panic(err)
	}

	// start
	if err := initApp(c).Run(); err != nil {
		panic(err)
	}
}
依赖注入
  • 本框架使用了google/wire来进行代码依赖注入
  • 本框架的注解功能依赖于google/wire组件

项目运行前,需要在当前项目下运行依赖注入命令

cd mago-skeleton
make wire
使用
  • 运行服务
cd mago-skeleton
go run main

....
17:56:51.060784 engine.go:668: [Debug] HERTZ: Method=GET    absolutePath=/ping                     --> handlerName=agentserver/config.NewHttpServer.func1 (num=2 handlers)
17:56:51.060973 engine.go:668: [Debug] HERTZ: Method=POST   absolutePath=/ussMessageTplVar/create  --> handlerName=agentserver/internal/adapter/admin.(*UssMessageTplVarController).Create-fm (num=2 handlers)
17:56:51.060995 engine.go:668: [Debug] HERTZ: Method=DELETE absolutePath=/ussMessageTplVar/delete  --> handlerName=agentserver/internal/adapter/admin.(*UssMessageTplVarController).Delete-fm (num=2 handlers)
17:56:51.061004 engine.go:668: [Debug] HERTZ: Method=GET    absolutePath=/ussMessageTplVar/getById --> handlerName=agentserver/internal/adapter/admin.(*UssMessageTplVarController).GetById-fm (num=2 handlers)
17:56:51.061015 engine.go:668: [Debug] HERTZ: Method=GET    absolutePath=/ussMessageTplVar/listByPage --> handlerName=agentserver/internal/adapter/admin.(*UssMessageTplVarController).ListByPage-fm (num=2 handlers)
17:56:51.061160 engine.go:668: [Debug] HERTZ: Method=PUT    absolutePath=/ussMessageTplVar/update  --> handlerName=agentserver/internal/adapter/admin.(*UssMessageTplVarController).Update-fm (num=2 handlers)
17:56:51.062232 engine.go:396: [Info] HERTZ: Using network library=netpoll
17:56:51.062533 transport.go:115: [Info] HERTZ: HTTP server listening on address=[::]:9501
  • 浏览器访问 http://localhost:9501/ping

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Pagination

func Pagination(page int, perPage int) func(db *gorm.DB) *gorm.DB

Types

type AbstractAdapter

type AbstractAdapter struct {
}

func (AbstractAdapter) Response

func (a AbstractAdapter) Response(ctx *app.RequestContext, vo interface{})

type AbstractDataObject

type AbstractDataObject struct {
	DataObject `gorm:"-:all" json:"-"`
	ID         uint           `gorm:"primarykey" json:"id"`
	CreatedAt  DateTime       `json:"createdAt"`
	UpdatedAt  DateTime       `json:"updatedAt"`
	DeletedAt  gorm.DeletedAt `gorm:"index" json:"deletedAt"`
}

func (AbstractDataObject) PrimaryKey

func (do AbstractDataObject) PrimaryKey() string

func (AbstractDataObject) PrimaryValue

func (do AbstractDataObject) PrimaryValue() uint

type AbstractPageQuery

type AbstractPageQuery struct {
	PageSize   int `query:"pageSize"`
	PageIndex  int `query:"pageIndex"`
	Columns    []string
	OrderByRaw string
	Where      [][]string
}

type AbstractRepository

type AbstractRepository[D DataObject] struct {
	Conf *config.Conf
	Err  error
}

func (*AbstractRepository[D]) Create

func (d *AbstractRepository[D]) Create(do *D) int64

func (*AbstractRepository[D]) DB

func (d *AbstractRepository[D]) DB(do D) *gorm.DB

func (*AbstractRepository[D]) Delete

func (d *AbstractRepository[D]) Delete(ids []int) int64

func (*AbstractRepository[D]) Error

func (d *AbstractRepository[D]) Error() error

func (*AbstractRepository[D]) Find

func (d *AbstractRepository[D]) Find(id int) *D

func (*AbstractRepository[D]) First

func (d *AbstractRepository[D]) First(where [][]string, columns []string) *D

func (*AbstractRepository[D]) Get

func (d *AbstractRepository[D]) Get(where [][]string, columns []string, limit int) *[]D

func (*AbstractRepository[D]) Last

func (d *AbstractRepository[D]) Last(where [][]string, columns []string) *D

func (*AbstractRepository[D]) Paginate

func (d *AbstractRepository[D]) Paginate(pageQry *AbstractPageQuery) *PageVO[D]

Paginate 分页

func (*AbstractRepository[D]) Update

func (d *AbstractRepository[D]) Update(id int, do *D) int64

type AbstractViewObject

type AbstractViewObject struct {
	ViewObject `json:"-"`
}

type App

type App struct {
	Name string

	Servers []Server
	// contains filtered or unexported fields
}

func New

func New(name string, servers []Server) *App

func (*App) Run

func (a *App) Run() error

func (*App) Stop

func (a *App) Stop(sig os.Signal) error

type BoolVO

type BoolVO struct {
	AbstractViewObject
	Result bool `json:"result"`
}

type CmdRepo

type CmdRepo[D DataObject, E Entity] struct {
	AbstractRepository[D]
}

func (*CmdRepo[D, E]) Create

func (cr *CmdRepo[D, E]) Create(e *E) uint

func (*CmdRepo[D, E]) Delete

func (cr *CmdRepo[D, E]) Delete(id []int)

func (*CmdRepo[D, E]) Find

func (cr *CmdRepo[D, E]) Find(id int) *E

func (*CmdRepo[D, E]) Update

func (cr *CmdRepo[D, E]) Update(id int, e *E)

type CmdRepository

type CmdRepository[E Entity] interface {
	Error() error
	Find(id int) *E
	// Create 单条添加 返回: 自增ID
	Create(entity *E) uint
	Update(id int, e *E)
	Delete(id []int)
}

type DataObject

type DataObject interface {
	DatabaseName() string
	PrimaryKey() string
	PrimaryValue() uint
}

type DateTime

type DateTime struct {
	time.Time
}

func (*DateTime) MarshalJSON

func (t *DateTime) MarshalJSON() ([]byte, error)

func (*DateTime) Scan

func (t *DateTime) Scan(_ context.Context, _ *schema.Field, _ reflect.Value, fieldValue interface{}) error

func (*DateTime) UnmarshalJSON

func (t *DateTime) UnmarshalJSON(data []byte) error

func (*DateTime) Value

func (t *DateTime) Value(_ context.Context, _ *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

type EmptyVO

type EmptyVO struct {
	AbstractViewObject
}

type Entity

type Entity interface {
}

type Error

type Error interface {
	Code() ErrorCode
	HttpCode() int
	Msg() string
	WithMsg(string) Error
	Error() string
}

Error 普通错误

func NewError

func NewError(code ErrorCode) Error

type ErrorCode

type ErrorCode int

ErrorCode 错误码

var (
	// ErrNone 成功
	ErrNone ErrorCode = 200
	// ErrTokenInvalid token失效
	ErrTokenInvalid ErrorCode = 401000
	// ErrAuthLoginFailed 用户或密码错误
	ErrAuthLoginFailed ErrorCode = 401100
	// ErrAuthTokenInvalid 非法token
	ErrAuthTokenInvalid ErrorCode = 401200
	// ErrAuthSessionExpired token过期
	ErrAuthSessionExpired ErrorCode = 401300
	// ErrAuthUnauthorized 未认证,没有token
	ErrAuthUnauthorized ErrorCode = 401400
	// ErrAuthFailed 认证失败
	ErrAuthFailed ErrorCode = 401500
	// ErrAccessDenied 没有权限
	ErrAccessDenied ErrorCode = 403100
	// ErrAccessRefuse 拒绝客户端请求
	ErrAccessRefuse ErrorCode = 403200
	// ErrNoRepetitionOperation 禁止重复操作
	ErrNoRepetitionOperation ErrorCode = 403400
	// ErrBadRequest 客户端错误
	ErrBadRequest ErrorCode = 400100
	// ErrUriNotFound 资源未找到
	ErrUriNotFound ErrorCode = 404100
	// ErrInvalidParams 非法的参数
	ErrInvalidParams ErrorCode = 422100
	// ErrServerError 服务器异常
	ErrServerError ErrorCode = 500100
)

func (ErrorCode) HttpCode

func (e ErrorCode) HttpCode() int

func (ErrorCode) Int

func (e ErrorCode) Int() int

func (ErrorCode) String

func (e ErrorCode) String() string

type Http

type Http struct {
	*server.Hertz
	// contains filtered or unexported fields
}

func NewHttp

func NewHttp(c *config.Conf) *Http

func (*Http) Start

func (h *Http) Start(_ context.Context) error

func (*Http) Stop

func (h *Http) Stop(ctx context.Context) error

type IdVO

type IdVO struct {
	AbstractViewObject
	ID int `json:"id"`
}

type PageVO

type PageVO[T any] struct {
	AbstractViewObject
	PageSize   int  `json:"pageSize"`
	PageIndex  int  `json:"pageIndex"`
	TotalCount int  `json:"totalCount"`
	TotalPage  int  `json:"totalPage"`
	Items      *[]T `json:"items"`
}

type QryRepo

type QryRepo[D DataObject] struct {
	AbstractRepository[D]
}

func (QryRepo[D]) ListByPage

func (q QryRepo[D]) ListByPage(pageQry *AbstractPageQuery) *PageVO[D]

type QryRepository

type QryRepository[D DataObject] interface {
	Repository[D]
	ListByPage(id []int)
}

type Repository

type Repository[D DataObject] interface {
	Error() error
	DB(do D) *gorm.DB
	Find(id int) *D
	First(where [][]string, columns []string) *D
	Last(where [][]string, columns []string) *D
	Get(where [][]string, columns []string, limit int) *[]D
	Paginate(where [][]string, columns []string, orderByRaw string, page int, pageSize int) *PageVO[D]

	Create(do *D) int64
	Update(id int, do *D) int64
	Delete(ids []int) int64
	// contains filtered or unexported methods
}

type Response

type Response interface {
	// Success 成功响应
	Success(data interface{})
	// Failure 错误响应-默认错误信息
	Failure(code ErrorCode)
	// FailureMsg 错误响应-自定义错误信息
	FailureMsg(code ErrorCode, msg string)
	// FailureError 错误响应-根据Error
	FailureError(err error)
}

Response 统一响应格式

func NewResponse

func NewResponse(ctx *app.RequestContext) Response

type Server

type Server interface {
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

type StopError

type StopError struct {
}

type VO

type VO[T any] struct {
	Data   *T
	Err    error
	IsZero bool
}

func NewVO

func NewVO[T any](err error, data interface{}) *VO[T]

func NewZeroVO

func NewZeroVO[T any]() *VO[T]

func (*VO[T]) Body

func (vo *VO[T]) Body() interface{}

func (*VO[T]) Error

func (vo *VO[T]) Error() error

func (*VO[T]) Zero

func (vo *VO[T]) Zero() bool

type ViewObject

type ViewObject interface {
}

type ViewObjectTemplate

type ViewObjectTemplate interface {
	Zero
	Error() error
	Body() interface{}
}

type Zero

type Zero interface {
	Zero() bool
}

Directories

Path Synopsis
mali module

Jump to

Keyboard shortcuts

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