gone

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 10, 2024 License: GPL-3.0 Imports: 11 Imported by: 13

README

English  |  中文

logo

gone framework license GoDoc

The most Spring programmer-friendly Golang framework, dependency injection, integrates Web.

Quick Start

1. Example of DI code
package main

import "github.com/gone-io/gone"

type AGoner struct {
	gone.Flag //tell the framework that this struct is a Goner
	Name      string
}

func (g *AGoner) Say() {
	println("I am the AGoner, My name is", g.Name)
}

type BGoner struct {
	gone.Flag         //tell the framework that this struct is a Goner
	a         *AGoner `gone:"*"` //Gone Tag `gone` tell the framework that this field will be injected by the framework
}

// AfterRevive executed After the Goner is revived; After `gone.Run`, gone framework detects the AfterRevive function on goners and runs it.
func (g *BGoner) AfterRevive() gone.AfterReviveError {
	g.a.Say()

	return nil
}

// Priest Responsible for putting Goners that need to be used into the framework
func Priest(cemetery gone.Cemetery) error {
	cemetery.Bury(&AGoner{Name: "Injected Goner"})
	cemetery.Bury(&BGoner{})
	return nil
}

func main() {

	// start gone framework
	gone.Run(Priest)
}

Run the above code, and the screen will print: "I am the AGoner, My name is Injected Goner".

2. Example of Web Service code
package main

import (
	"github.com/gone-io/gone"
	"github.com/gone-io/gone/goner"
	"github.com/gone-io/gone/goner/gin"
)

type controller struct {
	gone.Flag
	router gin.IRouter `gone:"gone-gin-router"` //inject gin router Goner, which is wrapped of `gin.Engine`
}

// Mount use for  mounting the router of gin framework
func (ctr *controller) Mount() gin.MountError {
	ctr.router.GET("/ping", func(c *gin.Context) (any, error) {
		return "hello", nil
	})
	return nil
}

func NewController() gone.Goner {
	return &controller{}
}

func Priest(cemetery gone.Cemetery) error {
	//Load the Goner of the gin web framework into the system
	_ = goner.GinPriest(cemetery)

	//Load the business Goner
	cemetery.Bury(NewController())
	return nil
}

func main() {
	
	//Gone.Server is used to start a service, and the program will block until the service ends.
	gone.Serve(Priest)
}

Run the code, it will listen on port 8080, and the screen will print: img.png

Test http request:

curl http://localhost:8080/ping

You will get the response:

{"code":0,"data":"hello"}

And prints on the screen: img.png

The story of the Gone framework

The word "gone" in English can mean "left," "departed," "absent," "missing," or "dead." Therefore, those managed by the Gone framework are referred to as "Goners".
There exists a mysterious graveyard where the "Goners" are laid to rest, and their souls 😇 ascend to heaven. Only the designated priests of heaven can bury the "Goners" in the graveyard...
The gates of heaven are slowly opening...

Concept
  • Heaven: 🕊☁️,The running program.
  • Heaven.Start: Means the program starts to run;Goner lives forever until the heaven end (the program terminates).
  • Heaven.Stop: The heaven end; the program terminates.
  • Cemetery: 🪦, Graveyard, Used to manage Tomb.
  • Cemetery.Bury: Put Goner in Tomb and bury him in the graveyard.
  • Cemetery.revive: Resurrect the Goner and elevate it to heaven; for the Goner, it signifies the completion of attribute injection (or assembly).
  • Tomb: ⚰️,The place where the Goner is buried;Which is a container for the Goner, and the Goner can be injected into other Goner.
  • Priest: ✝️,A special function responsible for burying the Goner.
  • Goner: 💀, A interface, which is an abstraction of injectable objects: can inject other Goner, can be injected by other Goner.
  • Prophet: A interface, If a Goner is a Prophet, after being resurrected, AfterRevive() gone.AfterReviveError will be executed.
  • Prophet.AfterRevive: A function, which allows Prophet to regain control of the program after resurrection. It is crucial that the execution of this function occurs swiftly, without causing any program interruptions. "The key to glimpsing heaven can only be temporary."
  • Angel: 𓆩♡𓆪 ,Both Start (gone.Cemetery) error and Stop (gone.Cemetery) error methods need to be implemented at the same time, just like angel wings.
  • Angel.Start: A function. Angel left wing, which means to start work; which can be used to start some long-running service goroutines.
  • Angel.Stop: A function. Angel right wing means the end of work. which can be used to send a stop signal to the service goroutines and clean up some resources.
  • Vampire: 🧛🏻‍,The Goner that implements Suck(conf string, v reflect.Value) gone.SuckError is termed as Vampire. Objects that are not classified as Goner can be injected into the Goner property through the Suck method. A vampire is an ominous entity that might annihilate the entire kingdom of heaven. Although the blood-sucking behavior can alter the standard behavior of dependency injection and add new features to the framework, it may also introduce circular dependencies, potentially harming the system.
  • Vampire.Suck: A function. Vampire "bloodsucking behavior"; before a vampire is injected into the Goner, its "bloodsucking behavior" is triggered so that it can allow other objects to inject into the Goner rather than itself.
