rpcx: github.com/smallnest/rpcx/server Index | Files

package server

import "github.com/smallnest/rpcx/server"

Index

Package Files

converter.go gateway.go jsonrpc2.go jsonrpc2_wire.go listener.go listener_unix.go option.go plugin.go pool.go server.go service.go

Constants

const (
    XVersion           = "X-RPCX-Version"
    XMessageType       = "X-RPCX-MesssageType"
    XHeartbeat         = "X-RPCX-Heartbeat"
    XOneway            = "X-RPCX-Oneway"
    XMessageStatusType = "X-RPCX-MessageStatusType"
    XSerializeType     = "X-RPCX-SerializeType"
    XMessageID         = "X-RPCX-MessageID"
    XServicePath       = "X-RPCX-ServicePath"
    XServiceMethod     = "X-RPCX-ServiceMethod"
    XMeta              = "X-RPCX-Meta"
    XErrorMessage      = "X-RPCX-ErrorMessage"
)
const (
    // CodeUnknownJSONRPCError should be used for all non coded errors.
    CodeUnknownJSONRPCError = -32001
    // CodeParseJSONRPCError is used when invalid JSON was received by the server.
    CodeParseJSONRPCError = -32700
    //CodeInvalidjsonrpcRequest is used when the JSON sent is not a valid jsonrpcRequest object.
    CodeInvalidjsonrpcRequest = -32600
    // CodeMethodNotFound should be returned by the handler when the method does
    // not exist / is not available.
    CodeMethodNotFound = -32601
    // CodeInvalidParams should be returned by the handler when method
    // parameter(s) were invalid.
    CodeInvalidParams = -32602
    // CodeInternalJSONRPCError is not currently returned but defined for completeness.
    CodeInternalJSONRPCError = -32603
)
const (
    // ReaderBuffsize is used for bufio reader.
    ReaderBuffsize = 1024
    // WriterBuffsize is used for bufio writer.
    WriterBuffsize = 1024
)

Variables

var (
    // RemoteConnContextKey is a context key. It can be used in
    // services with context.WithValue to access the connection arrived on.
    // The associated value will be of type net.Conn.
    RemoteConnContextKey = &contextKey{"remote-conn"}
    // StartRequestContextKey records the start time
    StartRequestContextKey = &contextKey{"start-parse-request"}
    // StartSendRequestContextKey records the start time
    StartSendRequestContextKey = &contextKey{"start-send-request"}
    // TagContextKey is used to record extra info in handling services. Its value is a map[string]interface{}
    TagContextKey = &contextKey{"service-tag"}
)
var ErrServerClosed = errors.New("http: Server closed")

ErrServerClosed is returned by the Server's Serve, ListenAndServe after a call to Shutdown or Close.

var UsePool bool

func HTTPRequest2RpcxRequest Uses

func HTTPRequest2RpcxRequest(r *http.Request) (*protocol.Message, error)

HTTPRequest2RpcxRequest converts a http request to a rpcx request.

func RegisterMakeListener Uses

func RegisterMakeListener(network string, ml MakeListener)

RegisterMakeListener registers a MakeListener for network.

type CORSOptions Uses

type CORSOptions struct {
    // AllowedOrigins is a list of origins a cross-domain request can be executed from.
    // If the special "*" value is present in the list, all origins will be allowed.
    // An origin may contain a wildcard (*) to replace 0 or more characters
    // (i.e.: http://*.domain.com). Usage of wildcards implies a small performance penalty.
    // Only one wildcard can be used per origin.
    // Default value is ["*"]
    AllowedOrigins []string
    // AllowOriginFunc is a custom function to validate the origin. It take the origin
    // as argument and returns true if allowed or false otherwise. If this option is
    // set, the content of AllowedOrigins is ignored.
    AllowOriginFunc func(origin string) bool
    // AllowOriginFunc is a custom function to validate the origin. It takes the HTTP Request object and the origin as
    // argument and returns true if allowed or false otherwise. If this option is set, the content of `AllowedOrigins`
    // and `AllowOriginFunc` is ignored.
    AllowOriginRequestFunc func(r *http.Request, origin string) bool
    // AllowedMethods is a list of methods the client is allowed to use with
    // cross-domain requests. Default value is simple methods (HEAD, GET and POST).
    AllowedMethods []string
    // AllowedHeaders is list of non simple headers the client is allowed to use with
    // cross-domain requests.
    // If the special "*" value is present in the list, all headers will be allowed.
    // Default value is [] but "Origin" is always appended to the list.
    AllowedHeaders []string
    // ExposedHeaders indicates which headers are safe to expose to the API of a CORS
    // API specification
    ExposedHeaders []string
    // MaxAge indicates how long (in seconds) the results of a preflight request
    // can be cached
    MaxAge int
    // AllowCredentials indicates whether the request can include user credentials like
    // cookies, HTTP authentication or client side SSL certificates.
    AllowCredentials bool
    // OptionsPassthrough instructs preflight to let other potential next handlers to
    // process the OPTIONS method. Turn this on if your application handles OPTIONS.
    OptionsPassthrough bool
    // Debugging flag adds additional output to debug server side CORS issues
    Debug bool
}

