Categorygithub.com/gone-io/gone
modulepackage
1.0.8
Repository: https://github.com/gone-io/gone.git
Documentation: pkg.go.dev

# README

English  |  中文

license GoDoc Go Report Card codecov Build and Test Release Mentioned in Awesome Go

logo

Gone

What Is Gone?

Gone is a lightweight golang dependency injection framework; a series of Goners components are built in for rapid development of micro services.

plan

Features

  • Define the Goner interface to abstract dependencies.
  • Dependency Injection:
    • Inject Goners.
    • Inject function arguments.
  • Modular, detachable design.
  • Startup process control.
  • Testing support.
  • Built-in components:
    • goner/config, supports dependency injection of configuration parameters.
    • goner/tracer, adds TraceId to call chains, supports link tracing.
    • goner/logrus, goner/zap, supports log recording.
    • goner/gin, integrates with the gin framework to provide HTTP request parameter dependency injection.
    • goner/viper, used to parse various configuration files.
    • ...

Dependency Injection and Startup

Here's an example:

package main

import (
	"fmt"
	"github.com/gone-io/gone"
)

type Worker struct {
	gone.Flag // Anonymously embedding gone.Flag structure makes it a Goner, it can be injected as a dependency into other Goners or receive injections from other Goners.
	Name      string
}

func (w *Worker) Work() {
	fmt.Printf("I am %s, and I am working\n", w.Name)
}

type Manager struct {
	gone.Flag                         // Anonymously embedding gone.Flag structure makes it a Goner, it can be injected as a dependency into other Goners or receive injections from other Goners.
	*Worker   `gone:"manager-worker"` // Named injection GonerId="manager-worker" for Worker instance.
	workers   []*Worker               `gone:"*"` // Inject all Workers into an array.
}

func (m *Manager) Manage() {
	fmt.Printf("I am %s, and I am managing\n", m.Name)
	for _, worker := range m.workers {
		worker.Work()
	}
}

func main() {
	managerRole := &Manager{}

	managerWorker := &Worker{Name: "Scott"}
	ordinaryWorker1 := &Worker{Name: "Alice"}
	ordinaryWorker2 := &Worker{Name: "Bob"}

	gone.
		Prepare(func(cemetery gone.Cemetery) error {
			cemetery.
				Bury(managerRole).
				Bury(managerWorker, gone.GonerId("manager-worker")).
				Bury(ordinaryWorker1).
				Bury(ordinary, ordinaryWorker2)
			return nil
		}).
		// Run method supports dependency injection of parameters in its function.
		Run(func(manager *Manager) {
			manager.Manage()
		})
}

Summary:

  1. In the Gone framework, dependencies are abstracted as Goners, which can be injected into each other.
  2. By anonymously embedding the gone.Flag, the structure implements the Goner interface.
  3. Before starting, load all Goners into the framework using the Bury function.
  4. Use the Run method to start, where the function supports dependency injection of parameters.

Full Documentation

Let's use Gone to write a web service below!

🌐Web Service

package main

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

// Implement a Goner. What is a Goner? => https://goner.fun/guide/core-concept.html#goner-%E9%80%9D%E8%80%85
type controller struct {
	gone.Flag // Goner tag, when anonymously embedded, a structure implements Goner
	gone.RouteGroup `gone:"gone-gin-router"` // Inject root routes
}

// Implement the Mount method to mount routes; the framework will automatically execute this method
func (ctr *controller) Mount() gone.GinMountError {

	// Define request structure
	type Req struct {
		Msg string `json:"msg"`
	}

	// Register the handler for `POST /hello`
	ctr.POST("/hello", func(in struct {
		to  string `gone:"http,query"` // Inject http request Query parameter To
		req *Req   `gone:"http,body"`  // Inject http request Body
	}) any {
		return fmt.Sprintf("to %s msg is: %s", in.to, in.req.Msg)
	})

	return nil
}

func main() {
	// Start the service
	gone.Serve(func(cemetery gone.Cemetery) error {
		// Call the framework's built-in component, load the gin framework
		_ = goner.GinPriest(cemetery)

		// Bury a controller-type Goner in the cemetery
		// What does bury mean? => https://goner.fun/guide/core-concept.html#burying
		// What is a cemetery? => https://goner.fun/guide/core-concept.html#cemetery
		cemetery.Bury(&controller{})
		return nil
	})
}

Run the above code: go run main.go, the program will listen on port 8080. Test it using curl:

curl -X POST 'http://localhost:8080/hello' \
    -H 'Content-Type: application/json' \
	--data-raw '{"msg": "你好呀?"}'

The result is as follows:

{"code":0,"data":"to  msg is: 你好呀?"}

Quick Start

💡Concepts

The code we write is ultimately lifeless unless it is run. In Gone, components are abstracted as Goners, whose properties can inject other Goners. Before Gone starts, all Goners need to be buried in the cemetery; after Gone starts, all Goners will be resurrected to establish a Heaven, "everyone in Heaven is no longer incomplete, and what they want will be satisfied."

Core Concepts

🌰 More Examples:

Detailed examples can be found in the example directory, and more will be completed in the future.

