Documentation ¶
Overview ¶
Package fasthttp provides transport implementations for Fast HTTP.
Example ¶
package main import ( "context" "fmt" "net" "net/http" "net/url" "sync" "time" "github.com/go-kit/kit/endpoint" "github.com/valyala/fasthttp" fasthttp_transport "github.com/wencan/kit-plugins/transport/fasthttp" ) type Request struct { Num int } type Response struct { Result int } var ( requestPool = &sync.Pool{ New: func() interface{} { return new(Request) }, } responsePool = &sync.Pool{ New: func() interface{} { return new(Response) }, } newRequest = requestPool.Get newResponse = responsePool.Get ) func releaseRequest(request interface{}) { r := request.(*Request) r.Num = 0 // clear requestPool.Put(r) // release } func releaseResponse(response interface{}) { res := response.(*Response) res.Result = 0 // clear responsePool.Put(res) // release } func newServerEndpoint(newResponse fasthttp_transport.NewObjectFunc) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { r := request.(*Request) res := newResponse().(*Response) res.Result = r.Num * r.Num return res, nil } } func main() { // Create a server server := fasthttp_transport.NewServer( newServerEndpoint(newResponse), fasthttp_transport.DecodeJSONRequest, fasthttp_transport.EncodeJSONResponse, newRequest, releaseRequest, releaseResponse) // Listen a random port listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { fmt.Println(err) return } // Run a server unit shutdown s := fasthttp.Server{ Handler: server.ServeFastHTTP, } go func() { if err := s.Serve(listener); err != nil { fmt.Printf("Error in server: %s", err) } }() defer s.Shutdown() // Create a client url, err := url.Parse(fmt.Sprintf("http://%s/", listener.Addr().String())) if err != nil { fmt.Println(err) return } opt := fasthttp_transport.SetClient(&fasthttp.Client{ MaxIdleConnDuration: time.Millisecond * 10, // Just for test }) client := fasthttp_transport.NewClient( http.MethodPost, url, fasthttp_transport.EncodeJSONRequest, fasthttp_transport.DecodeJSONResponse, newResponse, releaseResponse, opt) // Create endpoint endpoint := client.Endpoint() // Call request := &Request{ Num: 10, } response, err := endpoint(context.Background(), request) if err != nil { fmt.Println(err) return } fmt.Printf("Result: %d", response.(*Response).Result) }
Output: Result: 100
Index ¶
- Constants
- Variables
- func DecodeJSONRequest(_ context.Context, r *fasthttp.Request, request interface{}) error
- func DecodeJSONResponse(_ context.Context, resp *fasthttp.Response, response interface{}) error
- func DefaultErrorEncoder(_ context.Context, err error, resp *fasthttp.Response)
- func EncodeJSONRequest(_ context.Context, r *fasthttp.Request, request interface{}) error
- func EncodeJSONResponse(_ context.Context, resp *fasthttp.Response, response interface{}) error
- func NopReleaser(_ interface{})
- type Client
- type ClientFinalizerFunc
- type ClientOption
- type DecodeRequestFunc
- type DecodeResponseFunc
- type EncodeRequestFunc
- type EncodeResponseFunc
- type ErrorEncoder
- type Headerer
- type NewObjectFunc
- type ReleaseObjectFunc
- type RequestFunc
- type ResponseFunc
- type Server
- type ServerFinalizerFunc
- type ServerOption
- type StatusCoder
Examples ¶
Constants ¶
const ( // ContextKeyRequestCtx stored in context with value that *fasthttp.RequestCtx ContextKeyRequestCtx contextKey = iota )
Variables ¶
var ( // IngoreContentType Content-Type header will be ignored when decoding the body IngoreContentType bool )
Functions ¶
func DecodeJSONRequest ¶
DecodeJSONRequest is an DecodeRequestFunc that deserializes the response as a JSON object from the Request body. Many JSON-over-HTTP services can use it as a sensible default.
func DecodeJSONResponse ¶
DecodeJSONResponse is an DecodeResponseFunc that deserializes the response as a JSON object from the Response body. Many JSON-over-HTTP services can use it as a sensible default.
func DefaultErrorEncoder ¶
DefaultErrorEncoder writes the error to the ResponseWriter, by default a content type of text/plain, a body of the plain text of the error, and a status code of 500. If the error implements Headerer, the provided headers will be applied to the response. If the error implements json.Marshaler, and the marshaling succeeds, a content type of application/json and the JSON encoded form of the error will be used. If the error implements StatusCoder, the provided StatusCode will be used instead of 500.
func EncodeJSONRequest ¶
EncodeJSONRequest is an EncodeRequestFunc that serializes the request as a JSON object to the Request body. Many JSON-over-HTTP services can use it as a sensible default. If the request implements Headerer, the provided headers will be applied to the request.
func EncodeJSONResponse ¶
EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a JSON object to the ResponseWriter. Many JSON-over-HTTP services can use it as a sensible default. If the response implements Headerer, the provided headers will be applied to the response. If the response implements StatusCoder, the provided StatusCode will be used instead of 200.
func NopReleaser ¶
func NopReleaser(_ interface{})
NopReleaser is an ReleaseObjectFunc that do nothing. It's designed to be used in compatible servers.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client wraps a URL and provides a method that implements endpoint.Endpoint.
func NewClient ¶
func NewClient( method string, tgt *url.URL, enc EncodeRequestFunc, dec DecodeResponseFunc, newResponse NewObjectFunc, releaseResponse ReleaseObjectFunc, options ...ClientOption, ) *Client
NewClient constructs a usable Client for a single remote method.
type ClientFinalizerFunc ¶
type ClientFinalizerFunc func(c context.Context, req *fasthttp.Request, resp *fasthttp.Response, err error)
ClientFinalizerFunc can be used to perform work at the end of a client HTTP request, after the response is returned. The principal intended use is for error logging. Note: err may be nil. There maybe also no additional response parameters depending on when an error occurs.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption sets an optional parameter for clients.
func ClientAfter ¶
func ClientAfter(after ...ResponseFunc) ClientOption
ClientAfter sets the ResponseFuncs applied to the incoming HTTP request prior to it being decoded. This is useful for obtaining anything off of the response and adding onto the context prior to decoding.
func ClientBefore ¶
func ClientBefore(before ...RequestFunc) ClientOption
ClientBefore sets the RequestFuncs that are applied to the outgoing HTTP request before it's invoked.
func ClientFinalizer ¶
func ClientFinalizer(f ...ClientFinalizerFunc) ClientOption
ClientFinalizer is executed at the end of every HTTP request. By default, no finalizer is registered.
func SetClient ¶
func SetClient(client *fasthttp.Client) ClientOption
SetClient sets the underlying Fast HTTP client used for requests. By default, fasthttp.defaultClient is used.
type DecodeRequestFunc ¶
type DecodeRequestFunc func(ctx context.Context, req *fasthttp.Request, request interface{}) (err error)
DecodeRequestFunc extracts a user-domain request object from an HTTP request object. It's designed to be used in HTTP servers, for server-side endpoints. One straightforward DecodeRequestFunc could be something that JSON decodes from the request body to the concrete request type.
type DecodeResponseFunc ¶
type DecodeResponseFunc func(ctx context.Context, resp *fasthttp.Response, response interface{}) (err error)
DecodeResponseFunc extracts a user-domain response object from an HTTP response object. It's designed to be used in HTTP clients, for client-side endpoints. One straightforward DecodeResponseFunc could be something that JSON decodes from the response body to the concrete response type.
type EncodeRequestFunc ¶
type EncodeRequestFunc func(ctx context.Context, req *fasthttp.Request, request interface{}) (err error)
EncodeRequestFunc encodes the passed request object into the HTTP request object. It's designed to be used in HTTP clients, for client-side endpoints. One straightforward EncodeRequestFunc could be something that JSON encodes the object directly to the request body.
type EncodeResponseFunc ¶
type EncodeResponseFunc func(ctx context.Context, resp *fasthttp.Response, resonse interface{}) (err error)
EncodeResponseFunc encodes the passed response object to the HTTP response writer. It's designed to be used in HTTP servers, for server-side endpoints. One straightforward EncodeResponseFunc could be something that JSON encodes the object directly to the response body.
type ErrorEncoder ¶
ErrorEncoder is responsible for encoding an error to the ResponseWriter. Users are encouraged to use custom ErrorEncoders to encode HTTP errors to their clients, and will likely want to pass and check for their own error types. See the example shipping/handling service.
type Headerer ¶
Headerer is checked by DefaultErrorEncoder. If an error value implements Headerer, the provided headers will be applied to the response writer, after the Content-Type is set.
type NewObjectFunc ¶
type NewObjectFunc func() (object interface{})
NewObjectFunc acquire a clean object
type ReleaseObjectFunc ¶
type ReleaseObjectFunc func(object interface{})
ReleaseObjectFunc reset and release a object
type RequestFunc ¶
RequestFunc may take information from an HTTP request and put it into a request context. In Servers, RequestFuncs are executed prior to invoking the endpoint. In Clients, RequestFuncs are executed after creating the request but prior to invoking the HTTP client.
func SetRequestHeader ¶
func SetRequestHeader(key, val string) RequestFunc
SetRequestHeader returns a RequestFunc that sets the given header.
type ResponseFunc ¶
ResponseFunc may take information from a request context and use it to manipulate a Response. In Servers, RequestFuncs are executed after invoking the endpoint but prior to writing a response. In Clients, RequestFuncs are executed after a request has been made, but prior to it being decoded.
func SetResponseHeader ¶
func SetResponseHeader(key, val string) ResponseFunc
SetResponseHeader returns a ResponseFunc that sets the given header.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps an endpoint and provide fasthttp.RequestHandler method.
Example (Router) ¶
package main import ( "context" "fmt" "sync" "github.com/fasthttp/router" "github.com/go-kit/kit/endpoint" "github.com/valyala/fasthttp" fasthttp_transport "github.com/wencan/kit-plugins/transport/fasthttp" ) type HelloRequest struct { Name string } type HelloResponse struct { Greeting string } var ( helloRequestPool = &sync.Pool{ New: func() interface{} { return new(HelloRequest) }, } helloResponsePool = &sync.Pool{ New: func() interface{} { return new(HelloResponse) }, } newHelloRequest = helloRequestPool.Get newHelloResponse = helloResponsePool.Get ) func releaseHelloRequest(request interface{}) { r := request.(*HelloRequest) r.Name = "" // clear helloRequestPool.Put(r) // release } func releaseHelloResponse(response interface{}) { res := response.(*HelloResponse) res.Greeting = "" // clear helloResponsePool.Put(res) // release } func encodeHelloRequest(c context.Context, r *fasthttp.Request, request interface{}) error { ctx := c.Value(fasthttp_transport.ContextKeyRequestCtx).(*fasthttp.RequestCtx) name := ctx.UserValue("name").(string) request.(*HelloRequest).Name = name return nil } func newServerHelloEndpoint(newResponse fasthttp_transport.NewObjectFunc) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { r := request.(*HelloRequest) res := newResponse().(*HelloResponse) res.Greeting = fmt.Sprintf("hello, %s", r.Name) return res, nil } } func main() { // Create hello server helloServer := fasthttp_transport.NewServer( newServerHelloEndpoint(newHelloResponse), encodeHelloRequest, fasthttp_transport.EncodeJSONResponse, newHelloRequest, releaseHelloRequest, releaseHelloResponse) // Create router router := router.New() router.GET("/hello/:name", helloServer.ServeFastHTTP) // Run fasthttp server err := fasthttp.ListenAndServe("127.0.0.1:8080", router.Handler) if err != nil { fmt.Println(err) return } }
Output:
func NewCompatibleServer ¶
func NewCompatibleServer(e endpoint.Endpoint, dec DecodeRequestFunc, enc EncodeResponseFunc, newRequest NewObjectFunc, releaseRequest ReleaseObjectFunc, options ...ServerOption) *Server
NewCompatibleServer constructs a new compatible server. It does not reuse response object to share endpoint with other transport servers.
func NewServer ¶
func NewServer(e endpoint.Endpoint, dec DecodeRequestFunc, enc EncodeResponseFunc, newRequest NewObjectFunc, releaseRequest ReleaseObjectFunc, releaseResponse ReleaseObjectFunc, options ...ServerOption) *Server
NewServer constructs a new server.
func (Server) ServeFastHTTP ¶
func (s Server) ServeFastHTTP(ctx *fasthttp.RequestCtx)
ServeFastHTTP provide fasthttp.RequestHandler method.
type ServerFinalizerFunc ¶
type ServerFinalizerFunc func(c context.Context, req *fasthttp.Request, resp *fasthttp.Response, err error)
ServerFinalizerFunc can be used to perform work at the end of an HTTP request, after the response has been written to the client. The principal intended use is for request logging.
type ServerOption ¶
type ServerOption func(*Server)
ServerOption sets an optional parameter for servers.
func ServerAfter ¶
func ServerAfter(after ...ResponseFunc) ServerOption
ServerAfter functions are executed on the HTTP response writer after the endpoint is invoked, but before anything is written to the client.
func ServerBefore ¶
func ServerBefore(before ...RequestFunc) ServerOption
ServerBefore functions are executed on the HTTP request object before the request is decoded.
func ServerErrorEncoder ¶
func ServerErrorEncoder(ee ErrorEncoder) ServerOption
ServerErrorEncoder is used to encode errors to the http.ResponseWriter whenever they're encountered in the processing of a request. Clients can use this to provide custom error formatting and response codes. By default, errors will be written with the DefaultErrorEncoder.
func ServerErrorHandler ¶
func ServerErrorHandler(errorHandler transport.ErrorHandler) ServerOption
ServerErrorHandler is used to handle non-terminal errors. By default, non-terminal errors are ignored. This is intended as a diagnostic measure. Finer-grained control of error handling, including logging in more detail, should be performed in a custom ServerErrorEncoder or ServerFinalizer, both of which have access to the context.
func ServerFinalizer ¶
func ServerFinalizer(f ...ServerFinalizerFunc) ServerOption
ServerFinalizer is executed at the end of every HTTP request. By default, no finalizer is registered.
type StatusCoder ¶
type StatusCoder interface {
StatusCode() int
}
StatusCoder is checked by DefaultErrorEncoder. If an error value implements StatusCoder, the StatusCode will be used when encoding the error. By default, StatusInternalServerError (500) is used.