Four kinds of Goner.
  • Goner

ordinary Goner, which can be used to abstract Service, Controller, Client and other common components in program.

  • Prophet Goner

The method AfterRevive (Cemetery, Tomb) ReviveAfterError, it will be called after ascending to the Kingdom of Heaven.

example: urllib, a Goner that comes with the framework, which encapsulates github.com/imroc/req/v3, for sending http requests.

  • Angel Goner

Angels will assume certain responsibilities in heaven: in the start phase, the angel's Start method will be called; in the stop phase, the angel's Stop method will be called; Therefore, angels are suitable for abstracting components which need to be started and to be stopped.

example: xorm, a Goner that comes with the framework, which encapsulates xorm.io/xorm, for connecting mysql server.

  • Vampire Goner

Vampires, who have the ability to suck blood, can read / write marked fields through the Suck method, and can abstract the behavior of certain attributes of other components.

example: config, a Goner that comes with the framework, for injecting config values in config files to Goner Attributes.

Documentation

Index

Constants

View Source
const (
	// GonerIdIsExisted GonerId 不存在
	GonerIdIsExisted = 1001 + iota

	// CannotFoundGonerById 通过GonerId查找Goner失败
	CannotFoundGonerById

	// CannotFoundGonerByType 通过类型查找Goner失败
	CannotFoundGonerByType

	//NotCompatible 类型不兼容
	NotCompatible

	//ReplaceBuryIdParamEmpty 替换性下葬,GonerId不能为空
	ReplaceBuryIdParamEmpty
)

错误代码:gone框架内部错误代码编码空间:1001~1999

View Source
const (
	// IdGoneHeaven 天堂组件的ID,代码了程序本身,Gone程序启动时默认注入
	IdGoneHeaven = "gone-heaven"

	// IdGoneCemetery 坟墓组件的ID,是完成依赖注入的关键组件,Gone程序启动时默认注入
	IdGoneCemetery = "gone-cemetery"

	//IdGoneTestKit 测试箱,调用 gone.Test 或者 gone.TestAt 时,会将测试箱注入到程序;非测试代码中不应该注入该组件
	IdGoneTestKit = "gone-test-kit"

	//IdConfig 配置 Goner 的ID,提过能配置能力
	IdConfig = "config"
	//IdGoneConfigure 配置器 Goner 的ID
	IdGoneConfigure = "gone-configure"
	// IdGoneTracer Tracer Goner 的ID,提供日志追踪能力
	IdGoneTracer = "gone-tracer"
	// IdGoneLogger 日志 Goner 的ID,用于日志打印
	IdGoneLogger = "gone-logger"

	//IdGoneCumx [cmux Goner](/goner/cmux#Server) ID
	IdGoneCumx = "gone-cumx"

	//IdGoneGin Gin相关的组件ID,可以使用 [goner.GinPriest](goner#GinPriest) 牧师函数批量安葬
	IdGoneGin          = "gone-gin"
	IdGoneGinRouter    = "gone-gin-router"
	IdGoneGinProcessor = "gone-gin-processor"
	IdGoneGinProxy     = "gone-gin-proxy"
	IdGoneGinResponser = "gone-gin-responser"

	//IdGoneXorm Xorm Goner 的ID,封装了xorm,用于操作数据库;使用 [goner.XormPriest](goner#XormPriest) 牧师函数安葬
	IdGoneXorm = "gone-xorm"

	//IdGoneRedisPool redis pool goner; redis 相关 Goner,使用 [goner.RedisPriest](goner#RedisPriest) 牧师函数安葬
	IdGoneRedisPool     = "gone-redis-pool"
	IdGoneRedisCache    = "gone-redis-cache"
	IdGoneRedisKey      = "gone-redis-key"
	IdGoneRedisLocker   = "gone-redis-locker"
	IdGoneRedisProvider = "gone-redis-provider"

	// IdGoneSchedule 定时器Goner;使用 [goner.SchedulePriest](goner#SchedulePriest) 牧师函数安葬
	IdGoneSchedule = "gone-schedule"

	IdGoneReq = "gone-urllib"
)

