Documentation ¶
Overview ¶
Package restful provides RESTful API for tRPC-Go.
Experimental
Index ¶
- Constants
- Variables
- func DefaultFastHTTPRespHandler(stubCtx context.Context, requestCtx *fasthttp.RequestCtx, ...) error
- func GetRouter(name string) http.Handler
- func GetStatusCodeOnSucceed(ctx context.Context) int
- func PopulateMessage(msg proto.Message, fieldPath []string, values []string) error
- func RegisterCompressor(c Compressor)
- func RegisterRouter(name string, router http.Handler)
- func RegisterSerializer(s Serializer)
- func SetCtxForCompatibility(f func(context.Context, http.ResponseWriter, *http.Request) context.Context)
- func SetDefaultSerializer(s Serializer)
- func SetStatusCodeOnSucceed(ctx context.Context, code int)
- type Binding
- type BodyLocator
- type Compressor
- type CustomResponseHandler
- type ErrorHandler
- type ExtractFilterFunc
- type FastHTTPErrorHandler
- type FastHTTPHeaderMatcher
- type FastHTTPRespHandler
- type FormSerializer
- type GZIPCompressor
- type HandleFunc
- type HeaderMatcher
- type Initializer
- type JSONPBSerializer
- type Option
- func WithContainer(container string) Option
- func WithDiscardUnknownParams(i bool) Option
- func WithEnvironment(env string) Option
- func WithErrorHandler(errorHandler ErrorHandler) Option
- func WithFastHTTPErrorHandler(errHandler FastHTTPErrorHandler) Option
- func WithFastHTTPHeaderMatcher(m FastHTTPHeaderMatcher) Option
- func WithFastHTTPRespHandler(h FastHTTPRespHandler) Option
- func WithFilterFunc(f ExtractFilterFunc) Option
- func WithHeaderMatcher(m HeaderMatcher) Option
- func WithNamespace(namespace string) Option
- func WithResponseHandler(h CustomResponseHandler) Option
- func WithServiceName(name string) Option
- func WithSet(set string) Option
- func WithTimeout(t time.Duration) Option
- type Options
- type Pattern
- type ProtoMessage
- type ProtoSerializer
- type ResponseBodyLocator
- type Router
- type Serializer
- type WithStatusCode
Constants ¶
const (
// MarshalErrorContent is the content of http response body indicating error marshaling failure.
MarshalErrorContent = `{"code": 11, "message": "failed to marshal error"}`
)
Variables ¶
var DefaultErrorHandler = func(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) { _, s := serializerForTranscoding(r.Header[headerContentType], r.Header[headerAccept]) w.Header().Set(headerContentType, s.ContentType()) buf, merr := marshalError(err, s) if merr != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(MarshalErrorContent)) return } w.WriteHeader(statusCodeFromError(err)) w.Write(buf) }
DefaultErrorHandler is the default ErrorHandler.
var DefaultFastHTTPErrorHandler = func(ctx context.Context, requestCtx *fasthttp.RequestCtx, err error) { _, s := serializerForTranscoding( []string{bytes2str(requestCtx.Request.Header.Peek(headerContentType))}, []string{bytes2str(requestCtx.Request.Header.Peek(headerAccept))}, ) requestCtx.Response.Header.Set(headerContentType, s.ContentType()) buf, merr := marshalError(err, s) if merr != nil { requestCtx.Response.SetStatusCode(http.StatusInternalServerError) requestCtx.Write([]byte(MarshalErrorContent)) return } requestCtx.SetStatusCode(statusCodeFromError(err)) requestCtx.Write(buf) }
DefaultFastHTTPErrorHandler is the default FastHTTPErrorHandler.
var DefaultFastHTTPHeaderMatcher = func( ctx context.Context, requestCtx *fasthttp.RequestCtx, serviceName, methodName string, ) (context.Context, error) { return withNewMessage(ctx, serviceName, methodName), nil }
DefaultFastHTTPHeaderMatcher is the default FastHTTPHeaderMatcher.
var DefaultHeaderMatcher = func( ctx context.Context, w http.ResponseWriter, req *http.Request, serviceName, methodName string, ) (context.Context, error) { return withNewMessage(ctx, serviceName, methodName), nil }
DefaultHeaderMatcher is the default HeaderMatcher.
var DefaultResponseHandler = func( ctx context.Context, w http.ResponseWriter, r *http.Request, resp proto.Message, body []byte, ) error { // compress var writer io.Writer = w _, c := compressorForTranscoding(r.Header[headerContentEncoding], r.Header[headerAcceptEncoding]) if c != nil { writeCloser, err := c.Compress(w) if err != nil { return fmt.Errorf("failed to compress resp body: %w", err) } defer writeCloser.Close() w.Header().Set(headerContentEncoding, c.ContentEncoding()) writer = writeCloser } _, s := serializerForTranscoding(r.Header[headerContentType], r.Header[headerAccept]) w.Header().Set(headerContentType, s.ContentType()) statusCode := GetStatusCodeOnSucceed(ctx) w.WriteHeader(statusCode) if statusCode != http.StatusNoContent && statusCode != http.StatusNotModified { writer.Write(body) } return nil }
DefaultResponseHandler is the default CustomResponseHandler.
var ( // ErrTraverseNotFound is the error which indicates the field is // not found after traversing the proto message. ErrTraverseNotFound = errors.New("field not found") )
var JSONAPI = jsoniter.ConfigCompatibleWithStandardLibrary
JSONAPI is a copy of jsoniter.ConfigCompatibleWithStandardLibrary. github.com/json-iterator/go is faster than Go's standard json library.
Deprecated: This global variable is exportable due to backward comparability issue but should not be modified. If users want to change the default behavior of internal JSON serialization, please use register your customized serializer function like:
restful.RegisterSerializer(yourOwnJSONSerializer)
var Marshaller = protojson.MarshalOptions{EmitUnpopulated: true}
Marshaller is a configurable protojson marshaler.
var Unmarshaller = protojson.UnmarshalOptions{DiscardUnknown: true}
Unmarshaller is a configurable protojson unmarshaler.
Functions ¶
func DefaultFastHTTPRespHandler ¶
func DefaultFastHTTPRespHandler(stubCtx context.Context, requestCtx *fasthttp.RequestCtx, protoResp proto.Message, body []byte) error
DefaultFastHTTPRespHandler is the default FastHTTPRespHandler.
func GetStatusCodeOnSucceed ¶
GetStatusCodeOnSucceed returns status code on succeed. SetStatusCodeOnSucceed must be called first in tRPC method.
func PopulateMessage ¶
PopulateMessage populates a proto message.
func RegisterCompressor ¶
func RegisterCompressor(c Compressor)
RegisterCompressor registers a Compressor. This function is not thread-safe, it should only be called in init() function.
func RegisterRouter ¶
RegisterRouter registers a Router which corresponds to a tRPC Service.
func RegisterSerializer ¶
func RegisterSerializer(s Serializer)
RegisterSerializer registers a Serializer. This function is not thread-safe, it should only be called in init() function.
func SetCtxForCompatibility ¶
func SetCtxForCompatibility(f func(context.Context, http.ResponseWriter, *http.Request) context.Context)
SetCtxForCompatibility is used only for compatibility with thttp.
func SetDefaultSerializer ¶
func SetDefaultSerializer(s Serializer)
SetDefaultSerializer sets the default Serializer. This function is not thread-safe, it should only be called in init() function.
func SetStatusCodeOnSucceed ¶
SetStatusCodeOnSucceed sets status code on succeed, should be 2XX. It's not supposed to call this function but use WithStatusCode in restful/errors.go to set status code on error.
Types ¶
type Binding ¶
type Binding struct { Name string Input Initializer Output Initializer Filter HandleFunc HTTPMethod string Pattern *Pattern Body BodyLocator ResponseBody ResponseBodyLocator }
Binding is the binding of tRPC method and HttpRule.
type BodyLocator ¶
type BodyLocator interface { Body() string Locate(ProtoMessage) interface{} }
BodyLocator locates which fields of the proto message would be populated according to HttpRule body.
type Compressor ¶
type Compressor interface { // Compress compresses http body. Compress(w io.Writer) (io.WriteCloser, error) // Decompress decompresses http body. Decompress(r io.Reader) (io.Reader, error) // Name returns name of the Compressor. Name() string // ContentEncoding returns the encoding indicated by Content-Encoding response header. ContentEncoding() string }
Compressor is the interface for http body compression/decompression.
func GetCompressor ¶
func GetCompressor(name string) Compressor
GetCompressor returns a Compressor by name.
type CustomResponseHandler ¶
type CustomResponseHandler func( ctx context.Context, w http.ResponseWriter, r *http.Request, resp proto.Message, body []byte, ) error
CustomResponseHandler is the custom response handler.
type ErrorHandler ¶
ErrorHandler handles tRPC errors.
type ExtractFilterFunc ¶
type ExtractFilterFunc func() filter.ServerChain
ExtractFilterFunc extracts tRPC service filter chain.
type FastHTTPErrorHandler ¶
type FastHTTPErrorHandler func(context.Context, *fasthttp.RequestCtx, error)
FastHTTPErrorHandler handles tRPC errors when fasthttp is used.
type FastHTTPHeaderMatcher ¶
type FastHTTPHeaderMatcher func( ctx context.Context, requestCtx *fasthttp.RequestCtx, serviceName, methodName string, ) (context.Context, error)
FastHTTPHeaderMatcher matches fasthttp request header to tRPC Stub Context.
type FastHTTPRespHandler ¶
type FastHTTPRespHandler func( ctx context.Context, requestCtx *fasthttp.RequestCtx, resp proto.Message, body []byte, ) error
FastHTTPRespHandler is the custom response handler when fasthttp is used.
type FormSerializer ¶
type FormSerializer struct { // If DiscardUnknown is set, unknown fields are ignored. DiscardUnknown bool }
FormSerializer is used for Content-Type: application/x-www-form-urlencoded.
func (*FormSerializer) ContentType ¶
func (*FormSerializer) ContentType() string
ContentType implements Serializer. Does the same thing as jsonpb marshaler.
func (*FormSerializer) Marshal ¶
func (*FormSerializer) Marshal(v interface{}) ([]byte, error)
Marshal implements Serializer. It does the same thing as the jsonpb marshaler's Marshal method.
func (*FormSerializer) Unmarshal ¶
func (f *FormSerializer) Unmarshal(data []byte, v interface{}) error
Unmarshal implements Serializer
type GZIPCompressor ¶
type GZIPCompressor struct{}
GZIPCompressor is the compressor for Content-Encoding: gzip.
func (*GZIPCompressor) Compress ¶
func (*GZIPCompressor) Compress(w io.Writer) (io.WriteCloser, error)
Compress implements Compressor.
func (*GZIPCompressor) ContentEncoding ¶
func (*GZIPCompressor) ContentEncoding() string
ContentEncoding implements Compressor.
func (*GZIPCompressor) Decompress ¶
Decompress implements Compressor.
type HandleFunc ¶
type HandleFunc func(svc interface{}, ctx context.Context, reqBody interface{}) (interface{}, error)
HandleFunc is tRPC method handle function.
type HeaderMatcher ¶
type HeaderMatcher func( ctx context.Context, w http.ResponseWriter, r *http.Request, serviceName, methodName string, ) (context.Context, error)
HeaderMatcher matches http request header to tRPC Stub Context.
type JSONPBSerializer ¶
type JSONPBSerializer struct {
AllowUnmarshalNil bool // allow unmarshalling nil body
}
JSONPBSerializer is used for content-Type: application/json. It's based on google.golang.org/protobuf/encoding/protojson.
This serializer will firstly try jsonpb's serialization. If object does not conform to protobuf proto.Message interface, the serialization will switch to json-iterator.
func (*JSONPBSerializer) ContentType ¶
func (*JSONPBSerializer) ContentType() string
ContentType implements Serializer.
func (*JSONPBSerializer) Marshal ¶
func (*JSONPBSerializer) Marshal(v interface{}) ([]byte, error)
Marshal implements Serializer. Unlike Serializers in trpc-go/codec, Serializers in trpc-go/restful could be used to marshal a field of a tRPC message.
func (*JSONPBSerializer) Unmarshal ¶
func (j *JSONPBSerializer) Unmarshal(data []byte, v interface{}) error
Unmarshal implements Serializer.
type Option ¶
type Option func(*Options)
Option sets restful router options.
func WithContainer ¶
WithContainer returns an Option that sets container name.
func WithDiscardUnknownParams ¶
WithDiscardUnknownParams returns an Option that sets whether to ignore unknown query params for the restful router.
func WithEnvironment ¶
WithEnvironment returns an Option that sets environment name.
func WithErrorHandler ¶
func WithErrorHandler(errorHandler ErrorHandler) Option
WithErrorHandler returns an Option that sets error handler for the restful router.
func WithFastHTTPErrorHandler ¶
func WithFastHTTPErrorHandler(errHandler FastHTTPErrorHandler) Option
WithFastHTTPErrorHandler returns an Option that sets fasthttp error handler for the restful router.
func WithFastHTTPHeaderMatcher ¶
func WithFastHTTPHeaderMatcher(m FastHTTPHeaderMatcher) Option
WithFastHTTPHeaderMatcher returns an Option that sets fasthttp header matcher for the restful router.
func WithFastHTTPRespHandler ¶
func WithFastHTTPRespHandler(h FastHTTPRespHandler) Option
WithFastHTTPRespHandler returns an Option that sets fasthttp custom response handler for the restful router.
func WithFilterFunc ¶
func WithFilterFunc(f ExtractFilterFunc) Option
WithFilterFunc returns an Option that sets tRPC service filter chain extracting function for the restful router.
func WithHeaderMatcher ¶
func WithHeaderMatcher(m HeaderMatcher) Option
WithHeaderMatcher returns an Option that sets header matcher for the restful router.
func WithNamespace ¶
WithNamespace returns an Option that set namespace.
func WithResponseHandler ¶
func WithResponseHandler(h CustomResponseHandler) Option
WithResponseHandler returns an Option that sets custom response handler for the restful router.
func WithServiceName ¶
WithServiceName returns an Option that sets tRPC service name for the restful router.
func WithTimeout ¶
WithTimeout returns an Option that sets timeout for the restful router.
type Options ¶
type Options struct { ServiceName string // tRPC service name ServiceImpl interface{} // tRPC service impl FilterFunc ExtractFilterFunc // extract tRPC service filter chain ErrorHandler ErrorHandler // error handler HeaderMatcher HeaderMatcher // header matcher ResponseHandler CustomResponseHandler // custom response handler FastHTTPErrHandler FastHTTPErrorHandler // fasthttp error handler FastHTTPHeaderMatcher FastHTTPHeaderMatcher // fasthttp header matcher FastHTTPRespHandler FastHTTPRespHandler // fasthttp custom response handler DiscardUnknownParams bool // ignore unknown query params Timeout time.Duration // timeout // contains filtered or unexported fields }
Options are restful router options.
type Pattern ¶
type Pattern struct {
*httprule.PathTemplate
}
Pattern makes *httprule.PathTemplate accessible.
type ProtoSerializer ¶
type ProtoSerializer struct{}
ProtoSerializer is used for content-Type: application/octet-stream.
func (*ProtoSerializer) ContentType ¶
func (*ProtoSerializer) ContentType() string
ContentType implements Serializer.
func (*ProtoSerializer) Marshal ¶
func (*ProtoSerializer) Marshal(v interface{}) ([]byte, error)
Marshal implements Serializer.
func (*ProtoSerializer) Unmarshal ¶
func (*ProtoSerializer) Unmarshal(data []byte, v interface{}) error
Unmarshal implements Serializer.
type ResponseBodyLocator ¶
type ResponseBodyLocator interface { ResponseBody() string Locate(ProtoMessage) interface{} }
ResponseBodyLocator locates which fields of the proto message would be marshaled according to HttpRule response_body.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is restful router.
func (*Router) AddImplBinding ¶
AddImplBinding creates a new binding with a specified service implementation.
func (*Router) HandleRequestCtx ¶
func (r *Router) HandleRequestCtx(ctx *fasthttp.RequestCtx)
HandleRequestCtx fasthttp handler
type Serializer ¶
type Serializer interface { // Marshal marshals the tRPC message itself or a field of it to http body. Marshal(v interface{}) ([]byte, error) // Unmarshal unmarshalls http body to the tRPC message itself or a field of it. Unmarshal(data []byte, v interface{}) error // Name returns name of the Serializer. Name() string // ContentType returns the original media type indicated by Content-Encoding response header. ContentType() string }
Serializer is the interface for http body marshaling/unmarshalling.
func GetSerializer ¶
func GetSerializer(name string) Serializer
GetSerializer returns a Serializer by its name.
type WithStatusCode ¶
WithStatusCode is the error that corresponds to an HTTP status code.
func (*WithStatusCode) Unwrap ¶
func (w *WithStatusCode) Unwrap() error
Unwrap returns the wrapped error.