gateway

package
v2.0.0-beta.14 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: Apache-2.0 Imports: 48 Imported by: 0

README

Gateway

Gateway 是一个 gRPC Gateway 实现,提供 HTTP/JSON 到 gRPC 的协议转换功能。它支持服务注册、中间件、HTTP Rule 解析等特性,让开发者可以轻松地将 gRPC 服务暴露为 RESTful API。

核心特性

  • HTTP Rule 解析:支持 google.api.http 注解,自动解析 RESTful 路径模板
  • 协议转换:自动处理 HTTP/JSON 与 gRPC/Protobuf 之间的双向转换
  • gRPC Web 支持:允许浏览器直接调用 gRPC 服务
  • 服务注册:支持本地服务和代理服务的注册
  • 中间件支持:提供 Unary 和 Stream 拦截器
  • 自定义编解码:支持 JSON、Protobuf 等多种编码格式
  • 错误映射:自动将 gRPC 错误码映射为 HTTP 状态码

快速开始

1. 定义 Proto 文件
syntax = "proto3";

package example.v1;

import "google/api/annotations.proto";

service UserService {
  rpc GetUser(GetUserRequest) returns (User) {
    option (google.api.http) = {
      get: "/v1/users/{user_id}"
    };
  }
  
  rpc CreateUser(CreateUserRequest) returns (User) {
    option (google.api.http) = {
      post: "/v1/users"
      body: "*"
    };
  }
}
2. 实现并注册服务
package main

import (
    "github.com/gofiber/fiber/v3"
    "github.com/pubgo/lava/v2/pkg/gateway"
    pb "your/proto/package"
)

func main() {
    // 创建 Gateway
    mux := gateway.NewMux()

    // 注册服务
    mux.RegisterService(&pb.UserService_ServiceDesc, &userServiceImpl{})

    // 创建 Fiber 应用
    app := fiber.New()
    app.All("/v1/*", mux.Handler)

    app.Listen(":8080")
}
3. 调用服务
# GET 请求
curl http://localhost:8080/v1/users/123

# POST 请求
curl -X POST http://localhost:8080/v1/users \
  -H "Content-Type: application/json" \
  -d '{"name": "John", "email": "john@example.com"}'

文档

文档 说明
使用指南 服务注册、路由配置、中间件、错误处理等
gRPC Web 浏览器端 gRPC Web 集成
架构设计 核心组件、数据结构、处理流程
实现细节 路径解析、元数据转换、流式处理等

支持的协议

协议 Content-Type 说明
HTTP/JSON application/json RESTful API
gRPC Web application/grpc-web+proto 浏览器 gRPC (二进制)
gRPC Web Text application/grpc-web-text+proto 浏览器 gRPC (Base64)

路径匹配