func AllowAllCORSOptions Uses

func AllowAllCORSOptions() *CORSOptions

AllowAllCORSOptions returns a option that allows access.

type ID Uses

type ID struct {
    Name   string
    Number int64
}

ID is a jsonrpcRequest identifier. Only one of either the Name or Number members will be set, using the number form if the Name is the empty string.

func (*ID) MarshalJSON Uses

func (id *ID) MarshalJSON() ([]byte, error)

func (*ID) String Uses

func (id *ID) String() string

String returns a string representation of the ID. The representation is non ambiguous, string forms are quoted, number forms are preceded by a #

func (*ID) UnmarshalJSON Uses

func (id *ID) UnmarshalJSON(data []byte) error

type JSONRPCError Uses

type JSONRPCError struct {
    // Code is an error code indicating the type of failure.
    Code int64 `json:"code"`
    // Message is a short description of the error.
    Message string `json:"message"`
    // Data is optional structured data containing additional information about the error.
    Data *json.RawMessage `json:"data"`
}

JSONRPCError represents a structured error in a jsonrpcRespone.

func (*JSONRPCError) JSONRPCError Uses

func (err *JSONRPCError) JSONRPCError() string

type MakeListener Uses

type MakeListener func(s *Server, address string) (ln net.Listener, err error)

MakeListener defines a listener generater.

type OptionFn Uses

type OptionFn func(*Server)

OptionFn configures options of server.

func WithReadTimeout Uses

func WithReadTimeout(readTimeout time.Duration) OptionFn

WithReadTimeout sets readTimeout.

func WithTLSConfig Uses

func WithTLSConfig(cfg *tls.Config) OptionFn

WithTLSConfig sets tls.Config.

func WithWriteTimeout Uses

func WithWriteTimeout(writeTimeout time.Duration) OptionFn

WithWriteTimeout sets writeTimeout.

type Plugin Uses

type Plugin interface {
}

Plugin is the server plugin interface.

type PluginContainer Uses

type PluginContainer interface {
    Add(plugin Plugin)
    Remove(plugin Plugin)
    All() []Plugin

    DoRegister(name string, rcvr interface{}, metadata string) error
    DoRegisterFunction(serviceName, fname string, fn interface{}, metadata string) error
    DoUnregister(name string) error

    DoPostConnAccept(net.Conn) (net.Conn, bool)
    DoPostConnClose(net.Conn) bool

    DoPreReadRequest(ctx context.Context) error
    DoPostReadRequest(ctx context.Context, r *protocol.Message, e error) error

    DoPreHandleRequest(ctx context.Context, req *protocol.Message) error

    DoPreWriteResponse(context.Context, *protocol.Message, *protocol.Message) error
    DoPostWriteResponse(context.Context, *protocol.Message, *protocol.Message, error) error

    DoPreWriteRequest(ctx context.Context) error
    DoPostWriteRequest(ctx context.Context, r *protocol.Message, e error) error
}

PluginContainer represents a plugin container that defines all methods to manage plugins. And it also defines all extension points.

type PostConnAcceptPlugin Uses

type PostConnAcceptPlugin interface {
    HandleConnAccept(net.Conn) (net.Conn, bool)
}

PostConnAcceptPlugin represents connection accept plugin. if returns false, it means subsequent IPostConnAcceptPlugins should not contiune to handle this conn and this conn has been closed.

type PostConnClosePlugin Uses

type PostConnClosePlugin interface {
    HandleConnClose(net.Conn) bool
}

PostConnClosePlugin represents client connection close plugin.

type PostReadRequestPlugin Uses

type PostReadRequestPlugin interface {
    PostReadRequest(ctx context.Context, r *protocol.Message, e error) error
}

PostReadRequestPlugin represents .

type PostWriteRequestPlugin Uses

type PostWriteRequestPlugin interface {
    PostWriteRequest(ctx context.Context, r *protocol.Message, e error) error
}

PostWriteRequestPlugin represents .

type PostWriteResponsePlugin Uses

type PostWriteResponsePlugin interface {
    PostWriteResponse(context.Context, *protocol.Message, *protocol.Message, error) error
}

PostWriteResponsePlugin represents .

type PreHandleRequestPlugin Uses

type PreHandleRequestPlugin interface {
    PreHandleRequest(ctx context.Context, r *protocol.Message) error
}

PreHandleRequestPlugin represents .

type PreReadRequestPlugin Uses

type PreReadRequestPlugin interface {
    PreReadRequest(ctx context.Context) error
}

PreReadRequestPlugin represents .

type PreWriteRequestPlugin Uses

type PreWriteRequestPlugin interface {
    PreWriteRequest(ctx context.Context) error
}

