http

package
v1.0.21 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: MIT Imports: 39 Imported by: 1

Documentation

Index

Constants

View Source
const SupportPackageIsVersion1 = true

SupportPackageIsVersion1 These constants should not be referenced from any other code.

Variables

This section is empty.

Functions

func CodecForRequest

func CodecForRequest(r *http.Request, name string) (encoding.Codec, bool)

CodecForRequest get encoding.Codec via http.Request

func CodecForResponse

func CodecForResponse(r *http.Response) encoding.Codec

CodecForResponse get encoding.Codec via http.Response

func DefaultErrorDecoder

func DefaultErrorDecoder(_ context.Context, res *http.Response) error

DefaultErrorDecoder is an HTTP error decoder.

func DefaultErrorEncoder

func DefaultErrorEncoder(c Context, err error)

DefaultErrorEncoder encodes the error to the HTTP response.

func DefaultRequestDecoder

func DefaultRequestDecoder(r *http.Request, v interface{}) error

DefaultRequestDecoder decodes the request body to object.

func DefaultRequestEncoder

func DefaultRequestEncoder(_ context.Context, contentType string, in interface{}) ([]byte, error)

DefaultRequestEncoder is an HTTP request encoder.

func DefaultRequestQuery

func DefaultRequestQuery(r *http.Request, v interface{}) error

DefaultRequestQuery decodes the request vars to object.

func DefaultRequestVars

func DefaultRequestVars(r *http.Request, v interface{}) error

DefaultRequestVars decodes the request vars to object.

func DefaultResponseDecoder

func DefaultResponseDecoder(_ context.Context, res *http.Response, v interface{}) error

DefaultResponseDecoder is an HTTP response decoder.

func DefaultResponseEncoder

func DefaultResponseEncoder(w http.ResponseWriter, r *http.Request, v interface{}) error

DefaultResponseEncoder encodes the object to the HTTP response.

func RequestFromServerContext

func RequestFromServerContext(ctx context.Context) (*http.Request, bool)

RequestFromServerContext returns request from context.

func SetOperation

func SetOperation(ctx context.Context, op string)

SetOperation sets the transport operation.

Types

type BaseHandler

type BaseHandler struct{}

func (*BaseHandler) Handle

func (h *BaseHandler) Handle(router Router)

func (*BaseHandler) Prefix

func (h *BaseHandler) Prefix() string

type CallOption

type CallOption interface {
	// contains filtered or unexported methods
}

CallOption configures a Call before it starts or extracts information from a Call after it completes.

func ContentType

func ContentType(contentType string) CallOption

ContentType with request content type.

func Header(header *http.Header) CallOption

Header returns a CallOptions that retrieves the http response header from server reply.

func Operation

func Operation(operation string) CallOption

Operation is serviceMethod call option

func PathTemplate

func PathTemplate(pattern string) CallOption

PathTemplate is http path template

func URL added in v1.0.12

func URL(v string) CallOption

URL returns a CallOptions that retrieves the http response header

type Client

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

Client is an HTTP client.

func NewClient

func NewClient(ctx context.Context, options ...ClientOption) (*Client, error)

NewClient returns an HTTP client.

func (*Client) Close

func (client *Client) Close() error

Close tears down the Transport and all underlying connections.

func (*Client) Do

func (client *Client) Do(req *http.Request, opts ...CallOption) (*http.Response, error)

Do send an HTTP request and decodes the body of response into target. returns an error (of type *Error) if the response status code is not 2xx.

func (*Client) Invoke

func (client *Client) Invoke(ctx context.Context, method, path string, args interface{}, reply interface{}, opts ...CallOption) error

Invoke makes a rpc call procedure for remote service.

type ClientOption

type ClientOption func(*clientOptions)

ClientOption is HTTP client option.

func WithBlock

func WithBlock() ClientOption

WithBlock with client block.

func WithConfig added in v1.0.4

func WithConfig(cfg *anypb.Any) ClientOption

WithConfig with client config.

func WithDiscovery

func WithDiscovery(d registry.Discovery) ClientOption

WithDiscovery with client discovery.

func WithEndpoint

func WithEndpoint(endpoint string) ClientOption

WithEndpoint with client addr.

func WithErrorDecoder

