Documentation ¶
Overview ¶
Package http provides support for http protocol by default, provides rpc server with http protocol, and provides rpc client for calling http protocol.
Index ¶
- Constants
- Variables
- func Handle(pattern string, h stdhttp.Handler)
- func HandleFunc(pattern string, ...)
- func NewClientTransport(http2Only bool, opt ...transport.ClientTransportOption) transport.ClientTransport
- func NewFormDataSerialization(tag string) codec.Serializer
- func NewFormSerialization(tag string) codec.Serializer
- func NewGetSerialization(tag string) codec.Serializer
- func NewRESTServerTransport(basedOnFastHTTP bool, opt ...transport.ServerTransportOption) transport.ServerTransport
- func NewStdHTTPClient(name string, opts ...client.Option) *http.Client
- func RegisterContentEncoding(httpContentEncoding string, compressType int)
- func RegisterContentType(httpContentType string, serializationType int)
- func RegisterDefaultService(s server.Service)
- func RegisterNoProtocolService(s server.Service)
- func RegisterNoProtocolServiceMux(s server.Service, mux stdhttp.Handler)
- func RegisterSerializer(httpContentType string, serializationType int, serializer codec.Serializer)
- func RegisterServiceMux(s server.Service, mux stdhttp.Handler)
- func RegisterStatus[T errs.ErrCode](code T, httpStatus int)
- func Request(ctx context.Context) *http.Request
- func Response(ctx context.Context) http.ResponseWriter
- func SetContentType(httpContentType string, serializationType int)
- func WithHeader(ctx context.Context, value *Header) context.Context
- type Client
- type ClientCodec
- type ClientReqHeader
- type ClientRspHeader
- type ClientTransport
- type ContextKey
- type ErrorHandler
- type FormDataSerialization
- type FormSerialization
- type GetSerialization
- type Header
- type OptServerTransport
- type RESTServerTransport
- type ResponseHandler
- type ServerCodec
- type ServerTransport
Constants ¶
const ( TrpcVersion = "trpc-version" TrpcCallType = "trpc-call-type" TrpcMessageType = "trpc-message-type" TrpcRequestID = "trpc-request-id" TrpcTimeout = "trpc-timeout" TrpcCaller = "trpc-caller" TrpcCallee = "trpc-callee" TrpcTransInfo = "trpc-trans-info" TrpcEnv = "trpc-env" TrpcDyeingKey = "trpc-dyeing-key" // TrpcErrorMessage used to pass error messages, // contains user code's error or frame errors (such as validation framework). TrpcErrorMessage = "trpc-error-msg" // TrpcFrameworkErrorCode used to pass the error code reported by framework. TrpcFrameworkErrorCode = "trpc-ret" // TrpcUserFuncErrorCode used to pass the error code reported by user. TrpcUserFuncErrorCode = "trpc-func-ret" // Connection is used to set whether connect mode is "Connection". Connection = "Connection" )
Constants of header keys related to trpc.
const ( // ContextKeyHeader key of http header ContextKeyHeader = ContextKey("TRPC_SERVER_HTTP_HEADER") // ParseMultipartFormMaxMemory maximum memory for parsing request body, default is 32M. ParseMultipartFormMaxMemory int64 = 32 << 20 )
Variables ¶
var ( // DefaultClientCodec is the default http client codec. DefaultClientCodec = &ClientCodec{} // DefaultServerCodec is the default http server codec. DefaultServerCodec = &ServerCodec{ AutoGenTrpcHead: true, ErrHandler: defaultErrHandler, RspHandler: defaultRspHandler, AutoReadBody: true, DisableEncodeTransInfoBase64: false, } // DefaultNoProtocolServerCodec is the default http no protocol server codec. DefaultNoProtocolServerCodec = &ServerCodec{ AutoGenTrpcHead: true, ErrHandler: defaultErrHandler, RspHandler: defaultRspHandler, AutoReadBody: false, DisableEncodeTransInfoBase64: false, } )
var ( // DefaultRESTServerTransport is the default RESTful ServerTransport. DefaultRESTServerTransport = NewRESTServerTransport(false, transport.WithReusePort(true)) // DefaultRESTHeaderMatcher is the default REST HeaderMatcher. DefaultRESTHeaderMatcher = func(ctx context.Context, _ http.ResponseWriter, r *http.Request, serviceName, methodName string, ) (context.Context, error) { return putRESTMsgInCtx(ctx, r.Header.Get, serviceName, methodName) } // DefaultRESTFastHTTPHeaderMatcher is the default REST FastHTTPHeaderMatcher. DefaultRESTFastHTTPHeaderMatcher = func( ctx context.Context, requestCtx *fasthttp.RequestCtx, serviceName, methodName string, ) (context.Context, error) { headerGetter := func(k string) string { return string(requestCtx.Request.Header.Peek(k)) } return putRESTMsgInCtx(ctx, headerGetter, serviceName, methodName) } )
var DefaultClientTransport = NewClientTransport(false)
DefaultClientTransport default client http transport.
var DefaultHTTP2ClientTransport = NewClientTransport(true)
DefaultHTTP2ClientTransport default client http2 transport.
var DefaultHTTP2ServerTransport transport.ServerTransport
DefaultHTTP2ServerTransport is the default server http2 transport.
var DefaultServerTransport transport.ServerTransport
DefaultServerTransport is the default server http transport.
var ErrEncodeMissingHeader = errors.New("trpc/http: server encode missing http header in context")
ErrEncodeMissingHeader defines error used for special handling in transport when ctx lost header information.
var ErrsToHTTPStatus = map[trpcpb.TrpcRetCode]int{ errs.RetServerDecodeFail: http.StatusBadRequest, errs.RetServerEncodeFail: http.StatusInternalServerError, errs.RetServerNoService: http.StatusNotFound, errs.RetServerNoFunc: http.StatusNotFound, errs.RetServerTimeout: http.StatusGatewayTimeout, errs.RetServerOverload: http.StatusTooManyRequests, errs.RetServerSystemErr: http.StatusInternalServerError, errs.RetServerAuthFail: http.StatusUnauthorized, errs.RetServerValidateFail: http.StatusBadRequest, errs.RetUnknown: http.StatusInternalServerError, }
ErrsToHTTPStatus maps from framework errs retcode to http status code.
var ( // FormDataMarshalType the serialization method of the response data, // default is json serialization. FormDataMarshalType = codec.SerializationTypeJSON )
var NewClientProxy = func(name string, opts ...client.Option) Client { c := &cli{ serviceName: name, client: client.DefaultClient, } c.opts = make([]client.Option, 0, len(opts)+1) c.opts = append(c.opts, client.WithProtocol("http")) c.opts = append(c.opts, opts...) return c }
NewClientProxy creates a new http backend request proxy. Parameter name means the name of backend http service (e.g. trpc.http.xxx.xxx), mainly used for metrics, can be freely defined but format needs to follow "trpc.app.server.service".
var NewRoundTripper = newValueDetachedTransport
NewRoundTripper creates new NewRoundTripper and can be replaced.
var ServiceDesc = server.ServiceDesc{ HandlerType: nil, }
ServiceDesc is descriptor for server.RegisterService.
var StdHTTPTransport = &stdhttp.Transport{ Proxy: stdhttp.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, ForceAttemptHTTP2: true, IdleConnTimeout: 50 * time.Second, TLSHandshakeTimeout: 10 * time.Second, MaxIdleConnsPerHost: 100, DisableCompression: true, ExpectContinueTimeout: time.Second, }
StdHTTPTransport all RoundTripper object used by http and https.
Functions ¶
func HandleFunc ¶
HandleFunc registers http handler with custom route.
func NewClientTransport ¶
func NewClientTransport(http2Only bool, opt ...transport.ClientTransportOption) transport.ClientTransport
NewClientTransport creates http transport.
func NewFormDataSerialization ¶
func NewFormDataSerialization(tag string) codec.Serializer
NewFormDataSerialization initializes from serialized object.
func NewFormSerialization ¶
func NewFormSerialization(tag string) codec.Serializer
NewFormSerialization initializes the form serialized object.
func NewGetSerialization ¶
func NewGetSerialization(tag string) codec.Serializer
NewGetSerialization initializes the get serialized object.
func NewRESTServerTransport ¶
func NewRESTServerTransport(basedOnFastHTTP bool, opt ...transport.ServerTransportOption) transport.ServerTransport
NewRESTServerTransport creates a RESTful ServerTransport.
func NewStdHTTPClient ¶
NewStdHTTPClient returns http.Client of the go sdk, which is convenient for third-party clients to use, and can report monitoring metrics.
func RegisterContentEncoding ¶
RegisterContentEncoding registers an existing decompression method, such as RegisterContentEncoding("gzip", codec.CompressTypeGzip).
func RegisterContentType ¶
RegisterContentType registers existing serialization method to contentTypeSerializationType and serializationTypeContentType.
func RegisterDefaultService ¶
RegisterDefaultService registers service. See http/README.md for usage details. Deprecated: use RegisterNoProtocolService(s.Service("your.stdhttp.service.name")) instead.
func RegisterNoProtocolService ¶
RegisterNoProtocolService registers no protocol service. See http/README.md for usage details.
func RegisterNoProtocolServiceMux ¶
RegisterNoProtocolServiceMux registers service with http standard mux handler. Business registers routing plug-in by himself.
func RegisterSerializer ¶
func RegisterSerializer(httpContentType string, serializationType int, serializer codec.Serializer)
RegisterSerializer registers a new custom serialization method, such as RegisterSerializer("text/plain", 130, xxxSerializer).
func RegisterServiceMux ¶
RegisterServiceMux registers service with http standard mux handler. Business registers routing plug-in by himself. Deprecated: use RegisterNoProtocolServiceMux(s.Service("your.stdhttp.service.name"), mux) instead.
func RegisterStatus ¶
RegisterStatus registers trpc return code to http status.
func Response ¶
func Response(ctx context.Context) http.ResponseWriter
Response gets the corresponding http response from context.
func SetContentType ¶
SetContentType sets one-way mapping relationship for compatibility with old framework services, allowing multiple http content type to map to the save trpc serialization type. Tell the framework which serialization method to use to parse this content-type. Such as, a non-standard http server returns content type seems to be "text/html", but it is actually "json" data. At this time, you can set it like this: SetContentType("text/html", codec.SerializationTypeJSON).
Types ¶
type Client ¶
type Client interface { Get(ctx context.Context, path string, rspBody interface{}, opts ...client.Option) error Post(ctx context.Context, path string, reqBody interface{}, rspBody interface{}, opts ...client.Option) error Put(ctx context.Context, path string, reqBody interface{}, rspBody interface{}, opts ...client.Option) error Patch(ctx context.Context, path string, reqBody interface{}, rspBody interface{}, opts ...client.Option) error Delete(ctx context.Context, path string, reqBody interface{}, rspBody interface{}, opts ...client.Option) error }
Client provides the HTTP client interface. The primary use of this interface is to request standard HTTP services, if you wish to request HTTP RPC services use the client provided by the stub code (simply specify the protocol as "http").
type ClientCodec ¶
type ClientCodec struct{}
ClientCodec decodes http client request.
type ClientReqHeader ¶
type ClientReqHeader struct { // Schema should be named as scheme according to https://www.rfc-editor.org/rfc/rfc3986#section-3. // Now that it has been exported, we can do nothing more than add a comment here. Schema string // Examples: HTTP, HTTPS. Method string Host string Request *http.Request Header http.Header ReqBody io.Reader }
ClientReqHeader encapsulates http client context. Setting ClientReqHeader is not allowed when NewClientProxy is waiting for the init of Client. Setting ClientReqHeader is needed for each RPC.
func (*ClientReqHeader) AddHeader ¶
func (h *ClientReqHeader) AddHeader(key string, value string)
AddHeader adds http header.
type ClientRspHeader ¶
type ClientRspHeader struct { // ManualReadBody is used to control whether to read http response manually // (not read automatically by the framework). // Set it to true so that you can read data directly from Response.Body manually. // The default value is false. ManualReadBody bool Response *http.Response }
ClientRspHeader encapsulates the context returned by http client request.
type ClientTransport ¶
type ClientTransport struct { stdhttp.Client // http client, exposed variables, allow user to customize settings. // contains filtered or unexported fields }
ClientTransport client side http transport.
func (*ClientTransport) RoundTrip ¶
func (ct *ClientTransport) RoundTrip( ctx context.Context, reqBody []byte, callOpts ...transport.RoundTripOption, ) (rspBody []byte, err error)
RoundTrip sends and receives http packets, put http response into ctx, no need to return rspBuf here.
type ErrorHandler ¶
ErrorHandler handles error of http server's response. By default, the error code is placed in header, which can be replaced by a specific implementation of user.
type FormDataSerialization ¶
type FormDataSerialization struct {
// contains filtered or unexported fields
}
FormDataSerialization packages kv structure of http request.
func (*FormDataSerialization) Marshal ¶
func (j *FormDataSerialization) Marshal(body interface{}) ([]byte, error)
Marshal serializes.
func (*FormDataSerialization) Unmarshal ¶
func (j *FormDataSerialization) Unmarshal(in []byte, body interface{}) error
Unmarshal unpacks kv structure.
type FormSerialization ¶
type FormSerialization struct {
// contains filtered or unexported fields
}
FormSerialization packages the kv structure of http get request.
func (*FormSerialization) Marshal ¶
func (j *FormSerialization) Marshal(body interface{}) ([]byte, error)
Marshal packages kv structure.
func (*FormSerialization) Unmarshal ¶
func (j *FormSerialization) Unmarshal(in []byte, body interface{}) error
Unmarshal unpacks kv structure.
type GetSerialization ¶
type GetSerialization struct {
// contains filtered or unexported fields
}
GetSerialization packages kv structure of the http get request.
func (*GetSerialization) Marshal ¶
func (s *GetSerialization) Marshal(body interface{}) ([]byte, error)
Marshal packages kv structure.
func (*GetSerialization) Unmarshal ¶
func (s *GetSerialization) Unmarshal(in []byte, body interface{}) error
Unmarshal unpacks kv structure.
type Header ¶
type Header struct { ReqBody []byte Request *http.Request Response http.ResponseWriter }
Header encapsulates http context.
type OptServerTransport ¶
type OptServerTransport func(*ServerTransport)
OptServerTransport modifies ServerTransport.
func WithEnableH2C ¶
func WithEnableH2C() OptServerTransport
WithEnableH2C returns an OptServerTransport which enables H2C.
func WithReusePort ¶
func WithReusePort() OptServerTransport
WithReusePort returns an OptServerTransport which enables reuse port.
type RESTServerTransport ¶
type RESTServerTransport struct {
// contains filtered or unexported fields
}
RESTServerTransport is the RESTful ServerTransport.
func (*RESTServerTransport) ListenAndServe ¶
func (st *RESTServerTransport) ListenAndServe(ctx context.Context, opt ...transport.ListenServeOption) error
ListenAndServe implements interface of transport.ServerTransport.
type ResponseHandler ¶
ResponseHandler handles data of http server's response. By default, the content is returned directly, which can replaced by a specific implementation of user.
type ServerCodec ¶
type ServerCodec struct { // AutoGenTrpcHead converts trpc header automatically. // Auto conversion could be enabled by setting http.DefaultServerCodec.AutoGenTrpcHead with true. AutoGenTrpcHead bool // ErrHandler is error code handle function, which is filled into header by default. // Business can set this with http.DefaultServerCodec.ErrHandler = func(rsp, req, err) {}. ErrHandler ErrorHandler // RspHandler returns the data handle function. By default, data is returned directly. // Business can customize this method to shape returned data. // Business can set this with http.DefaultServerCodec.RspHandler = func(rsp, req, rspBody) {}. RspHandler ResponseHandler // AutoReadBody reads http request body automatically. AutoReadBody bool // DisableEncodeTransInfoBase64 indicates whether to disable encoding the transinfo value by base64. DisableEncodeTransInfoBase64 bool }
ServerCodec is the encoder/decoder for HTTP server.
type ServerTransport ¶
type ServerTransport struct {
// contains filtered or unexported fields
}
ServerTransport is the http transport layer.
func NewServerTransport ¶
func NewServerTransport( newStdHttpServer func() *stdhttp.Server, opts ...OptServerTransport, ) *ServerTransport
NewServerTransport creates a new ServerTransport which implement transport.ServerTransport. The parameter newStdHttpServer is used to create the underlying stdhttp.Server when ListenAndServe, and that server is modified by opts of this function and ListenAndServe.
func (*ServerTransport) ListenAndServe ¶
func (t *ServerTransport) ListenAndServe(ctx context.Context, opt ...transport.ListenServeOption) error
ListenAndServe handles configuration.