PreWriteRequestPlugin represents .

type PreWriteResponsePlugin Uses

type PreWriteResponsePlugin interface {
    PreWriteResponse(context.Context, *protocol.Message, *protocol.Message) error
}

PreWriteResponsePlugin represents .

type RegisterFunctionPlugin Uses

type RegisterFunctionPlugin interface {
    RegisterFunction(serviceName, fname string, fn interface{}, metadata string) error
}

RegisterFunctionPlugin is .

type RegisterPlugin Uses

type RegisterPlugin interface {
    Register(name string, rcvr interface{}, metadata string) error
    Unregister(name string) error
}

RegisterPlugin is .

type Reset Uses

type Reset interface {
    Reset()
}

Reset defines Reset method for pooled object.

type Server Uses

type Server struct {
    DisableHTTPGateway bool // should disable http invoke or not.
    DisableJSONRPC     bool // should disable json rpc or not.

    Plugins PluginContainer

    // AuthFunc can be used to auth.
    AuthFunc func(ctx context.Context, req *protocol.Message, token string) error
    // contains filtered or unexported fields
}

Server is rpcx server that use TCP or UDP.

func NewServer Uses

func NewServer(options ...OptionFn) *Server

NewServer returns a server.

func (*Server) ActiveClientConn Uses

func (s *Server) ActiveClientConn() []net.Conn

ActiveClientConn returns active connections.

func (*Server) Address Uses

func (s *Server) Address() net.Addr

Address returns listened address.

func (*Server) Close Uses

func (s *Server) Close() error

Close immediately closes all active net.Listeners.

func (*Server) Register Uses

func (s *Server) Register(rcvr interface{}, metadata string) error

Register publishes in the server the set of methods of the receiver value that satisfy the following conditions:

- exported method of exported type
- three arguments, the first is of context.Context, both of exported type for three arguments
- the third argument is a pointer
- one return value, of type error

It returns an error if the receiver is not an exported type or has no suitable methods. It also logs the error. The client accesses each method using a string of the form "Type.Method", where Type is the receiver's concrete type.

func (*Server) RegisterFunction Uses

func (s *Server) RegisterFunction(servicePath string, fn interface{}, metadata string) error

RegisterFunction publishes a function that satisfy the following conditions:

- three arguments, the first is of context.Context, both of exported type for three arguments
- the third argument is a pointer
- one return value, of type error

The client accesses function using a string of the form "servicePath.Method".

func (*Server) RegisterFunctionName Uses

func (s *Server) RegisterFunctionName(servicePath string, name string, fn interface{}, metadata string) error

RegisterFunctionName is like RegisterFunction but uses the provided name for the function instead of the function's concrete type.

func (*Server) RegisterName Uses

func (s *Server) RegisterName(name string, rcvr interface{}, metadata string) error

RegisterName is like Register but uses the provided name for the type instead of the receiver's concrete type.

func (*Server) RegisterOnShutdown Uses

func (s *Server) RegisterOnShutdown(f func(s *Server))

RegisterOnShutdown registers a function to call on Shutdown. This can be used to gracefully shutdown connections.

func (*Server) SendMessage Uses

func (s *Server) SendMessage(conn net.Conn, servicePath, serviceMethod string, metadata map[string]string, data []byte) error

SendMessage a request to the specified client. The client is designated by the conn. conn can be gotten from context in services:

ctx.Value(RemoteConnContextKey)

servicePath, serviceMethod, metadata can be set to zero values.

func (*Server) Serve Uses

func (s *Server) Serve(network, address string) (err error)

Serve starts and listens RPC requests. It is blocked until receiving connectings from clients.

func (*Server) ServeHTTP Uses

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

ServeHTTP implements an http.Handler that answers RPC requests.

func (*Server) SetCORS Uses

func (s *Server) SetCORS(options *CORSOptions)

SetCORS sets CORS options. for example:

cors.Options{
	AllowedOrigins:   []string{"foo.com"},
	AllowedMethods:   []string{http.MethodGet, http.MethodPost, http.MethodDelete},
	AllowCredentials: true,
}

func (*Server) Shutdown Uses

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

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing the listener, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener.

func (*Server) UnregisterAll Uses

func (s *Server) UnregisterAll() error

UnregisterAll unregisters all services. You can call this method when you want to shutdown/upgrade this node.

type VersionTag Uses

type VersionTag struct{}

VersionTag is a special 0 sized struct that encodes as the jsonrpc version tag. It will fail during decode if it is not the correct version tag in the stream.

func (VersionTag) MarshalJSON Uses

func (VersionTag) MarshalJSON() ([]byte, error)

func (VersionTag) UnmarshalJSON Uses

func (VersionTag) UnmarshalJSON(data []byte) error

Package server imports 32 packages (graph) and is imported by 48 packages. Updated 2019-10-18. Refresh now. Tools for package owners.