luchen

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: May 3, 2024 License: Apache-2.0 Imports: 45 Imported by: 15

README

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

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

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

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

特性

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

快速体验

启动 helloworld 服务

$ cd _example/helloworld
$ go run main.go

请求服务接口

$ curl http://localhost:8080/say-hello?name=fjx
hello: fjx
示例

文档

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

生态

  • lca 基于 amis 开发的低代码后台系统
  • glca 基于luchen开发 lca 后台服务实现
  • lc glca 命令行工具,可以快速生成通用代码

作者

个人微信

Documentation

Index

Constants

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

Variables

View Source
var (
	// HTTPRequestHeaderCtxKey context http header
	HTTPRequestHeaderCtxKey = httpRequestHeaderKey{}
	// HTTPRequestURLCtxKey context http url
	HTTPRequestURLCtxKey = httpRequestURLKey{}

	// NopHTTPRequestDecoder 不需要解析请求参数
	NopHTTPRequestDecoder = httptransport.NopRequestDecoder
)
View Source
var (
	// ErrNoServer 没有可用的服务节点
	ErrNoServer = errors.New("no server available")
)
View Source
var (
	// ErrSystem 系统错误
	ErrSystem = &Errno{Code: 500, HTTPCode: 500, Msg: "系统错误"}
)
View Source
var (
	// TraceIDCtxKey traceID context key
	TraceIDCtxKey = traceIDKey{}
)

Functions

func AddBeforeStopHook

func AddBeforeStopHook(handler func())

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

func DecodeHTTPJSONRequest

func DecodeHTTPJSONRequest[T any](ctx context.Context, r *http.Request) (interface{}, error)

DecodeHTTPJSONRequest 解析 http request body json 参数

func DecodeHTTPParamRequest

func DecodeHTTPParamRequest[T any](ctx context.Context, r *http.Request) (interface{}, error)

DecodeHTTPParamRequest 解析 http request query 和 form 参数

func DecodePB

func DecodePB[T any](_ context.Context, req interface{}) (interface{}, error)

DecodePB protobuf 解码

func Dir added in v1.0.4

func Dir(root string, listDirectory bool) fs.FS

Dir 返回 http.FileSystem 实现 listDirectory = true,返回 http.Dir() listDirectory = false,返回 onlyFilesFS,不会显示目录

func DoStopHook

func DoStopHook()

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

func EncodeHTTPJSONResponse

func EncodeHTTPJSONResponse(wrapper DataWrapper) httptransport.EncodeResponseFunc

EncodeHTTPJSONResponse http 返回json数据 wrapper 对数据重新包装

func EncodePB

func EncodePB[T any](_ context.Context, resp interface{}) (interface{}, error)

EncodePB protobuf 编码

func FileHandler added in v1.0.4

func FileHandler(prefix string, fs fs.FS) http.Handler

FileHandler 处理静态文件请求 参考 http.StripPrefix

func HandlerChain

func HandlerChain(h http.Handler, middlewares ...HTTPMiddleware) http.Handler

HandlerChain 使用中间件包装 handler

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 OnlyFilesFS added in v1.0.4

func OnlyFilesFS(fs fs.FS, listDirectory bool, root string) fs.FS

OnlyFilesFS 将 fs.FS 包装为 onlyFilesFS root 可以设置根路径,文件将会从根路径开始查找

func RequestEndpoint

func RequestEndpoint(ctx context.Context) string

RequestEndpoint 请求端点

func RequestMethod

func RequestMethod(ctx context.Context) string

RequestMethod 请求方法

func RequestProtocol

func RequestProtocol(ctx context.Context) string

RequestProtocol 请求协议

func RequestStartTime

func RequestStartTime(ctx context.Context) time.Time

RequestStartTime 请求开始时间

func ShouldBind

func ShouldBind(r *http.Request, obj any) error

ShouldBind 从参数url参数和form表单解析参数

func ShouldBindJSON

func ShouldBindJSON(r *http.Request, obj any) error

ShouldBindJSON 从body解析json

func Start

func Start(svrs ...Server)

Start 启动服务

func StartWithContext

func StartWithContext(ctx context.Context, svrs ...Server)

StartWithContext 启动服务

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 WithTraceID

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

WithTraceID context 注入 traceID

Types

type AccessLog

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

func NewAccessLog

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

NewAccessLog 创建一个 AccessLog

type AccessLogOpt

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

type Balancer

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

Balancer 选择器负载策略

type DataWrapper

type DataWrapper func(data any) any

DataWrapper 对数据重新组装

type Endpoint

type Endpoint = endpoint.Endpoint

Endpoint alias for endpoint.Endpoint

type Errno

