server

package
v4.0.20 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2024 License: Apache-2.0 Imports: 21 Imported by: 7

Documentation

Overview

Package server is an interface for a micro server

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultRegisterFunc uses backoff to register service
	DefaultRegisterFunc = func(svc *register.Service, config Options) error {
		var err error

		opts := []register.RegisterOption{
			register.RegisterTTL(config.RegisterTTL),
			register.RegisterDomain(config.Namespace),
		}

		for i := 0; i <= config.RegisterAttempts; i++ {
			err = config.Register.Register(config.Context, svc, opts...)
			if err == nil {
				break
			}

			time.Sleep(backoff.Do(i + 1))
			continue
		}
		return err
	}
	// DefaultDeregisterFunc uses backoff to deregister service
	DefaultDeregisterFunc = func(svc *register.Service, config Options) error {
		var err error

		opts := []register.DeregisterOption{
			register.DeregisterDomain(config.Namespace),
		}

		for i := 0; i <= config.DeregisterAttempts; i++ {
			err = config.Register.Deregister(config.Context, svc, opts...)
			if err == nil {
				break
			}

			time.Sleep(backoff.Do(i + 1))
			continue
		}
		return err
	}
)
View Source
var (
	// DefaultAddress will be used if no address passed, use secure localhost
	DefaultAddress = "127.0.0.1:0"
	// DefaultName will be used if no name passed
	DefaultName = "server"
	// DefaultVersion will be used if no version passed
	DefaultVersion = "latest"
	// DefaultRegisterCheck holds func that run before register server
	DefaultRegisterCheck = func(context.Context) error { return nil }
	// DefaultRegisterInterval holds interval for register
	DefaultRegisterInterval = time.Second * 30
	// DefaultRegisterTTL holds register record ttl, must be multiple of DefaultRegisterInterval
	DefaultRegisterTTL = time.Second * 90
	// DefaultMaxMsgSize holds default max msg size
	DefaultMaxMsgSize = 1024 * 1024 * 4 // 4Mb
	// DefaultMaxMsgRecvSize holds default max recv size
	DefaultMaxMsgRecvSize = 1024 * 1024 * 4 // 4Mb
	// DefaultMaxMsgSendSize holds default max send size
	DefaultMaxMsgSendSize = 1024 * 1024 * 4 // 4Mb
	// DefaultGracefulTimeout default time for graceful stop
	DefaultGracefulTimeout = 5 * time.Second
)
View Source
var DefaultCodecs = map[string]codec.Codec{
	"application/octet-stream": codec.NewCodec(),
}

DefaultCodecs will be used to encode/decode

View Source
var DefaultServer = NewServer()

DefaultServer default server

Functions

func Advertise(a string) options.Option

Advertise the address to advertise for discovery - host:port

func GracefulTimeout added in v4.0.17

func GracefulTimeout(td time.Duration) options.Option

func ID

func ID(id string) options.Option

ID unique server id

func Listener

func Listener(nl net.Listener) options.Option

Listener specifies the net.Listener to use instead of the default

func MaxConn

func MaxConn(n int) options.Option

MaxConn specifies maximum number of max simultaneous connections to server

func NewContext

func NewContext(ctx context.Context, s Server) context.Context

NewContext stores Server to context

func NewRegisterService

func NewRegisterService(s Server) (*register.Service, error)

NewRegisterService returns *register.Service from Server

func RegisterCheck

func RegisterCheck(fn func(context.Context) error) options.Option

RegisterCheck run func before register service

func RegisterInterval

func RegisterInterval(td time.Duration) options.Option

RegisterInterval registers service with at interval

func RegisterTTL

func RegisterTTL(td time.Duration) options.Option

RegisterTTL registers service with a TTL

func Version

func Version(v string) options.Option

Version of the service

func Wait

func Wait(wg *sync.WaitGroup) options.Option

Wait tells the server to wait for requests to finish before exiting If `wg` is nil, server only wait for completion of rpc handler. For user need finer grained control, pass a concrete `wg` here, server will wait against it on stop.

Types

type Error

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

func NewError

func NewError(id string) *Error

func (*Error) BadGateway

func (e *Error) BadGateway(format string, a ...interface{}) error

func (*Error) BadRequest

func (e *Error) BadRequest(format string, a ...interface{}) error

func (*Error) Conflict

func (e *Error) Conflict(format string, a ...interface{}) error

func (*Error) Forbidden

func (e *Error) Forbidden(format string, a ...interface{}) error

func (*Error) GatewayTimeout

func (e *Error) GatewayTimeout(format string, a ...interface{}) error

func (*Error) InternalServerError

func (e *Error) InternalServerError(format string, a ...interface{}) error

func (*Error) MethodNotAllowed

func (e *Error) MethodNotAllowed(format string, a ...interface{}) error

func (*Error) NotFound

func (e *Error) NotFound(format string, a ...interface{}) error

func (*Error) NotImplemented

func (e *Error) NotImplemented(format string, a ...interface{}) error

