luchen

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2025 License: MIT Imports: 37 Imported by: 22

README

luchen 基于 go-kit 封装的微服务框架

luchen 是一个基于 go-kit 封装的微服务框架。秉承 go-kit 的分层设计思想,同时集成了丰富的工程实践设计。它提供了一套完整的解决方案,旨在简化服务开发、提高开发效率,让开发者更专注于业务逻辑的实现。

无论是构建复杂的微服务系统还是简单的单体应用,luchen 都能满足你的需求。

开始这个项目的时候,我女儿刚出生,取名【路辰】,所以将项目名命名为luchen

特性

  • 快速开发: 封装了工程实践中常用的组件和工具,可以快速构建和部署服务。
  • 多协议支持: 支持 HTTP、gRPC 传输协议,适用于不同的场景和需求,轻松扩展更多协议支持,无需改动业务层代码。
  • 分层设计: 保留 go-kit 的分层设计思想,包括端点(Endpoints)、传输(Transport)、服务(Service)等层次,保证了代码的可维护性和可扩展性。
  • 微服务支持: 使用 go-kit 实现微服务化架构,支持服务注册、发现、负载均衡、限流、熔断等功能。
  • 完善的工具链支持,一键生成 crud 和接口实现代码。

快速体验

启动 helloworld 服务

$ cd _example/helloworld
$ go run main.go

请求服务接口

$ curl 'http://localhost:8080/say-hello' \
--header 'Content-Type: application/json' \
--data '{
    "name": "fengjx"
}'
{"Msg":"hello fengjx"}
示例

文档

详细的文档请查阅: https://luchen.fun

相关项目

  • lucky 基于luchen实现的快速开发平台-后端工程
  • lucky-web lucky前端工程
  • lc cli 工具
  • daox 数据库访问辅助类库

技术交流

加我微信拉你进群,请备注:luchen

版权声明

你可以自由使用本项目用于个人、商业用途及二次开发,但请注明源码出处。

Documentation

Index

Constants

View Source
const (
	HeaderRspMeta = "X-Rsp-Meta"
)
View Source
const (
	// TraceIDHeader traceID header key
	TraceIDHeader = "X-Trace-ID"
)

Variables

View Source
var (
	// ErrSystem 系统错误
	ErrSystem = NewErrnoWithHttpCode(http.StatusInternalServerError, "")
	// ErrNotImplemented 未实现
	ErrNotImplemented = NewErrnoWithHttpCode(http.StatusNotImplemented, "")
	// ErrBadGateway 网关错误
	ErrBadGateway = NewErrnoWithHttpCode(http.StatusBadGateway, "")
	// ErrServiceUnavailable 服务不可用
	ErrServiceUnavailable = NewErrnoWithHttpCode(http.StatusServiceUnavailable, "")
	// ErrGatewayTimeout 网关超时
	ErrGatewayTimeout = NewErrnoWithHttpCode(http.StatusGatewayTimeout, "")

	// ErrBadRequest 参数错误
	ErrBadRequest = NewErrnoWithHttpCode(http.StatusBadRequest, "")
	// ErrUnauthorized 未授权
	ErrUnauthorized = NewErrnoWithHttpCode(http.StatusUnauthorized, "")
	// ErrForbidden 没有权限访问
	ErrForbidden = NewErrnoWithHttpCode(http.StatusForbidden, "")
	// ErrNotFound 资源不存在
	ErrNotFound = NewErrnoWithHttpCode(http.StatusNotFound, "")
)
View Source
var (
	// ErrNoServer 没有可用的服务节点
	ErrNoServer = errors.New("no server available")
)
View Source
var GlobalGRPCMiddlewares []Middleware

GlobalGRPCMiddlewares 全局 GRPC 中间件

View Source
var GlobalHTTPMiddlewares []Middleware

GlobalHTTPMiddlewares 全局 HTTP 中间件

View Source
var (
	// TraceIDCtxKey traceID context key
	TraceIDCtxKey = traceIDKey{}
)

Functions

func AddBeforeStopHook

func AddBeforeStopHook(handler func())

AddBeforeStopHook 注册服务停止前回调函数

func DoStopHook

func DoStopHook()

DoStopHook 执行服务停止前的回调函数

func LogMiddleware added in v1.1.0

func LogMiddleware(next endpoint.Endpoint) endpoint.Endpoint

LogMiddleware 错误日志堆栈打印,放在第一个执行

func Marshaller added in v1.1.0

func Marshaller(ctx context.Context) marshal.Marshaller

Marshaller 返回当前请求的 marshaller