type Errno struct {
	Code     int    // 自定义错误码
	HTTPCode int    // http 错误码
	Msg      string // 错误信息
}

Errno 错误编码定义

func (*Errno) Error

func (e *Errno) Error() string

Error 实现 error 接口

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(reg RegisterHandler) *GRPCServer

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

NewGRPCTransportServer grpc handler 绑定 endpoint

type Gateway

type Gateway struct {
	*httputil.ReverseProxy
	// contains filtered or unexported fields
}

Gateway 网关服务

func NewGateway

func NewGateway(cfg GatewayConfig, opts ...GatewayOption) *Gateway

NewGateway 创建 gateway 服务

func (Gateway) GetServiceInfo

func (s Gateway) GetServiceInfo() *ServiceInfo

func (*Gateway) RegPattern

func (g *Gateway) RegPattern(patterns ...Pattern)

RegPattern 注册匹配模式

func (*Gateway) ServeHTTP

func (g *Gateway) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP 重新定义 request context

func (*Gateway) Start

func (g *Gateway) Start() error

Start 启动服务

func (*Gateway) Stop

func (g *Gateway) Stop() error

Stop 停止服务

type GatewayConfig

type GatewayConfig struct {
	ServerName      string  `json:"server-name"`             // 服务名
	Listen          string  `json:"listen"`                  // 监听地址
	WebsocketPrefix string  `json:"websocket-prefix-listen"` // websocket 连接路径
	DiscoveryPrefix string  `json:"discovery-prefix"`        // 自动服务发现路由前缀
	Routes          []Route `json:"routes"`                  // 静态路由
}

GatewayConfig 网关配置

type GatewayOption

type GatewayOption func(*GatewayOptions)

GatewayOption 网关选项赋值

func WithGatewayPlugin

func WithGatewayPlugin(plugins ...GatewayPlugin) GatewayOption

WithGatewayPlugin 注册网关扩展插件

func WithGatewaySelectorBuilder

func WithGatewaySelectorBuilder(b SelectorBuilder) GatewayOption

WithGatewaySelectorBuilder 自定义通过 serviceName 构造 Selector 的方式

func WithGatewayTransport

func WithGatewayTransport(transport http.RoundTripper) GatewayOption

WithGatewayTransport 网关 http transport

type GatewayOptions

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

GatewayOptions 网关选项定义

type GatewayPlugin

type GatewayPlugin interface {
	// BeforeRoute 路由匹配前
	BeforeRoute(context.Context, *http.Request) (*http.Request, error)
	// AfterRoute 路由匹配后
	AfterRoute(context.Context, *http.Request) (*http.Request, error)
	// ModifyResponse 响应阶段处理
	ModifyResponse(context.Context, *http.Response) error
	// ErrorHandler 统一异常处理
	ErrorHandler(context.Context, http.ResponseWriter, *http.Request, error)
}

GatewayPlugin 网关插件接口

type GetValueFromContext

type GetValueFromContext func(ctx context.Context) any

GetValueFromContext 从 context 中获取值

type HTTPClient

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

HTTPClient 支持服务发现的 http client

func GetHTTPClient

func GetHTTPClient(serviceName string) *HTTPClient

GetHTTPClient 返回服务对应的 client

func (*HTTPClient) Call

func (c *HTTPClient) Call(ctx context.Context, req *HTTPRequest) (*HTTPResponse, error)

Call 发起 http 请求

type HTTPHandler

type HTTPHandler interface {
	// Bind 绑定路由
	Bind(router *HTTPServeMux)
}

HTTPHandler http 请求处理器接口

type HTTPMiddleware

type HTTPMiddleware func(http.Handler) http.Handler

HTTPMiddleware http 请求中间件

type HTTPRequest

type HTTPRequest struct {
	Path   string
	Method string
	Header http.Header
	Params url.Values
	Form   url.Values
	Body   []byte
}

HTTPRequest http 请求参数

type HTTPResponse

type HTTPResponse = httpc.Response

HTTPResponse http 请求返回信息

type HTTPServeMux

type HTTPServeMux struct {
	*http.ServeMux
	// contains filtered or unexported fields
}

HTTPServeMux http 路由

func NewHTTPServeMux

func NewHTTPServeMux() *HTTPServeMux

NewHTTPServeMux 创建一个 mux

func (*HTTPServeMux) ServeHTTP

func (mux *HTTPServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*HTTPServeMux) Sub

func (mux *HTTPServeMux) Sub(prefix string, fn func(sub *HTTPServeMux))

Sub 注册子路由

func (*HTTPServeMux) Use

func (mux *HTTPServeMux) Use(middlewares ...HTTPMiddleware) *HTTPServeMux

Use 注册中间件

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) Handler