func WithErrorDecoder(errorDecoder DecodeErrorFunc) ClientOption

WithErrorDecoder with client error decoder.

func WithMiddleware

func WithMiddleware(m ...middleware.Middleware) ClientOption

WithMiddleware with client middleware.

func WithNodeFilter

func WithNodeFilter(filters ...selector.NodeFilter) ClientOption

WithNodeFilter with select filters

func WithRequestEncoder

func WithRequestEncoder(encoder EncodeRequestFunc) ClientOption

WithRequestEncoder with client request encoder.

func WithResponseDecoder

func WithResponseDecoder(decoder DecodeResponseFunc) ClientOption

WithResponseDecoder with client response decoder.

func WithSubset

func WithSubset(size int) ClientOption

WithSubset with client disocvery subset size. zero value means subset filter disabled

func WithTLSConfig

func WithTLSConfig(c *tls.Config) ClientOption

WithTLSConfig with tls config.

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout with client request timeout.

func WithTransport

func WithTransport(trans http.RoundTripper) ClientOption

WithTransport with client transport.

func WithUserAgent

func WithUserAgent(ua string) ClientOption

WithUserAgent with client user agent.

type ContentTypeCallOption

type ContentTypeCallOption struct {
	EmptyCallOption
	ContentType string
}

ContentTypeCallOption is BodyCallOption

type Context

type Context interface {
	context.Context
	Vars() url.Values
	Query() url.Values
	Form() url.Values
	Header() http.Header
	Request() *http.Request
	SetRequest(r *http.Request)
	Response() *Response
	SetResponse(r *Response)
	Middleware(middleware.Handler) middleware.Handler
	Bind(interface{}) error
	BindVars(interface{}) error
	BindQuery(interface{}) error
	BindForm(interface{}) error
	Returns(interface{}, error) error
	Result(int, interface{}) error
	JSON(int, interface{}) error
	XML(int, interface{}) error
	String(int, string) error
	Blob(int, string, []byte) error
	Stream(int, string, io.Reader) error
	Reset(http.ResponseWriter, *http.Request)
}

Context is an HTTP Context.

func NewContext

func NewContext(r *router, req *http.Request, w http.ResponseWriter) Context

NewContext returns a Context instance.

type CustomResponse

