g

package module
v1.3.6 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2025 License: MIT Imports: 9 Imported by: 37

README

English  |  中文

goner/g Component

The goner/g component is one of the core components of the Gone framework, providing a series of fundamental interfaces and functionalities including log tracing, service discovery, load balancing and other core features.

Core Features

1. Log Tracing (CtxLogger)

The CtxLogger interface is used for log tracing, which can assign a unified traceId to the same call chain for easier log tracing and issue troubleshooting.

type CtxLogger interface {
    Ctx(ctx context.Context) gone.Logger
}

Usage example:

type user struct {
    gone.Flag
    logger CtxLogger `gone:"*"` // Inject Logger
}

func (u *user) Use(ctx context.Context) (err error) {
    // Get traceId from openTelemetry context and inject into logger
    logger := u.logger.Ctx(ctx)

    logger.Infof("hello")

    return
}
2. Service Discovery (ServiceDiscovery)

The ServiceDiscovery interface provides service discovery and monitoring functionality, allowing clients to find available service instances and monitor instance changes.

type ServiceDiscovery interface {
    // GetInstances returns all instances of the specified service
    GetInstances(serviceName string) ([]Service, error)

    // Watch creates a channel to receive updates about service instance changes
    Watch(serviceName string) (ch <-chan []Service, stop func() error, err error)
}
3. Load Balancing (LoadBalancer)

The LoadBalancer interface provides load balancing functionality for selecting appropriate instances from available service instances.

type LoadBalancer interface {
    // GetInstance returns a service instance based on load balancing strategy
    GetInstance(ctx context.Context, serviceName string) (Service, error)
}

Load balancing strategy interface:

type LoadBalanceStrategy interface {
    // Select chooses a service instance from the provided instance list
    Select(ctx context.Context, instances []Service) (Service, error)
}
4. Service Instance (Service)

The Service interface represents a service instance in the service registry, providing basic information about the service instance including identity, location, metadata and health status.

type Service interface {
    // GetName returns the service name of the instance
    GetName() string

    // GetIP returns the IP address of the instance
    GetIP() string

    // GetPort returns the port number of the instance
    GetPort() int

    // GetMetadata returns metadata associated with the service instance
    GetMetadata() Metadata

    // GetWeight returns the weight of the instance
    GetWeight() float64

    // IsHealthy returns the health status of the service instance
    IsHealthy() bool
}

Create service instance:

// NewService creates a new service instance
func NewService(name, ip string, port int, meta Metadata, healthy bool, weight float64) Service

Usage Recommendations

  1. When using log tracing, it's recommended to obtain CtxLogger instance through dependency injection and use the Ctx() method to inject context information when processing requests.

  2. When implementing service discovery, you can choose appropriate service discovery components (such as Consul, Etcd, etc.) to implement the ServiceDiscovery interface.

  3. When using load balancing, you can implement custom LoadBalanceStrategy according to actual needs, such as round-robin, random, weight-based strategies.

  4. Service instance metadata can be used to store additional configuration information such as version numbers, deployment environments, etc.

  • goner/balancer: Provides concrete implementation of load balancer
  • goner/consul: Service discovery implementation based on Consul
  • goner/etcd: Service discovery implementation based on Etcd

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func App added in v1.1.0

func App(name string, loadFuncs ...gone.LoadFunc) (app *gone.Application)

App creates or retrieves an application instance with the specified name and loading functions name: Application name loadFuncs: Loading functions Returns: Application instance

func BuildOnceLoadFunc added in v1.0.9

func BuildOnceLoadFunc(ops ...*LoadOp) gone.LoadFunc

BuildOnceLoadFunc builds a loading function that executes only once ops: List of LoadOps to execute Returns: Loading function that ensures single execution

func ErrorPrinter added in v1.2.1

func ErrorPrinter(logger gone.Logger, err error, msg string, args ...any)

func GetComponentByName added in v1.0.10

func GetComponentByName[T any](keeper gone.GonerKeeper, name string) (T, error)

GetComponentByName gets a component of specified type by name T: Component type to get keeper: Component manager name: Component name Returns: Found component instance and possible error

func GetLocalIps added in v1.0.9

func GetLocalIps() []net.IP

GetLocalIps gets all non-loopback IPv4 addresses of the local machine Returns: List of all available IPv4 addresses

func GetServerValue added in v1.0.11

func GetServerValue(instance Service) string

func GetServiceId added in v1.0.11

func GetServiceId(instance Service) string

func IsLoaded added in v1.2.1

func IsLoaded(loader gone.Loader, goner gone.Goner) bool

func NamedThirdComponentLoadFunc added in v1.0.10

func NamedThirdComponentLoadFunc[T any](name string, component T) gone.LoadFunc

NamedThirdComponentLoadFunc creates a named third-party component loading function T: Component type name: Component name component: Third-party component instance Returns: Loading function for third-party components

func PanicIfErr added in v1.2.1

func PanicIfErr(err error)

PanicIfErr panics if an error occurs

func Recover added in v1.0.9

func Recover(logger gone.Logger)

Recover captures and logs panics to prevent program crashes logger: Logger for recording panic information

func ResultError added in v1.2.1

func ResultError[T any](t *T, err error, msg string) (*T, error)

ResultError return wrapped error if error occurs, otherwise returns the result

func SingLoadProviderFunc added in v1.0.10

func SingLoadProviderFunc[P any, T any](fn gone.FunctionProvider[P, T], options ...gone.Option) gone.LoadFunc

SingLoadProviderFunc creates a loading function for singleton Provider P: Provider's parameter type T: Component type provided by Provider fn: Function to create components options: Loading options Returns: Loading function that ensures single loading Deprecated since v2.1.0, use gone.BuildSingProviderLoadFunc instead:

Types

type Cmux

type Cmux interface {
	MatchFor(ProtocolType) net.Listener
	GetAddress() string
}

type Controller added in v1.2.1

type Controller interface {
	// Mount Route mount interface, this interface will be called before the service starts, the implementation of this function should usually return `nil`
	Mount() MountError
}

type CtxLogger added in v1.2.1

type CtxLogger interface {
	Ctx(ctx context.Context) gone.Logger
}

CtxLogger Log tracking, which is used to assign a unified traceId to the same call link to facilitate log tracking. Examples:

type user struct {
	gone.Flag
	logger CtxLogger `gone:"*"` //Inject  Logger
}

func (u *user) Use(ctx context.Context) (err error) {
	// get traceId from openTelemetry context and inject it into the logger
	logger := u.logger.Ctx(ctx)

	logger.Infof("hello")

	return
}

type DoLocker

type DoLocker interface {
	LockAndDo(key string, fn func(), lockTime, checkPeriod time.Duration) (err error)
}

type HTTPDoer added in v1.0.8

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

type HandlerFunc added in v1.2.1

type HandlerFunc any

type IRoutes added in v1.2.1

type IRoutes interface {
	Use(...HandlerFunc) IRoutes

	Handle(string, string, ...HandlerFunc) IRoutes
	Any(string, ...HandlerFunc) IRoutes
	GET(string, ...HandlerFunc) IRoutes
	POST(string, ...HandlerFunc) IRoutes
	DELETE(string, ...HandlerFunc) IRoutes
	PATCH(string, ...HandlerFunc) IRoutes
	PUT(string, ...HandlerFunc) IRoutes
	OPTIONS(string, ...HandlerFunc) IRoutes
	HEAD(string, ...HandlerFunc) IRoutes
}

type IsOtelLogLoaded added in v1.2.1

type IsOtelLogLoaded bool

type IsOtelMeterLoaded added in v1.2.1

type IsOtelMeterLoaded bool

type IsOtelTracerLoaded added in v1.2.1

type IsOtelTracerLoaded bool

type LoadBalanceStrategy added in v1.0.9

type LoadBalanceStrategy interface {
	// Select chooses a service instance from the provided list of instances
	// Returns an error if selection fails or no suitable instance is found
	Select(ctx context.Context, instances []Service) (Service, error)
}

LoadBalanceStrategy defines the interface for implementing different load balancing algorithms It allows for custom instance selection logic based on various factors

type LoadBalancer added in v1.0.9

type LoadBalancer interface {
	// GetInstance returns a service instance based on the load balancing strategy
	// Returns an error if no instance is available or selection fails
	GetInstance(ctx context.Context, serviceName string) (Service, error)
}

LoadBalancer provides load balancing functionality for service instances It selects an appropriate instance from available service instances

type LoadOp added in v1.0.9

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

LoadOp struct encapsulates loading operations goner: Component to be loaded options: Loading options f: Loading function

func F added in v1.0.9

func F(loadFunc gone.LoadFunc) *LoadOp

F creates a LoadOp containing a loading function loadFunc: Custom loading function Returns: New LoadOp instance

func L added in v1.0.9

func L(g gone.Goner, options ...gone.Option) *LoadOp

L creates a LoadOp for loading components g: Component to be loaded options: Loading options Returns: New LoadOp instance

type Metadata

type Metadata map[string]string

Metadata represents a map of key-value pairs for storing service instance metadata

type MountError added in v1.2.1

type MountError error

type ProtocolType

type ProtocolType int
const (
	GRPC  ProtocolType = 0x01
	HTTP1 ProtocolType = 0x01 << 1
)

type Service

type Service interface {
	// GetName returns the service name of the instance
	GetName() string

	GetIP() string

	GetPort() int

	// GetMetadata returns the metadata associated with the service instance
	GetMetadata() Metadata

	GetWeight() float64

	// IsHealthy returns the health status of the service instance
	IsHealthy() bool
}

Service represents a service instance in the service registry It provides basic information about a service instance including its identity, location, metadata, and health status

func NewService added in v1.0.9

func NewService(name, ip string, port int, meta Metadata, healthy bool, weight float64) Service

func ParseService added in v1.0.11

func ParseService(serverValue string) (Service, error)

type ServiceDiscovery added in v1.0.9

type ServiceDiscovery interface {
	// GetInstances returns all instances of a specified service
	// Returns an error if the service discovery fails
	GetInstances(serviceName string) ([]Service, error)

	// Watch creates a channel that receives updates when the service instances change
	// Returns an error if watching fails
	Watch(serviceName string) (ch <-chan []Service, stop func() error, err error)
}

ServiceDiscovery provides methods for discovering and monitoring service instances It allows clients to find available service instances and watch for changes

type ServiceRegistry added in v1.0.9

type ServiceRegistry interface {
	// Register adds a new service instance to the registry
	// Returns an error if registration fails
	Register(instance Service) error

	// Deregister removes a service instance from the registry
	// Returns an error if de registration fails
	Deregister(instance Service) error
}

ServiceRegistry provides methods for service registration and management It handles service instance registration, deregistration, and heartbeat updates

type Tracer

type Tracer interface {

	//SetTraceId to set `traceId` to the calling function. If traceId is an empty string, an automatic one will
	//be generated. TraceId can be obtained by using the GetTraceId () method in the calling function.
	SetTraceId(traceId string, fn func())

	//GetTraceId Get the traceId of the current goroutine
	GetTraceId() string

	//Go Start a new goroutine instead of `go func`, which can pass the traceId to the new goroutine.
	Go(fn func())
}

Tracer Log tracking, which is used to assign a unified traceId to the same call link to facilitate log tracking.

Directories

Path Synopsis
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

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