模式 示例 说明
{field} /users/{id} 路径变量
* /files/* 单段通配符
** /files/** 多段通配符
:verb /users/{id}:get 动词后缀

错误码映射

gRPC Code HTTP Status
OK 200
InvalidArgument 400
Unauthenticated 401
PermissionDenied 403
NotFound 404
Internal 500

完整映射表见 实现细节

示例

参考

Documentation

Index

Constants

View Source
const MetadataHeaderPrefix = "Grpc-Metadata-"

MetadataHeaderPrefix is the http prefix that represents custom metadata parameters to or from a gRPC call.

View Source
const MetadataPrefix = "grpcgateway-"

MetadataPrefix is prepended to permanent HTTP header keys (as specified by the IANA) when added to the gRPC context.

View Source
const MetadataTrailerPrefix = "Grpc-Trailer-"

MetadataTrailerPrefix is prepended to gRPC metadata as it is converted to HTTP headers in a response handled by grpc-gateway

Variables

View Source
var DefaultContextTimeout = 0 * time.Second

DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound header isn't present. If the value is 0 the sent `context` will not have a timeout.

Functions

func FieldMaskFromRequestBody

func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*fieldmask.FieldMask, error)

FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body.

func HTTPPathPattern

func HTTPPathPattern(ctx context.Context) (string, bool)

HTTPPathPattern returns the HTTP path pattern string relating to the HTTP handler, if one exists. The format of the returned string is defined by the google.api.http path template type.

func HTTPStatusFromCode

func HTTPStatusFromCode(code codes.Code) int

HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto

func NewContextWithServerTransportStream

func NewContextWithServerTransportStream(ctx context.Context, s grpc.ServerStream, method string) context.Context

func NewServerMetadataContext

func NewServerMetadataContext(ctx context.Context, md ServerMetadata) context.Context

NewServerMetadataContext creates a new context with ServerMetadata

func RPCMethod

func RPCMethod(ctx context.Context) (string, bool)

RPCMethod returns the method string for the server context. The returned string is in the format of "/package.service/method".

func TransparentHandler

func TransparentHandler(cli grpc.ClientConnInterface, inType, outType protoreflect.MessageType, opts ...grpc.CallOption) grpc.StreamHandler

Types

type AnnotateContextOption

type AnnotateContextOption func(ctx context.Context) context.Context

func WithHTTPPathPattern

func WithHTTPPathPattern(pattern string) AnnotateContextOption

type Codec

type Codec interface {
	encoding.Codec
	// MarshalAppend appends the marshaled form of v to b and returns the result.
	MarshalAppend([]byte, any) ([]byte, error)
}

Codec defines the interface used to encode and decode messages.

type CodecJSON

CodecJSON is a Codec implementation with protobuf json format.

func (CodecJSON) Marshal

func (c CodecJSON) Marshal(v any) ([]byte, error)

func (CodecJSON) MarshalAppend

func (c CodecJSON) MarshalAppend(b []byte, v any) ([]byte, error)

func (CodecJSON) Name

func (CodecJSON) Name() string

func (CodecJSON) ReadNext

func (c CodecJSON) ReadNext(b []byte, r io.Reader, limit int) ([]byte, int, error)

ReadNext reads the length of the message around the json object. It reads until it finds a matching number of braces. It does not validate the JSON.

func (CodecJSON) Unmarshal

func (c CodecJSON) Unmarshal(data []byte, v any) error

func (CodecJSON) WriteNext

func (c CodecJSON) WriteNext(w io.Writer, b []byte) (int, error)

WriteNext writes the raw JSON message to w without any size prefix.

type CodecProto

type CodecProto struct {
	proto.MarshalOptions
}

CodecProto is a Codec implementation with protobuf binary format.

func (CodecProto) Marshal

func (c CodecProto) Marshal(v any) ([]byte, error)

func (CodecProto) MarshalAppend

func (c CodecProto) MarshalAppend(b []byte, v any) ([]byte, error)

func (CodecProto) Name

func (CodecProto) Name() string

Name == "proto" overwritting internal proto codec

func (CodecProto) ReadNext

func (c CodecProto) ReadNext(b []byte, r io.Reader, limit int) ([]byte, int, error)

ReadNext reads a varint size-delimited wire-format message from r.

func (CodecProto) Unmarshal

func (CodecProto) Unmarshal(data []byte, v any) error

func (CodecProto) WriteNext

func (c CodecProto) WriteNext(w io.Writer, b []byte) (int, error)

WriteNext writes the length of the message encoded as 4 byte unsigned integer and then writes the message to w.

type Compressor

type Compressor interface {
	encoding.Compressor
}

Compressor is used to compress and decompress messages. Based on grpc/encoding.

type Gateway

type Gateway interface {
	grpc.ClientConnInterface
	SetUnaryInterceptor(interceptor grpc.UnaryServerInterceptor)
	SetStreamInterceptor(interceptor grpc.StreamServerInterceptor)

	SetRequestDecoder(protoreflect.FullName, func(ctx fiber.Ctx, msg proto.Message) error)
	SetResponseEncoder(protoreflect.FullName, func(ctx fiber.Ctx, msg proto.Message) error)
	RegisterService(sd *grpc.ServiceDesc, ss any)

	GetOperation(operation string) *GrpcMethod
	Handler(fiber.Ctx) error
	ServeHTTP(http.ResponseWriter, *http.Request)
	GetRouteMethods() []RouteOperation
}

type GrpcMethod

type GrpcMethod struct {
	Srv     any
	SrvDesc *grpc.ServiceDesc

	GrpcMethodDesc *grpc.MethodDesc
	GrpcStreamDesc *grpc.StreamDesc
	MethodDesc     protoreflect.MethodDescriptor

	GrpcFullMethod string
	Meta           *lavapbv1.RpcMeta
}

type MatchOperation

type MatchOperation = routertree.MatchOperation

func GetRouterTarget

func GetRouterTarget(mux *Mux, kind, path string) (*MatchOperation, error)

type MethodHandler

type MethodHandler = func(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error)

type Mux

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

func NewMux

func NewMux(opts ...MuxOption) *Mux

func (*Mux) GetOperation

func (m *Mux) GetOperation(operation string) *GrpcMethod

func (*Mux) GetOperationByName

func (m *Mux) GetOperationByName(name string) *GrpcMethod

func (*Mux) GetRouteMethods

func (m *Mux) GetRouteMethods() []RouteOperation

func (*Mux) Handler

func (m *Mux) Handler(ctx fiber.Ctx) error

func (*Mux) Invoke

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

func (*Mux) MatchOperation

func (m *Mux) MatchOperation(method, path string) (r result.Result[*MatchOperation])

func (*Mux) NewStream

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

func (*Mux) RegisterProxy

func (m *Mux) RegisterProxy(sd *grpc.ServiceDesc, proxy lava.GrpcRouter, cli grpc.ClientConnInterface)

func (*Mux) RegisterService

func (m *Mux) RegisterService(sd *grpc.ServiceDesc, ss any)

RegisterService satisfies grpc.ServiceRegistrar for generated service code hooks.

func (*Mux) ServeHTTP

func (m *Mux) ServeHTTP(writer http.ResponseWriter, request *http.Request)

func (*Mux) SetRequestDecoder

func (m *Mux) SetRequestDecoder(name protoreflect.FullName, f func(ctx fiber.Ctx, msg proto.Message) error)

func (*Mux) SetResponseEncoder

func (m *Mux) SetResponseEncoder(name protoreflect.FullName, f func(ctx fiber.Ctx, msg proto.Message) error)

func (*Mux) SetStreamInterceptor

func (m *Mux) SetStreamInterceptor(interceptor grpc.StreamServerInterceptor)

SetStreamInterceptor configures the in-process channel to use the given server interceptor for streaming RPCs when dispatching.

func (*Mux) SetUnaryInterceptor

func (m *Mux) SetUnaryInterceptor(interceptor grpc.UnaryServerInterceptor)

type MuxOption

type MuxOption func(*muxOptions)

MuxOption is an option for a mux.

type PathFieldVar

type PathFieldVar = routertree.PathFieldVar

type RouteOperation

type RouteOperation = routertree.RouteOperation

type ServerMetadata

type ServerMetadata struct {
	HeaderMD  metadata.MD
	TrailerMD metadata.MD
}

ServerMetadata consists of metadata sent from gRPC server.

func ServerMetadataFromContext

func ServerMetadataFromContext(ctx context.Context) (md ServerMetadata, ok bool)

ServerMetadataFromContext returns the ServerMetadata in ctx

type ServerTransportStream

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

ServerTransportStream implements grpc.ServerTransportStream. It should only be used by the generated files to support grpc.SendHeader outside of gRPC server use.

func (*ServerTransportStream) Header

func (s *ServerTransportStream) Header() metadata.MD

Header returns the header metadata of the stream.

func (*ServerTransportStream) Method

func (s *ServerTransportStream) Method() string

Method returns the method for the stream.

func (*ServerTransportStream) SendHeader

func (s *ServerTransportStream) SendHeader(md metadata.MD) error

SendHeader sets the header metadata.

func (*ServerTransportStream) SetHeader

func (s *ServerTransportStream) SetHeader(md metadata.MD) error

SetHeader sets the header metadata.

func (*ServerTransportStream) SetTrailer

func (s *ServerTransportStream) SetTrailer(md metadata.MD) error

SetTrailer sets the trailer metadata.

func (*ServerTransportStream) Trailer

func (s *ServerTransportStream) Trailer() metadata.MD

Trailer returns the cached trailer metadata.

type StreamDirector

type StreamDirector func(ctx context.Context, fullMethodName string) (context.Context, grpc.ClientConnInterface, error)

type StreamHandler

type StreamHandler = grpc.StreamHandler

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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