core

package module
v1.10.2 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2021 License: Apache-2.0 Imports: 16 Imported by: 0

README

core

framework core instance

controller

controller提供了基础类和实现方式

简单控制器实现:

func Index(c *gin.Context) {
	p := &Controller{}

	p.ProcessFun = func(c *base.Controller) base.IError {
		c.Data = "hello world"
		return nil
	}

	base.RunProcess(p, c)
}

自定义控制器实现:

type ExampleService struct {
	*core.Controller
}

func (ex *ExampleService) Process() core.IError {
	m :=  models.Order{}
	core.GetCore().GetDb("default").
		First(&m, "id=?",ex.Ctx.Param("id"))
	return nil
}
func Example(c *gin.Context) {
    base.RunProcess(&ExampleService{}, c)
}

model(可用配套mode生成器生成)

示例:

type Order struct {
	Id         uint64  `gorm:"column:id;type:bigint(20) unsigned" json:"id"`
	OrderId    uint64  `gorm:"column:order_id;type:bigint(20) unsigned" json:"order_id"`
	UserId     uint64  `gorm:"column:user_id;type:bigint(20) unsigned" json:"user_id"`
	Name       string  `gorm:"column:name;type:varchar(255)" json:"name"` // 订单内容的缩写或者主题描述
}

//get real primary key name
func (order *Order) GetKeyName() string {
	return "id"
}

//get real primary key name
func (order *Order) TableName() string {
	return "order"
}

session (1.1.4)

quote from github.com/grest/session

cache

开发中

Documentation

Index

Constants

View Source
const (
	SuccessCode     = "000000"
	FailCode        = "500"
	FailUnknownCode = "-1"
	FailJsonParse   = "-2"
	FailThirdLogin  = "-3"
	FailSecret      = "-4"
	FailParamsError = "-5"
	FailPostMax     = "-6"
	FailInternal    = "400"
)

Variables

View Source
var DefaultCodeMapping = CodeMapping{
	FailCode:        "操作失败",
	FailUnknownCode: "未知接口",
	FailJsonParse:   "JSON解析错误或者接口不存在",
	FailThirdLogin:  "第三方登录异常",
	FailSecret:      "加密参数错误",
	SuccessCode:     "操作成功",
	FailInternal:    "内部错误",
	FailParamsError: "参数不合法",
	FailPostMax:     "数据超过限制的大小",
}
View Source
var ResponseDataNil = struct {
}{}
View Source
var ServiceName string

Functions

func GetConfig added in v1.0.3

func GetConfig() *goconfig.ConfigFile

return instance config

func GetDb

func GetDb(name string) *gorm.DB

get db if exists

func GetGin added in v1.1.1

func GetGin() *gin.Engine

return instance gin core

func GetLog

func GetLog() log.Logger

return instance logger

func InitConfig

func InitConfig(path string)

func ResponseJson added in v1.10.2

func ResponseJson(c *Context, data interface{})

func ResponseStr added in v1.10.2

func ResponseStr(c *Context, str string)

func RunProcess

func RunProcess(controller IController, g *gin.Context)

run

func RunWithRequest added in v1.1.7

func RunWithRequest(req interface{}, g *gin.Context)

alias name, If run it, do not use RunProcess

Types

type CodeMapping

type CodeMapping map[string]string

func (CodeMapping) AddCodeInfo added in v1.10.2

func (cm CodeMapping) AddCodeInfo(code, msg string)

func (CodeMapping) GetCodeInfo

func (cm CodeMapping) GetCodeInfo(code string) string

type Context

type Context struct {
	*gin.Context
}

func GetContext

func GetContext(g *gin.Context) *Context

type Controller

type Controller struct {
	//log trackId
	TrackId string //访问id
	//the gin context
	Ctx *Context
	//response code, default success
	Code string

	//response data
	Data interface{} //output  from data raw data parse
	Req  interface{} //input params

	// middleware functions
	Middleware []ProcessFunc
	// logic functions
	ProcessFun ProcessFunc
	// contains filtered or unexported fields
}

func GetNewController added in v1.1.4

func GetNewController(g *gin.Context, req interface{}) *Controller

get new Controller demo:

c := GetNewController(g, &UserInfo{UserId:1})
c.ProcessFunc = func(con *Controller) IError {
	u := con.Req.(*Req)
	con.Data = u
}

func (*Controller) Decode

func (controller *Controller) Decode() IError

controller default Decode

func (*Controller) GetContext

func (controller *Controller) GetContext() *Context

get gin Content

func (*Controller) GetTrackId

func (controller *Controller) GetTrackId() string

get trackId

func (*Controller) Param added in v1.1.4

func (controller *Controller) Param(key string) string

router params with gin

func (*Controller) Process

func (controller *Controller) Process() IError

controller default Process

func (*Controller) Query added in v1.1.4

func (controller *Controller) Query(key string) string

query things with gin

func (*Controller) SetContext

func (controller *Controller) SetContext(c *Context)

set Context

func (*Controller) SetError

func (controller *Controller) SetError(err IError)

set error

func (*Controller) SetTrackId

func (controller *Controller) SetTrackId(id string)

set trackId

func (*Controller) Use added in v1.1.4

func (controller *Controller) Use(fn func(controller *Controller) IError)

type Core

type Core struct {
	Gin         *gin.Engine
	Log         log.Logger
	Config      *goconfig.ConfigFile
	Db          map[string]*gorm.DB
	Redis       map[string]*redis.Client
	Cache       map[string]ICache
	SessionType string
}