Gone框架中的内置组件ID

Variables

View Source
var AfterStopSignalWaitSecond = 5

AfterStopSignalWaitSecond 收到停机信号后,退出程序等待的时间

Functions

func ExecuteInjectWrapFn added in v0.2.1

func ExecuteInjectWrapFn(fn *reflect.Value) (results []any)

func GetFuncName added in v0.0.20

func GetFuncName(f any) string

GetFuncName 获取某个函数的名字

func GetInterfaceType added in v0.0.17

func GetInterfaceType[T any](t *T) reflect.Type

GetInterfaceType 获取接口的类型

func InjectWrapFn added in v0.2.1

func InjectWrapFn(cemetery Cemetery, fn any) (*reflect.Value, error)

func NewSimpleLogger added in v0.0.8

func NewSimpleLogger() (Goner, GonerId)

func PanicTrace

func PanicTrace(kb int) []byte

PanicTrace 用于获取调用者的堆栈信息

func Run

func Run(priests ...Priest)

Run 开始运行一个Gone程序;`gone.Run` 和 `gone.Serve` 的区别是: 1. gone.Serve启动的程序,主协程会调用 Heaven.WaitEnd 挂起等待停机信号,可以用于服务程序的开发 2. gone.Run启动的程序,主协程则不会挂起,运行完就结束,适合开发一致性运行的代码

    // 定义加载服务的Priest函数
	func LoadServer(c Cemetery) error {
		c.Bury(goneXorm.New())
		c.Bury(goneGin.New())
		return nil
	}

    // 加载组件的Priest函数
	func LoadComponent(c Cemetery) error {
		c.Bury(componentA.New())
		c.Bury(componentB.New())
	}

	gone.Run(LoadServer, LoadComponent)//开始运行

func Serve added in v0.0.6

func Serve(priests ...Priest)