func (*Error) ServiceUnavailable

func (e *Error) ServiceUnavailable(format string, a ...interface{}) error

func (*Error) Timeout

func (e *Error) Timeout(format string, a ...interface{}) error

func (*Error) Unauthorized

func (e *Error) Unauthorized(format string, a ...interface{}) error

type HandleOptions added in v4.0.6

type HandleOptions struct {
	// Context holds external options
	Context context.Context
	// Metadata for handler
	Metadata map[string]metadata.Metadata
}

HandleOptions struct

func NewHandleOptions added in v4.0.6

func NewHandleOptions(opts ...options.Option) HandleOptions

NewHandleOptions creates new HandleOptions

type HandlerFunc

type HandlerFunc func(ctx context.Context, req Request, rsp interface{}) error

HandlerFunc represents a single method of a handler. It's used primarily for the wrappers. What's handed to the actual method is the concrete request and response types.

type HandlerWrapper

type HandlerWrapper func(HandlerFunc) HandlerFunc

HandlerWrapper wraps the HandlerFunc and returns the equivalent

type Options

type Options struct {
	// Context holds the external options and can be used for server shutdown
	Context context.Context
	// Register holds the register
	Register register.Register
	// Tracer holds the tracer
	Tracer tracer.Tracer
	// Logger holds the logger
	Logger logger.Logger
	// Meter holds the meter
	Meter meter.Meter
	// Listener may be passed if already created
	Listener net.Listener
	// Wait group
	Wait *msync.WaitGroup
	// TLSConfig specifies tls.Config for secure serving
	TLSConfig *tls.Config
	// Metadata holds the server metadata
	Metadata metadata.Metadata
	// RegisterCheck run before register server
	RegisterCheck func(context.Context) error
	// Codecs map to handle content-type
	Codecs map[string]codec.Codec
	// ID holds the id of the server
	ID string
	// Namespace for te server
	Namespace string
	// Name holds the server name
	Name string
	// Address holds the server address
	Address string
	// Advertise holds the advertise address
	Advertise string
	// Version holds the server version
	Version string
	// RegisterAttempts holds the number of register attempts before error
	RegisterAttempts int
	// RegisterInterval holds he interval for re-register
	RegisterInterval time.Duration
	// RegisterTTL specifies TTL for register record
	RegisterTTL time.Duration
	// MaxConn limits number of connections
	MaxConn int
	// DeregisterAttempts holds the number of deregister attempts before error
	DeregisterAttempts int
	// Hooks may contains HandleWrapper or Server func wrapper
	Hooks options.Hooks
	// GracefulTimeout timeout for graceful stop server
	GracefulTimeout time.Duration
}

Options server struct

func NewOptions

func NewOptions(opts ...options.Option) Options

NewOptions returns new options struct with default or passed values

type Request

type Request interface {
	// Service name requested
	Service() string
	// The action requested
	Method() string
	// Endpoint name requested
	Endpoint() string
	// Content type provided
	ContentType() string
	// Header of the request
	Header() metadata.Metadata
	// Body is the initial decoded value
	Body() interface{}
	// Read the undecoded request body
	Read() ([]byte, error)
	// The encoded message stream
	Codec() codec.Codec
	// Indicates whether its a stream
	Stream() bool
}

Request is a synchronous request interface

type Response

type Response interface {
	// Encoded writer
	Codec() codec.Codec
	// Write the header
	WriteHeader(md metadata.Metadata)
	// write a response directly to the client
	Write([]byte) error
}

Response is the response writer for unencoded messages

type Server

type Server interface {
	// Name returns server name
	Name() string
	// Initialise options
	Init(...options.Option) error
	// Retrieve the options
	Options() Options
	// Create and register new handler
	Handle(h interface{}, opts ...options.Option) error
	// Start the server
	Start() error
	// Stop the server
	Stop() error
	// Server implementation
	String() string
}

Server is a simple micro server abstraction

func FromContext

func FromContext(ctx context.Context) (Server, bool)

FromContext returns Server from context

func NewServer

func NewServer(opts ...options.Option) Server

NewServer returns new noop server

type Stream

type Stream interface {
	// Context for the stream
	Context() context.Context
	// Request returns request
	Request() Request
	// Send will encode and send a request
	Send(msg interface{}) error
	// Recv will decode and read a response
	Recv(msg interface{}) error
	// SendMsg will encode and send a request
	SendMsg(msg interface{}) error
	// RecvMsg will decode and read a response
	RecvMsg(msg interface{}) error
	// Error returns stream error
	Error() error
	// Close closes the stream
	Close() error
}

Stream represents a stream established with a client. A stream can be bidirectional which is indicated by the request. The last error will be left in Error(). EOF indicates end of the stream.

type StreamWrapper

type StreamWrapper func(Stream) Stream

StreamWrapper wraps a Stream interface and returns the equivalent. Because streams exist for the lifetime of a method invocation this is a convenient way to wrap a Stream as its in use for trace, monitoring, metrics, etc.

Jump to

Keyboard shortcuts

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