🪜🧰🛠️ Component Library (👉🏻 More components are under development... 💪🏻 ヾ(◍°∇°◍)ノ゙ 🖖🏻)

  • goner/cumx, a wrapper for github.com/soheilhy/cmux, used to reuse the same port to implement multiple protocols;
  • goner/config, used to implement configuration for Gone-App
  • goner/gin, a wrapper for github.com/gin-gonic/gin, providing web services
  • goner/logrus, a wrapper for github.com/sirupsen/logrus, providing logging services
  • goner/tracer, providing log tracing, providing a unified tracer```markdown Id for the same request chain
  • goner/xorm, a wrapper for xorm.io/xorm, used for database access; when using it, import the database driver as needed;
  • goner/redis, a wrapper for github.com/gomodule/redigo, used for interacting with redis
  • goner/schedule, a wrapper for github.com/robfig/cron/v3, used for setting timers
  • emitter, encapsulates event handling, which can be used for DDD's Event Storm
  • goner/urllib, encapsulates github.com/imroc/req/v3, used for sending HTTP requests, and connects the traceId between server and client

📚Full Documentation

Contributing

If you have a bug report or feature request, you can open an issue, and pull requests are also welcome.

Contact

If you have questions, feel free to reach out to us in the following ways:

License

gone released under MIT license, refer LICENSE file.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author

# Functions

No description provided by the author
No description provided by the author
No description provided by the author
GetFuncName get function name.
No description provided by the author
GetInterfaceType get interface type.
No description provided by the author
No description provided by the author
IsCompatible t Type can put in goner.
No description provided by the author
New build new Heaven.
NewBuryMockCemeteryForTest make a new Cemetery for test.
NewBusinessError create a business error.
NewError create a error.
No description provided by the author
No description provided by the author
NewParameterError create a Parameter error.
No description provided by the author
No description provided by the author
No description provided by the author
PanicTrace used for getting panic stack.
No description provided by the author
No description provided by the author
Run A Gone Program; gone.Run vs gone.Serve: - gone.Run, The main goroutine never hangs, and the program is terminated when the main goroutine exits.
Serve Start for A Gone Server Program.
Test Use for writing test cases, refer to [example](https://github.com/gone-io/gone/blob/main/example/test/goner_test.go).
TestAt Use for writing test cases, test a specific ID of Goner.
TimeStat record the time of function and avg time.
ToError translate any type to An Error.
WrapNormalFnToProcess warp a func to Process.

# Constants

CannotFoundGonerById cannot find the Goner by the GonerId.
CannotFoundGonerByType cannot find the Goner by the Type.
DbRollForPanic error in rollback of DB transaction for panic.
GonerIdIsExisted Goner for the GonerId is existed.
IdConfig , The GonerId of Config Goner, which can be used for Injecting Configs from files or envs.
IdGoneCemetery , The GonerId of Cemetery Goner, which is Dependence Injection Key Goner, and which is injected by default.
IdGoneCMux , The GonerId of CMuxServer.
IdGoneConfigure , The GonerId of Configure Goner, which is used to read configs from devices.
IdGoneGin , IdGoneGinRouter , IdGoneGinProcessor, IdGoneGinProxy, IdGoneGinResponser, IdHttpInjector; The GonerIds of Goners in goner/gin, which integrates gin framework for web request.
GonerIds for Gone framework inner Goners.
GonerIds for Gone framework inner Goners.
GonerIds for Gone framework inner Goners.
GonerIds for Gone framework inner Goners.
IdGoneHeaven , The GonerId of Heaven Goner, which represents the program itself, and which is injected by default when it starts.
IdGoneLogger , The GonerId of Logger.
GonerIds for Gone framework inner Goners.
GonerIds for Gone framework inner Goners.
GonerIds for Gone framework inner Goners.
IdGoneRedisPool ,IdGoneRedisCache, IdGoneRedisKey, IdGoneRedisLocker, IdGoneRedisProvider The GonerIds of Goners in goner/redis, which integrates redis framework for cache and locker.
GonerIds for Gone framework inner Goners.
IdGoneReq , The GonerId of urllib.Client Goner, which is for request in goner/urllib.
IdGoneSchedule , The GonerId of Schedule Goner, which is for schedule in goner/schedule.
IdGoneTestKit , The GonerId of TestKit Goner, which is injected by default when using gone.Test or gone.TestAt to run test code.
IdGoneTracer ,The GonerId of Tracer.
IdGoneXorm , The GonerId of XormEngine Goner, which is for xorm engine.
GonerIds for Gone framework inner Goners.
InjectError error for dependence injection error.
MustHaveGonerId error for the GonerId is empty.
NotCompatible Goner is not compatible with the Type.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
ReplaceBuryIdParamEmpty Cemetery.ReplaceBury error for the GonerId is empty.
No description provided by the author
StartError Gone Start flow error.
StopError Gone Stop flow error.
No description provided by the author

# Variables

AfterStopSignalWaitSecond , The variable is used to set the time to wait after the stop signal is received.

# Structs

BError Business error implementation.
Context is a wrapper of gin.Context.
No description provided by the author
No description provided by the author

# Interfaces

No description provided by the author
BusinessError which has data, and which is used for Business error.
Cemetery which is for burying and reviving Goner.
CMuxServer cMux service,Used to multiplex the same port to listen for multiple protocols,ref:https://pkg.go.dev/github.com/soheilhy/cmux.
Configure use for get value of struct attribute tag by `gone:"config,${key}"`.
Error normal error.
No description provided by the author
Goner which is an abstraction of injectable objects: can inject other Goner, can be injected by other Goner.
No description provided by the author
No description provided by the author
InnerError which has stack, and which is used for Internal error.
No description provided by the author
No description provided by the author
Logger log interface.
Prophet A interface which has a AfterRevive method.
No description provided by the author
RouteGroup route group, which is a wrapper of gin.RouterGroup, and can be injected for mount router.
Tomb container of Goner.
Tracer Log tracking, which is used to assign a unified traceId to the same call link to facilitate log tracking.
No description provided by the author
No description provided by the author
No description provided by the author

# Type aliases

No description provided by the author
No description provided by the author
GonerId Goner's id.
No description provided by the author
No description provided by the author
Priest A function which has A Cemetery parameter, and return an error.
Process a function which has a Cemetery parameter, and return an error.
No description provided by the author
No description provided by the author
No description provided by the author