Serve 开始服务,参考[Run](#Run)

func Test added in v0.0.6

func Test[T Goner](fn func(T), priests ...Priest)

Test 用于编写测试用例,参考[示例](https://github.com/gone-io/gone/blob/main/example/test/goner_test.go)

func TestAt added in v0.0.6

func TestAt[T Goner](id GonerId, fn func(T), priests ...Priest)

TestAt 用于编写测试用例,测试某个特定ID的Goner

Types

type AfterReviveError added in v0.0.6

type AfterReviveError error

type Angel

type Angel interface {
	Goner
	Start(Cemetery) error
	Stop(Cemetery) error
}

type Cemetery

type Cemetery interface {
	Goner

	//Bury a Goner to the Cemetery
	Bury(Goner, ...GonerId) Cemetery

	//ReplaceBury replace the Goner in the Cemetery with a new Goner
	ReplaceBury(Goner, GonerId) error

	//ReviveOne Revive a Goner from the Cemetery
	ReviveOne(goner any) (deps []Tomb, err error)

	//ReviveAllFromTombs Revive all Goner from the Cemetery
	ReviveAllFromTombs() error

	//GetTomById return the Tomb by the GonerId
	GetTomById(GonerId) Tomb

	//GetTomByType return the Tombs by the GonerType
	GetTomByType(reflect.Type) []Tomb
	// contains filtered or unexported methods
}

Cemetery which is for burying and reviving Goner

type DefaultLogger added in v0.2.1

type DefaultLogger interface {
	SetLogger(logger Logger) SetLoggerError
}

type Error

type Error interface {
	error
	Msg() string
	Code() int
}

Error normal error

func CannotFoundGonerByIdError

func CannotFoundGonerByIdError(id GonerId) Error

func CannotFoundGonerByTypeError

func CannotFoundGonerByTypeError(t reflect.Type) Error

func GonerIdIsExistedError

func GonerIdIsExistedError(id GonerId) Error

func NewError

func NewError(code int, msg string) Error

func NewInnerError added in v0.0.6

func NewInnerError(code int, msg string) Error

func NotCompatibleError

func NotCompatibleError(a reflect.Type, b reflect.Type) Error

func ReplaceBuryIdParamEmptyError

func ReplaceBuryIdParamEmptyError() Error

type Flag

type Flag struct{}

type Goner

type Goner interface {
	// contains filtered or unexported methods
}

Goner which is an abstraction of injectable objects: can inject other Goner, can be injected by other Goner.

type GonerId

type GonerId string

GonerId Goner's id

func GetGoneDefaultId

func GetGoneDefaultId(goner Goner) GonerId

type Heaven

type Heaven interface {

	//Install do some prepare before start
	Install() Heaven

	//WaitEnd make program block until heaven stop
	WaitEnd() Heaven

	//End send a signal to heaven to stop
	End() Heaven

	//Start make heaven start
	Start() Heaven
	Stop() Heaven

	//GetHeavenStopSignal return a channel to listen the signal of heaven stop
	GetHeavenStopSignal() <-chan struct{}

	//BeforeStart add a hook function which will execute before start;
	BeforeStart(Process) Heaven

	//AfterStart add a hook function which will execute after start
	AfterStart(Process) Heaven

	//BeforeStop add a hook function which will execute before stop
	BeforeStop(Process) Heaven

	//AfterStop add a hook function which will execute after stop
	AfterStop(Process) Heaven
}

func New

func New(priests ...Priest) Heaven

New 新建Heaven; Heaven 代表了一个应用程序;

type InnerError added in v0.0.6

type InnerError interface {
	Error
	Stack() []byte
}

InnerError which has stack

type Logger

type Logger interface {
	Tracef(format string, args ...any)
	Errorf(format string, args ...any)
	Warnf(format string, args ...any)
	Infof(format string, args ...any)
}

type Preparer added in v0.2.1

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

func Prepare added in v0.2.1

func Prepare(priests ...Priest) *Preparer

func (*Preparer) AfterStart added in v0.2.1

func (p *Preparer) AfterStart(fn any) *Preparer

func (*Preparer) AfterStop added in v0.2.1

func (p *Preparer) AfterStop(fn any) *Preparer

func (*Preparer) BeforeStart added in v0.2.1

func (p *Preparer) BeforeStart(fn any) *Preparer

func (*Preparer) BeforeStop added in v0.2.1

func (p *Preparer) BeforeStop(fn any) *Preparer

func (*Preparer) Run added in v0.2.1

func (p *Preparer) Run()

func (*Preparer) Serve added in v0.2.1

func (p *Preparer) Serve()

type Priest

type Priest func(cemetery Cemetery) error

Priest A function which has A Cemetery parameter, and return an error. use for Burying Goner

type Process

type Process func(cemetery Cemetery) error

Process a function which has a Cemetery parameter, and return an error. use for hooks

func WrapNormalFnToProcess added in v0.2.1

func WrapNormalFnToProcess(fn any) Process

type Prophet added in v0.0.6

type Prophet interface {
	Goner

	//AfterRevive A method which will execute after revive
	// Deprecate: use `AfterRevive() error` instead
	AfterRevive() AfterReviveError
}

Prophet A interface which has a AfterRevive method

type Prophet2 added in v0.2.1

type Prophet2 interface {
	Goner

	//AfterRevive A method which will execute after revive
	AfterRevive() error
}

type SetLoggerError added in v0.0.17

type SetLoggerError error

type SuckError

type SuckError error

type TestHeaven

type TestHeaven[T Goner] interface {
	Heaven
	WithId(id GonerId) TestHeaven[T]
	WithPriest(priests ...Priest) TestHeaven[T]
	Run()
}

func TestKit

func TestKit[T Goner](fn func(T)) TestHeaven[T]

type Tomb

type Tomb interface {
	SetId(GonerId) Tomb
	GetId() GonerId
	GetGoner() Goner
	GonerIsRevive(flags ...bool) bool
}

Tomb container of Goner

func NewTomb

func NewTomb(goner Goner) Tomb

type Tombs

type Tombs []Tomb

func (Tombs) GetTomByType

func (tombs Tombs) GetTomByType(t reflect.Type) (filterTombs []Tomb)

type Vampire

type Vampire interface {
	Goner
	Suck(conf string, v reflect.Value) SuckError
}

Directories

Path Synopsis
example
di
x
app Module
http-server Module
gin
tools

Jump to

Keyboard shortcuts

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