func GetCore

func GetCore() *Core

return instance

func (*Core) GetCache

func (gG *Core) GetCache(name string) ICache

get cache with name if not exists, fatal err

func (*Core) GetDb

func (gG *Core) GetDb(name string) *gorm.DB

get cache with name now only support gorm if not exists, fatal err

func (*Core) GetDefaultCache

func (gG *Core) GetDefaultCache() ICache

get default cache, if config set MYSQL_DSN

func (*Core) GetDefaultDb

func (gG *Core) GetDefaultDb() *gorm.DB

get default db, if config set MYSQL_DSN

func (*Core) GetDefaultRedis

func (gG *Core) GetDefaultRedis() *redis.Client

get default redis

func (*Core) GetRedis

func (gG *Core) GetRedis(name string) *redis.Client

get cache with name now only support gorm

func (*Core) GetSessionType

func (gG *Core) GetSessionType() string

return instance session

func (*Core) Group

func (gG *Core) Group(path string, handlers ...gin.HandlerFunc) *gin.RouterGroup

alias gin group

func (*Core) Handle

func (gG *Core) Handle(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes

alias gin Handle

func (*Core) SetLoggerFormat

func (gG *Core) SetLoggerFormat(format string)

set logger format params: %A - Time (2006-01-02T15:04:05.000Z) means all %T - Time (15:04:05 MST) %t - Time (15:04) %D - Date (2006/01/02) %d - Date (01/02/06) %L - Level (FNST, FINE, DEBG, TRAC, WARN, EROR, CRIT) %S - Source %M - Message Ignores unknown formats Recommended: "[%A] [%L] (%S) %M"

func (*Core) Use

func (gG *Core) Use(middleware ...gin.HandlerFunc) gin.IRoutes

alias gin Use

type Error

type Error struct {
	Code string
	Msg  string
	Err  interface{}
}

func NewError

func NewError(err error) Error

func NewErrorCode

func NewErrorCode(code string) Error

func NewErrorStr

func NewErrorStr(msg string) Error

func (Error) Error

func (err Error) Error() string

func (Error) GetCode

func (err Error) GetCode() string

func (Error) GetDetail

func (err Error) GetDetail() interface{}

func (Error) GetMsg

func (err Error) GetMsg() string

func (Error) IsNil

func (err Error) IsNil() bool

type ICache

type ICache interface {
	GetBytes(key string) []byte
	GetString(key string) string
	GetMap(key string) map[string]string
	GetList(key string) []string
	GetValue(key string) (string, error)

	SetValue(key string, val interface{}, ex time.Duration) error
	SetList(key string, val ...interface{}) error
	SetString(key, val string, ex time.Duration) error
	SetMap(key string, m map[string]string, ex time.Duration) error
	SetBytes(key string, b []byte, ex time.Duration) error
	Expire(key string, ex time.Duration)

	Command(args ...string) error
}

type IController

type IController interface {

	//set context(gin)
	SetContext(ctx *Context)
	//get context(gin)
	GetContext() *Context
	//self decode request obj
	//example:
	//get: ?a=b&c=d  => struct{A:b string `url:"a"`,C:d string `url:"c"`}
	//post(json): {"a":"b","c":"d"} struct{A:b string `url:"a"`,C:d string `url:"c"`}
	Decode() IError

	// processing business
	Process() IError

	//defer set error
	SetError(err IError)

	// Used to track distributed service link logs
	// recommend set it in query string
	GetTrackId() string

	// set trackId
	SetTrackId(id string)
	// contains filtered or unexported methods
}

It's a controller with a request process

type IError

type IError interface {
	GetCode() string
	GetMsg() string
	Error() string
	IsNil() bool
	GetDetail() interface{}
}

type IGetterSetter

type IGetterSetter interface {
	GetAttribute(key string) interface{}
	SetAttribute(key string, value interface{}) bool
	SetAttributes(mp map[string]interface{}) bool
	GetAttributes() map[string]interface{}

	GetAttrInt(key string) (int, error)
	GetAttrInt64(key string) (int64, error)
	GetAttrFloat(key string) (float32, error)
	GetAttrFloat64(key string) (float64, error)
	GetAttrUInt(key string) (uint, error)
	GetAttrUInt64(key string) (uint64, error)
	GetAttrBool(key string) (bool, error)
	GetAttrString(key string) (string, error)

	GetAttrTime(key string) (time.Time, error)
}

type IModel

type IModel interface {
	GetBytes() []byte
	GetString() string

	Update() bool
	Create() int64
	Delete() bool
	One(sql string, args ...interface{}) IGetterSetter
	List(sql string, args ...interface{}) []IGetterSetter

	TableName() string
	GetKeyName() string
	GetKey() int64
	GetName() string
}

type IModelStruct

type IModelStruct interface {
	TableName() string
	GetKeyName() string
}

type IResponse

type IResponse interface {
	GetBytes() []byte
	GetString() string
}

type IRouter

type IRouter interface {
}

func GetRouter

func GetRouter() IRouter

alias return instance gin core

type ProcessFunc

type ProcessFunc func(controller *Controller) IError

type Response

type Response struct {
	Code string      `json:"retcode"`
	Msg  string      `json:"desc"`
	Data interface{} `json:"biz"`
}

func (Response) GetBytes

func (res Response) GetBytes() []byte

func (Response) GetString

func (res Response) GetString() string

Jump to

Keyboard shortcuts

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