func (s *HTTPServer) Handler(handlers ...HTTPHandler) *HTTPServer

Handler 请求处理

func (*HTTPServer) Start

func (s *HTTPServer) Start() error

Start 启动服务

func (*HTTPServer) Static

func (s *HTTPServer) Static(pattern string, root string) *HTTPServer

Static 注册静态文件服务 默认不显示文件目录

func (*HTTPServer) StaticFS added in v1.0.4

func (s *HTTPServer) StaticFS(pattern string, fs fs.FS) *HTTPServer

StaticFS 注册静态文件服务,自定义文件系统 fs 可以使用 luchen.Dir() 创建

func (*HTTPServer) Stop

func (s *HTTPServer) Stop() error

Stop 停止服务

func (*HTTPServer) Use

func (s *HTTPServer) Use(middlewares ...HTTPMiddleware) *HTTPServer

Use 中间件

type HTTPTransportServer

type HTTPTransportServer = httptransport.Server

HTTPTransportServer go-kit http transport server

func NewHTTPTransportServer added in v1.0.3

NewHTTPTransportServer http handler 绑定 endpoint

type HostPattern

type HostPattern struct {
}

HostPattern host 匹配

func (*HostPattern) Match

func (h *HostPattern) Match(req *http.Request, route *httpRoute) bool

Match host 匹配判断

func (*HostPattern) Name

func (h *HostPattern) Name() string

Name 模式名称

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 Pattern

type Pattern interface {
	// Name 匹配模式名称
	Name() string
	// Match 匹配路由
	Match(req *http.Request, route *httpRoute) bool
}

Pattern 路由匹配模式

type PrefixPattern

type PrefixPattern struct {
}

PrefixPattern 前缀匹配

func (*PrefixPattern) Match

func (h *PrefixPattern) Match(req *http.Request, route *httpRoute) bool

Match 前缀匹配判断

func (*PrefixPattern) Name

func (h *PrefixPattern) Name() string

Name 模式名称

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 Route

type Route struct {
	Protocol     string            `json:"protocol"`      // 协议,暂时只支持 http
	Pattern      string            `json:"pattern"`       // 匹配模式:path, host
	Prefix       string            `json:"prefix"`        // 匹配前缀
	Host         string            `json:"host"`          // 匹配 host
	ServiceName  string            `json:"service-name"`  // 注册的服务名
	Upstream     string            `json:"upstream"`      // 上游服务
	RewriteRegex string            `json:"rewrite-regex"` // url 重写正则
	Weight       int               `json:"weight"`        // 权重
	Ext          map[string]string `json:"ext"`           // 扩展信息
}

Route 服务路由

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 服务节点信息

type TraceGatewayPlugin

type TraceGatewayPlugin struct {
	*UnimplementedGatewayPlugin
}

TraceGatewayPlugin 链路跟踪插件

func (*TraceGatewayPlugin) BeforeRoute

func (p *TraceGatewayPlugin) BeforeRoute(ctx context.Context, req *http.Request) (*http.Request, error)

BeforeRoute context 和 http header 注入 traceID

func (*TraceGatewayPlugin) ModifyResponse

func (p *TraceGatewayPlugin) ModifyResponse(ctx context.Context, res *http.Response) error

ModifyResponse 从上下文获取 tradeID 并写入 response header

type UnimplementedGatewayPlugin

type UnimplementedGatewayPlugin struct {
}

UnimplementedGatewayPlugin 其他自定义插件如果不想实现所有接口,可以跟UnimplementedGatewayPlugin组合,只实现指定的方法即可

func (*UnimplementedGatewayPlugin) AfterRoute

func (p *UnimplementedGatewayPlugin) AfterRoute(ctx context.Context, req *http.Request) (*http.Request, error)

AfterRoute nothing to do

func (*UnimplementedGatewayPlugin) BeforeRoute

func (p *UnimplementedGatewayPlugin) BeforeRoute(ctx context.Context, req *http.Request) (*http.Request, error)

BeforeRoute nothing to do

func (*UnimplementedGatewayPlugin) ErrorHandler

func (p *UnimplementedGatewayPlugin) ErrorHandler(ctx context.Context, w http.ResponseWriter, req *http.Request, err error)

ErrorHandler nothing to do

func (*UnimplementedGatewayPlugin) GetContextErr

func (p *UnimplementedGatewayPlugin) GetContextErr(ctx context.Context) error

GetContextErr 从上下文获取错误

func (*UnimplementedGatewayPlugin) ModifyResponse

func (p *UnimplementedGatewayPlugin) ModifyResponse(ctx context.Context, res *http.Response) error

ModifyResponse nothing to do

Directories

Path Synopsis
docs module
http

Jump to

Keyboard shortcuts

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