func MustLoadConfig

func MustLoadConfig[T any](files ...string) T

MustLoadConfig 加载配置,异常时 panic

func MustNewEtcdV3Client

func MustNewEtcdV3Client(address []string) etcdv3.Client

MustNewEtcdV3Client 创建 etcdv3.Client

func NewDefaultEtcdV3Client

func NewDefaultEtcdV3Client() etcdv3.Client

NewDefaultEtcdV3Client 创建默认 etcdv3.Client etcd 地址通过 GetDefaultEtcdAddress 方法获得

func RecoverHTTPMiddleware added in v1.1.0

func RecoverHTTPMiddleware(next http.Handler) http.Handler

RecoverHTTPMiddleware 恢复 panic

func Start

func Start(svrs ...Server)

Start 启动服务

func Stop

func Stop()

Stop 停止服务

func TraceGRPC

func TraceGRPC(ctx context.Context, md metadata.MD) (context.Context, string)

TraceGRPC 返回 traceID grpc 请求携带 traceID 处理

func TraceGRPCClient

func TraceGRPCClient(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error

TraceGRPCClient grpc client 携带 traceID

func TraceHTTPMiddleware

func TraceHTTPMiddleware(next http.Handler) http.Handler

TraceHTTPMiddleware 链路跟踪

func TraceHTTPRequest

func TraceHTTPRequest(r *http.Request) (*http.Request, string)

TraceHTTPRequest 返回 traceID http 请求携带 traceID 处理

func TraceID

func TraceID(ctx context.Context) string

TraceID 从 context 获得 TraceID

func TraceIDOrNew

func TraceIDOrNew(ctx context.Context) string

TraceIDOrNew 从 context 获得 TraceID,取不到则创建

func UseGlobalGRPCMiddleware added in v1.1.0

func UseGlobalGRPCMiddleware(m ...Middleware)

UseGlobalGRPCMiddleware 注册全局 GRPC 中间件 中间件的执行顺序与注册顺序相同,先注册的中间件先执行

func UseGlobalHTTPMiddleware added in v1.1.0

func UseGlobalHTTPMiddleware(m ...Middleware)

UseGlobalHTTPMiddleware 注册全局 HTTP 中间件 中间件的执行顺序与注册顺序相同,先注册的中间件先执行

func WithTraceID

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID context 注入 traceID

func WriteError added in v1.1.0

func WriteError(ctx context.Context, w http.ResponseWriter, err error)

WriteError write error

Types

type AccessLog

type AccessLog interface {
	Print(map[string]any)
}

func NewAccessLog

func NewAccessLog(maxSizeMB int, maxBackups int, maxDay int) AccessLog

NewAccessLog 创建一个 AccessLog

type AccessLogOpt

type AccessLogOpt struct {
	ContextFields map[string]GetValueFromContext
	PrintResp     bool
	AccessLog     AccessLog
	MaxDay        int
}

type Balancer

type Balancer[T any] interface {
	// Refresh 刷新服务节点
	Refresh(services []*T)
	// Pick 选择服务节点
	Pick() (*T, error)
}

Balancer 选择器负载策略

type Endpoint

type Endpoint = endpoint.Endpoint

Endpoint alias for endpoint.Endpoint

func EndpointChain added in v1.1.0

func EndpointChain(e Endpoint, middlewares ...Middleware) Endpoint

EndpointChain Endpoint 中间件包装

type EndpointDefine added in v1.1.0

type EndpointDefine struct {
	Name        string       // 端点名称
	Path        string       // http 请求路径
	ReqType     reflect.Type // 请求类型
	RspType     reflect.Type // 响应类型
	Endpoint    Endpoint     // 端点处理器
	Middlewares []Middleware // 中间件
}

EndpointDefine 端点定义信息

type Errno

type Errno struct {
	HttpCode int    `json:"http_code"` // http 状态码
	Code     int    `json:"code"`      // 错误码
	Msg      string `json:"msg"`       // 错误信息
	Detail   string `json:"detail"`    // 详细错误信息
	Cause    error  `json:"-"`         // 原始错误,不序列化
}

Errno 错误编码定义 Code: 0 - 500,使用 http 状态码规范,大于 1000 的错误码,表示自定义错误码

func FromError added in v1.1.0

func FromError(err error) (*Errno, bool)

FromError 从错误中提取 Errno

func NewErrno added in v1.1.0

func NewErrno(httpcode int, code int, msg string) *Errno

NewErrno 创建错误编码

func NewErrnoWithHttpCode added in v1.1.0

func NewErrnoWithHttpCode(httpcode int, msg string) *Errno

NewErrnoWithHttpCode 根据 http 状态码创建错误编码

func WrapError added in v1.1.0

func WrapError(err error) *Errno

WrapError 包装普通错误为 Errno

func (*Errno) Error

func (e *Errno) Error() string

Error 实现 error 接口

func (*Errno) Format added in v1.1.0

func (e *Errno) Format(s fmt.State, verb rune)

Format 实现 fmt.Formatter 接口,支持更丰富的格式化输出

func (*Errno) GetDetail added in v1.1.0

func (e *Errno) GetDetail() string

GetDetail 获取详细错误信息

func (*Errno) IsClientError added in v1.1.0

func (e *Errno) IsClientError() bool

IsClientError 是否是客户端错误

func (*Errno) IsServerError added in v1.1.0

func (e *Errno) IsServerError() bool

IsServerError 是否是服务端系统错误

func (*Errno) Unwrap added in v1.1.0

func (e *Errno) Unwrap() error

Unwrap 实现 errors.Unwrap 接口

func (*Errno) WithCause added in v1.1.0

func (e *Errno) WithCause(err error) *Errno

WithCause 设置原始错误

func (*Errno) WithDetail added in v1.1.0

func (e *Errno) WithDetail(detail string) *Errno

WithDetail 设置详细错误信息

func (*Errno) WithMsg added in v1.1.0

func (e *Errno) WithMsg(msg string) *Errno

WithMsg 设置错误信息

type EtcdV3Registrar

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

EtcdV3Registrar 基于 etcd 实现的服务注册器

func NewEtcdV3Registrar

func NewEtcdV3Registrar(servers ...Server) *EtcdV3Registrar

NewEtcdV3Registrar 创建一个服务注册器 servers 需要注册的服务

func (*EtcdV3Registrar) Deregister

func (r *EtcdV3Registrar) Deregister()

Deregister 摘除服务注册信息并停止服务

func (*EtcdV3Registrar) Register

func (r *EtcdV3Registrar) Register()

Register 启动并注册服务到 etcd

type EtcdV3Selector

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

EtcdV3Selector 基于etcd3的节点查询器

func GetEtcdV3Selector

func GetEtcdV3Selector(serviceName string) *EtcdV3Selector

GetEtcdV3Selector 创建 EtcdV3Selector

func (*EtcdV3Selector) Close

func (s *EtcdV3Selector) Close()

Close 关闭查询器

func (*EtcdV3Selector) Next

func (s *EtcdV3Selector) Next() (*ServiceInfo, error)

Next 返回一个服务节点信息

type GRPCClient

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

GRPCClient 支持服务发现的 grpc client

func GetGRPCClient

func GetGRPCClient(serviceName string, opts ...grpc.DialOption) *GRPCClient

GetGRPCClient 创建grpc客户端

func (*GRPCClient) Invoke

func (c *GRPCClient) Invoke(ctx context.Context, method string, args any, reply any, opts ...grpc.CallOption) error

Invoke 实现 Invoke 接口,支持服务发现

func (*GRPCClient) NewStream

func (c *GRPCClient) NewStream(ctx context.Context, desc *grpc.StreamDesc, method string, opts ...grpc.CallOption) (grpc.ClientStream, error)

NewStream begins a streaming RPC.

type GRPCServer

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

GRPCServer grpc server 实现

func NewGRPCServer

func NewGRPCServer(opts ...ServerOption) *GRPCServer

NewGRPCServer 创建 grpc server opts 查看 ServerOptions

func (GRPCServer) GetServiceInfo

func (s GRPCServer) GetServiceInfo() *ServiceInfo

func (*GRPCServer) RegisterService

func (s *GRPCServer) RegisterService(desc *grpc.ServiceDesc, impl any)

RegisterService 注册 grpc 接口实现

func (*GRPCServer) Start

func (s *GRPCServer) Start() error

Start 停止服务

func (*GRPCServer) Stop

func (s *GRPCServer) Stop() error

Stop 停止服务

type GRPCTransportServer

type GRPCTransportServer = grpctransport.Server

GRPCTransportServer grpc transport server

func NewGRPCTransportServer added in v1.0.3

func NewGRPCTransportServer(
	def *EndpointDefine,
	options ...grpctransport.ServerOption,
) *GRPCTransportServer

NewGRPCTransportServer grpc handler 绑定 endpoint

type GetValueFromContext

type GetValueFromContext func(ctx context.Context) any

GetValueFromContext 从 context 中获取值

type HTTPServer

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

HTTPServer http server 实现

func NewHTTPServer

func NewHTTPServer(opts ...ServerOption) *HTTPServer

NewHTTPServer 创建 http server opts 查看 ServerOptions

func (HTTPServer) GetServiceInfo

func (s HTTPServer) GetServiceInfo() *ServiceInfo

func (*HTTPServer) Handle added in v1.1.0

func (s *HTTPServer) Handle(def *EndpointDefine)

Handle 注册 http 路由

func (*HTTPServer) Mux added in v1.1.0

func (s *HTTPServer) Mux() *xin.Mux

Mux 获取路由复用器

func (*HTTPServer) Start

func (s *HTTPServer) Start() error

Start 启动服务

func (*HTTPServer) Stop

func (s *HTTPServer) Stop() error

Stop 停止服务

type HTTPTransportServer

type HTTPTransportServer = httptransport.Server

HTTPTransportServer go-kit http transport server

func NewHTTPTransportServer added in v1.0.3

func NewHTTPTransportServer(
	def *EndpointDefine,
	options ...httptransport.ServerOption,
) *HTTPTransportServer

NewHTTPTransportServer http handler 绑定 endpoint

type Header struct {
	Protocol    string
	Method      string
	Endpoint    string
	Host        string
	CLientIP    string
	TraceID     string
	StartTime   time.Time
	ContentType string
}

func GetHeader added in v1.1.0

func GetHeader(ctx context.Context) *Header

GetHeader 返回当前请求的 header

type LogGRPCErrorHandler

type LogGRPCErrorHandler struct {
}

LogGRPCErrorHandler grpc 接口错误处理器

func NewLogGRPCErrorHandler

func NewLogGRPCErrorHandler() *LogGRPCErrorHandler

NewLogGRPCErrorHandler 创建 LogGRPCErrorHandler

func (*LogGRPCErrorHandler) Handle

func (h *LogGRPCErrorHandler) Handle(ctx context.Context, err error)

Handle 统一错误处理

type Middleware

type Middleware = endpoint.Middleware

Middleware alias for endpoint.Endpoint

func AccessMiddleware

func AccessMiddleware(opt *AccessLogOpt) Middleware

AccessMiddleware 请求日志

type Protocol

type Protocol string

Protocol 服务协议

const (

	// ProtocolHTTP http 协议
	ProtocolHTTP Protocol = "http"
	// ProtocolGRPC grpc 协议
	ProtocolGRPC Protocol = "grpc"
)

type RegisterHandler

type RegisterHandler func(grpcServer *grpc.Server)

RegisterHandler 注册 grpc handler

type RoundRobinBalancer

type RoundRobinBalancer[T any] struct {
	// contains filtered or unexported fields
}

RoundRobinBalancer 基于 RoundRobin 算法的 Balancer 实现

func NewRoundRobinBalancer

func NewRoundRobinBalancer[T any]() *RoundRobinBalancer[T]

NewRoundRobinBalancer 创建 NewRoundRobinBalancer 实例

func (*RoundRobinBalancer[T]) Pick

func (b *RoundRobinBalancer[T]) Pick() (*T, error)

Pick 选择一个服务节点

func (*RoundRobinBalancer[T]) Refresh

func (b *RoundRobinBalancer[T]) Refresh(services []*T)

Refresh 刷新节点列表

type Selector

type Selector interface {
	Next() (*ServiceInfo, error)
}

Selector 节点查询

type SelectorBuilder

type SelectorBuilder func(serviceName string) Selector

SelectorBuilder Selector 构造函数

type Server

type Server interface {
	Start() error
	Stop() error
	GetServiceInfo() *ServiceInfo
}

Server server 接口定义

type ServerOption

type ServerOption func(*ServerOptions)

ServerOption grpc server 选项赋值

func WithServerAddr

func WithServerAddr(addr string) ServerOption

WithServerAddr server 监听地址

func WithServerMetadata

func WithServerMetadata(md map[string]any) ServerOption

WithServerMetadata server 注册信息 metadata,单体服务无需关注

func WithServiceName

func WithServiceName(serviceName string) ServerOption

WithServiceName server 名称,在微服务中作为一组服务名称标识,单体服务则无需关注

type ServerOptions

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

ServerOptions server 选项

type ServiceInfo

type ServiceInfo struct {
	ID       string         `json:"id"`
	Name     string         `json:"name"`
	Protocol Protocol       `json:"protocol"`
	Addr     string         `json:"addr"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

ServiceInfo 服务节点信息

Directories

Path Synopsis
docs module

Jump to

Keyboard shortcuts

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