type CustomResponse struct {
	Code     int               `json:"code"`
	Reason   string            `json:"reason,omitempty"`
	Message  string            `json:"message"`
	Data     interface{}       `json:"data,omitempty"`
	TraceId  string            `json:"trace_id,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
	Cause    error             `json:"-"`
}

func (*CustomResponse) Unwrap

func (r *CustomResponse) Unwrap() error

Unwrap satisfies the Go 1.13 error wrapper interface.

type DecodeErrorFunc

type DecodeErrorFunc func(ctx context.Context, res *http.Response) error

DecodeErrorFunc is decode error func.

type DecodeRequestFunc

type DecodeRequestFunc func(*http.Request, interface{}) error

DecodeRequestFunc is decode request func.

type DecodeResponseFunc

type DecodeResponseFunc func(ctx context.Context, res *http.Response, out interface{}) error

DecodeResponseFunc is response decode func.

type EmptyCallOption

type EmptyCallOption struct{}

EmptyCallOption does not alter the Call configuration. It can be embedded in another structure to carry satellite data for use by interceptors.

type EncodeErrorFunc

type EncodeErrorFunc func(Context, error)

EncodeErrorFunc is encode error func.

type EncodeRequestFunc

type EncodeRequestFunc func(ctx context.Context, contentType string, in interface{}) (body []byte, err error)

EncodeRequestFunc is request encode func.

type EncodeResponseFunc

type EncodeResponseFunc func(http.ResponseWriter, *http.Request, interface{}) error

EncodeResponseFunc is encode response func.

type FilterFunc

type FilterFunc func(http.Handler) http.Handler

FilterFunc is a function which receives a http.Handler and returns another http.Handler.

func FilterChain

func FilterChain(filters ...FilterFunc) FilterFunc

FilterChain returns a FilterFunc that specifies the chained handler for HTTP Router.

type Flusher

type Flusher = http.Flusher

Flusher type net/http

type Handler

type Handler interface {
	Prefix() string
	Handle(router Router)
}

type HandlerFunc

type HandlerFunc func(Context) error

HandlerFunc defines a function to serve HTTP requests.

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

WrapHandler wraps `http.Handler` into `http.HandlerFunc`.

type HeaderCallOption

type HeaderCallOption struct {
	EmptyCallOption
	// contains filtered or unexported fields
}

HeaderCallOption is retrieve response header for client call

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc defines a function to process middleware.

func WrapMiddleware

func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc

WrapMiddleware wraps `func(http.Handler) http.Handler` into `http.MiddlewareFunc`

type OperationCallOption

type OperationCallOption struct {
	EmptyCallOption
	Operation string
}

OperationCallOption is set ServiceMethod for client call

type PathTemplateCallOption

type PathTemplateCallOption struct {
	EmptyCallOption
	Pattern string
}

PathTemplateCallOption is set path template for client call

type Redirector

type Redirector interface {
	Redirect() (string, int)
}

Redirector replies to the request with a redirect to url which may be a path relative to the request path.

func NewRedirect

func NewRedirect(url string, code int) Redirector

NewRedirect new a redirect with url, which may be a path relative to the request path. The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther. If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body. Setting the Content-Type header to any value, including nil, disables that behavior.

type Request

type Request = http.Request

Request type net/http.

type Response

type Response struct {
	Writer http.ResponseWriter
	Status int
	Size   int64
}

Response wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response. See: https://golang.org/pkg/net/http/#ResponseWriter

func NewResponse

func NewResponse(w http.ResponseWriter) (r *Response)

NewResponse creates a new instance of Response.

func (*Response) Flush

func (r *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the header map for the writer that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)

func (*Response) StatusCode

func (r *Response) StatusCode() int

func (*Response) Unwrap added in v1.0.19

func (r *Response) Unwrap() http.ResponseWriter

func (*Response) Write

func (r *Response) Write(b []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

type ResponseController

type ResponseController = http.ResponseController

type ResponseWriter

type ResponseWriter = http.ResponseWriter

ResponseWriter type net/http.

type RouteInfo

type RouteInfo struct {
	Path   string
	Method string
}

RouteInfo is an HTTP route info.

type Router

type Router interface {
	GET(path string, handler HandlerFunc, m ...MiddlewareFunc)
	POST(path string, handler HandlerFunc, m ...MiddlewareFunc)
	PUT(path string, handler HandlerFunc, m ...MiddlewareFunc)
	DELETE(path string, handler HandlerFunc, m ...MiddlewareFunc)
	HEAD(path string, handler HandlerFunc, m ...MiddlewareFunc)
	PATCH(path string, handler HandlerFunc, m ...MiddlewareFunc)
	CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc)
	OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc)
	TRACE(path string, h HandlerFunc, m ...MiddlewareFunc)
	Group(prefix string, filters ...MiddlewareFunc) Router
}

type Server

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

Server is an HTTP server wrapper.

func NewServer

func NewServer(opts ...ServerOption) *Server

NewServer creates an HTTP server by options.

func (*Server) Endpoint

func (s *Server) Endpoint() (*url.URL, error)

Endpoint return a real address to registry endpoint. examples:

https://127.0.0.1:8000
Legacy: http://127.0.0.1:8000?isSecure=false

func (*Server) Handle

func (s *Server) Handle(path string, h http.Handler)

Handle registers a new route with a matcher for the URL path.

func (*Server) HandleFunc

func (s *Server) HandleFunc(path string, h http.HandlerFunc)

HandleFunc registers a new route with a matcher for the URL path.

func (*Server) HandleHeader

func (s *Server) HandleHeader(key, val string, h http.HandlerFunc)

HandleHeader registers a new route with a matcher for the header.

func (*Server) HandlePrefix

func (s *Server) HandlePrefix(prefix string, h http.Handler)

HandlePrefix registers a new route with a matcher for the URL path prefix.

func (*Server) NewHandler

func (s *Server) NewHandler(handler Handler, middlewares ...MiddlewareFunc)

NewHandler registers an HTTP handler.

func (*Server) Route

func (s *Server) Route(prefix string, middlewares ...MiddlewareFunc) Router

Route registers an HTTP router.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP should write reply headers and data to the ResponseWriter and then return.

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start start the HTTP server.

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

Stop stop the HTTP server.

func (*Server) Use

func (s *Server) Use(selector string, m ...middleware.Middleware)

Use uses a service middleware with selector. selector:

  • '/*'
  • '/helloworld.v1.Greeter/*'
  • '/helloworld.v1.Greeter/SayHello'

func (*Server) WalkHandle

func (s *Server) WalkHandle(handle func(method, path string, handler http.HandlerFunc)) error

WalkHandle walks the router and all its sub-routers, calling walkFn for each route in the tree.

func (*Server) WalkRoute

func (s *Server) WalkRoute(fn WalkRouteFunc) error

WalkRoute walks the router and all its sub-routers, calling walkFn for each route in the tree.

type ServerOption

type ServerOption func(*Server)

ServerOption is an HTTP server option.

func Address

func Address(addr string) ServerOption

Address with server address.

func Endpoint

func Endpoint(endpoint *url.URL) ServerOption

Endpoint with server address.

func ErrorEncoder

func ErrorEncoder(en EncodeErrorFunc) ServerOption

ErrorEncoder with error encoder.

func Filter

func Filter(filters ...FilterFunc) ServerOption

Filter with HTTP middleware option.

func Listener

func Listener(lis net.Listener) ServerOption

Listener with server lis

func Logger

func Logger(_ log.Logger) ServerOption

Logger with server logger. Deprecated: use global logger instead.

func MethodNotAllowedHandler added in v1.0.19

func MethodNotAllowedHandler(handler http.Handler) ServerOption

func Middleware

func Middleware(m ...middleware.Middleware) ServerOption

Middleware with service middleware option.

func Network

func Network(network string) ServerOption

Network with server network.

func NotFoundHandler added in v1.0.19

func NotFoundHandler(handler http.Handler) ServerOption

func PathPrefix

func PathPrefix(prefix string) ServerOption

PathPrefix with mux's PathPrefix, router will replaced by a subrouter that start with prefix.

func RequestDecoder

func RequestDecoder(dec DecodeRequestFunc) ServerOption

RequestDecoder with request decoder.

func RequestQueryDecoder

func RequestQueryDecoder(dec DecodeRequestFunc) ServerOption

RequestQueryDecoder with request decoder.

func RequestVarsDecoder

func RequestVarsDecoder(dec DecodeRequestFunc) ServerOption

RequestVarsDecoder with request decoder.

func ResponseEncoder

func ResponseEncoder(en EncodeResponseFunc) ServerOption

ResponseEncoder with response encoder.

func StrictSlash

func StrictSlash(strictSlash bool) ServerOption

StrictSlash is with mux's StrictSlash If true, when the path pattern is "/path/", accessing "/path" will redirect to the former and vice versa.

func TLSConfig

func TLSConfig(c *tls.Config) ServerOption

TLSConfig with TLS config.

func Timeout

func Timeout(timeout time.Duration) ServerOption

Timeout with server timeout.

type Target

type Target struct {
	Scheme    string
	Authority string
	Endpoint  string
}

Target is resolver target

type Transport

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

Transport is an HTTP transport.

func (*Transport) Endpoint

func (tr *Transport) Endpoint() string

Endpoint returns the transport endpoint.

func (*Transport) Kind

func (tr *Transport) Kind() transport.Kind

Kind returns the transport kind.

func (*Transport) Operation

func (tr *Transport) Operation() string

Operation returns the transport operation.

func (*Transport) PathTemplate

func (tr *Transport) PathTemplate() string

PathTemplate returns the http path template.

func (*Transport) ReplyHeader

func (tr *Transport) ReplyHeader() transport.Header

ReplyHeader returns the reply header.

func (*Transport) Request

func (tr *Transport) Request() *http.Request

Request returns the HTTP request.

func (*Transport) RequestHeader

func (tr *Transport) RequestHeader() transport.Header

RequestHeader returns the request header.

type Transporter

type Transporter interface {
	transport.Transporter
	Request() *http.Request
	PathTemplate() string
}

Transporter is http Transporter

type URLCallOption added in v1.0.12

type URLCallOption struct {
	EmptyCallOption
	URL *url.URL
}

URLCallOption is set url for client call

type WalkRouteFunc

type WalkRouteFunc func(RouteInfo) error

WalkRouteFunc is the type of the function called for each route visited by Walk.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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