robin

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2022 License: GPL-3.0 Imports: 26 Imported by: 0

README

robin

a kcp network library for online games

Documentation

Index

Constants

View Source
const (
	// DebugMode indicates gotham mode is debug.
	DebugMode = "debug"
	// ReleaseMode indicates gotham mode is release.
	ReleaseMode = "release"
	// TestMode indicates gotham mode is test.
	TestMode = "test"
)

Variables

View Source
var DebugPrintRouteFunc func(absolutePath, handlerName string, nuHandlers int)

DebugPrintRouteFunc indicates debug log output format.

View Source
var DefaultErrorWriter io.Writer = os.Stderr
View Source
var DefaultWriter io.Writer = os.Stdout
View Source
var ErrHybridPath error = errors.New("hybrid type path is not allowed.")
View Source
var (
	ErrNotFlusher = errors.New("this writer is not a flusher")
)
View Source
var (
	ErrServerClosed = errors.New("[robin]: server closed")
)

Functions

func DefaultNoRouteHandler added in v1.0.2

func DefaultNoRouteHandler(c *Context)

func DisableConsoleColor added in v1.0.2

func DisableConsoleColor()

DisableConsoleColor disables color output in the console.

func ForceConsoleColor added in v1.0.2

func ForceConsoleColor()

ForceConsoleColor force color output in the console.

func IsDebugging added in v1.0.2

func IsDebugging() bool

IsDebugging returns true if the framework is running in debug mode. Use SetMode(gotham.ReleaseMode) to disable debug mode.

func Key

func Key(pass, salt string) (key []byte)

func ListenAndServe

func ListenAndServe(addr string, key []byte, handler Handler) error

func NewResponseWriter added in v1.0.1

func NewResponseWriter(w io.Writer) *responseWriter

func SetMode added in v1.0.2

func SetMode(value string)

SetMode sets gotham mode according to input string.

func Unmarshal added in v1.0.1

func Unmarshal(data []byte, req *Request) error

Types

type BufFlusher added in v1.0.1

type BufFlusher interface {
	// Flush writes any buffered data to the underlying io.Writer.
	Flush() error

	// Returns the number of bytes already written into the response.
	// See Written()
	Buffered() int
}

type ConnState

type ConnState int

A ConnState represents the state of a client connection to a server.

const (
	// StateNew represents a new connection that is expected to
	StateNew ConnState = iota

	// StateActive represents a connection that has read 1 or more
	StateActive

	// StateIdle represents a connection that has finished
	StateIdle

	// StateClosed represents a closed connection.
	StateClosed
)

func (ConnState) String

func (c ConnState) String() string

type Context added in v1.0.2

type Context struct {

	// Keys is a key/value pair exclusively for the context of each request.
	Keys map[string]interface{}

	// Errors is a list of Errors attached to all the handlers/middlewares who used this context.
	Errors errorMsgs

	Writer  ResponseWriter
	Request *Request
	// contains filtered or unexported fields
}

Context is the most important part of gamerouter. It allows us to pass variables between middleware, manage the flow, validate the JSON of a request and render a JSON response for example.

func (*Context) Abort added in v1.0.2

func (c *Context) Abort()

Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.

func (*Context) AbortWithStatus added in v1.0.2

func (c *Context) AbortWithStatus(code int)

func (*Context) Error added in v1.0.2

func (c *Context) Error(err error) *Error

Error attaches an error to the current context. The error is pushed to a list of errors. It's a good idea to call Error for each error that occurred during the resolution of a request. A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response. Error will panic if err is nil.

func (*Context) Get added in v1.0.2

func (c *Context) Get(key string) (value interface{}, exists bool)

Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)

func (*Context) GetBool added in v1.0.2

func (c *Context) GetBool(key string) (b bool)

GetBool returns the value associated with the key as a boolean.

func (*Context) GetDuration added in v1.0.2

func (c *Context) GetDuration(key string) (d time.Duration)

GetDuration returns the value associated with the key as a duration.

func (*Context) GetFloat64 added in v1.0.2

func (c *Context) GetFloat64(key string) (f64 float64)

GetFloat64 returns the value associated with the key as a float64.

func (*Context) GetInt added in v1.0.2

func (c *Context) GetInt(key string) (i int)

GetInt returns the value associated with the key as an integer.

func (*Context) GetInt64 added in v1.0.2

func (c *Context) GetInt64(key string) (i64 int64)

GetInt64 returns the value associated with the key as an integer.

func (*Context) GetString added in v1.0.2

func (c *Context) GetString(key string) (s string)

GetString returns the value associated with the key as a string.

func (*Context) GetStringMap added in v1.0.2

func (c *Context) GetStringMap(key string) (sm map[string]interface{})

GetStringMap returns the value associated with the key as a map of interfaces.

func (*Context) GetStringMapString added in v1.0.2

func (c *Context) GetStringMapString(key string) (sms map[string]string)

GetStringMapString returns the value associated with the key as a map of strings.

func (*Context) GetStringMapStringSlice added in v1.0.2

func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)

GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.

func (*Context) GetStringSlice added in v1.0.2

func (c *Context) GetStringSlice(key string) (ss []string)

GetStringSlice returns the value associated with the key as a slice of strings.

func (*Context) GetTime added in v1.0.2

func (c *Context) GetTime(key string) (t time.Time)

GetTime returns the value associated with the key as time.

func (*Context) Handler added in v1.0.2

func (c *Context) Handler() HandlerFunc

Handler returns the main handler.

func (*Context) HandlerName added in v1.0.2

func (c *Context) HandlerName() string

HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", this function will return "main.handleGetUsers".

func (*Context) HandlerNames added in v1.0.2

func (c *Context) HandlerNames() []string

HandlerNames returns a list of all registered handlers for this context in descending order, following the semantics of HandlerName()

func (*Context) IsAborted added in v1.0.2

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) MustGet added in v1.0.2

func (c *Context) MustGet(key string) interface{}

MustGet returns the value for the given key if it exists, otherwise it panics.

func (*Context) Next added in v1.0.2

func (c *Context) Next()

Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler. See example in GitHub.

func (*Context) Set added in v1.0.2

func (c *Context) Set(key string, value interface{})

Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.

func (*Context) Write added in v1.0.2

func (c *Context) Write(msg *any.Any) error

Write message to connection

type Error added in v1.0.2

type Error struct {
	Err  error
	Type ErrorType
	Meta interface{}
}

Error represents a error's specification.

func (Error) Error added in v1.0.2

func (msg Error) Error() string

Error implements the error interface.

func (*Error) IsType added in v1.0.2

func (msg *Error) IsType(flags ErrorType) bool

IsType judges one error.

func (*Error) SetMeta added in v1.0.2

func (msg *Error) SetMeta(data interface{}) *Error

SetMeta sets the error's meta data.

func (*Error) SetType added in v1.0.2

func (msg *Error) SetType(flags ErrorType) *Error

SetType sets the error's type.

type ErrorType added in v1.0.2

type ErrorType uint64

ErrorType is an unsigned 64-bit error code as defined in the gotham spec.

const (
	// ErrorTypePrivate indicates a private error.
	ErrorTypePrivate ErrorType = 1 << 0
	// ErrorTypePublic indicates a public error.
	ErrorTypePublic ErrorType = 1 << 1
	// ErrorTypeAny indicates any other error.
	ErrorTypeAny ErrorType = 1<<64 - 1
)

type Handler

type Handler interface {
	Serve(ResponseWriter, *Request)
}

type HandlerFunc added in v1.0.2

type HandlerFunc func(*Context)

HandlerFunc defines the handler used by gamerouter middleware as return value.

func Logger added in v1.0.2

func Logger() HandlerFunc

Logger instances a Logger middleware that will write the logs to gotham.DefaultWriter. By default gotham.DefaultWriter = os.Stdout.

func LoggerWithConfig added in v1.0.2

func LoggerWithConfig(conf LoggerConfig) HandlerFunc

LoggerWithConfig instance a Logger middleware with config.

func LoggerWithFormatter added in v1.0.2

func LoggerWithFormatter(f LogFormatter) HandlerFunc

LoggerWithFormatter instance a Logger middleware with the specified log format function.

func LoggerWithWriter added in v1.0.2

func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc

LoggerWithWriter instance a Logger middleware with the specified writer buffer. Example: os.Stdout, a file opened in write mode, a socket...

func Recovery added in v1.0.2

func Recovery() HandlerFunc

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

func RecoveryWithWriter added in v1.0.2

func RecoveryWithWriter(out io.Writer) HandlerFunc

RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.

type HandlersChain added in v1.0.2

type HandlersChain []HandlerFunc

HandlersChain defines a HandlerFunc array.

func (HandlersChain) Last added in v1.0.2

func (c HandlersChain) Last() HandlerFunc

Last returns the last handler in the chain. ie. the last handler is the main one.

type IHandlers added in v1.0.2

type IHandlers interface {
	Handlers() HandlersChain
	Name() string
}

IHandlers defines all routers which have handlers, and a unique name .

type IRoutes added in v1.0.2

type IRoutes interface {
	Handle(string, ...HandlerFunc) IRoutes
	Use(...HandlerFunc) IRoutes
}

IRoutes defines all router handle interface.

type LogFormatter added in v1.0.2

type LogFormatter func(params LogFormatterParams) string

LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter

type LogFormatterParams added in v1.0.2

type LogFormatterParams struct {
	Request *Request

	// TimeStamp shows the time after the server returns a response.
	TimeStamp time.Time
	// StatusCode is HTTP response code.
	StatusCode int
	// Latency is how much time the server cost to process a certain request.
	Latency time.Duration
	// ClientIP equals Context's ClientIP method.
	ClientIP string
	// Path is a path the client requests.
	Path string
	// ErrorMessage is set if error has occurred in processing the request.
	ErrorMessage string

	// MessageSize is the size of the protobuf message
	MessageSize int
	// Keys are the keys set on the request's context.
	Keys map[string]interface{}
	// contains filtered or unexported fields
}

LogFormatterParams is the structure any formatter will be handed when time to log comes

func (*LogFormatterParams) IsOutputColor added in v1.0.2

func (p *LogFormatterParams) IsOutputColor() bool

IsOutputColor indicates whether can colors be outputted to the log.

func (*LogFormatterParams) ResetColor added in v1.0.2

func (p *LogFormatterParams) ResetColor() string

ResetColor resets all escape attributes.

func (*LogFormatterParams) StatusCodeColor added in v1.0.2

func (p *LogFormatterParams) StatusCodeColor() string

StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.

type LoggerConfig added in v1.0.2

type LoggerConfig struct {
	// Optional. Default value is gotham.defaultLogFormatter
	Formatter LogFormatter

	// Output is a writer where logs are written.
	// Optional. Default value is gotham.DefaultWriter.
	Output io.Writer

	// SkipPaths is a url path array which logs are not written.
	// Optional.
	SkipPaths []string
}

LoggerConfig defines the config for Logger middleware.

type Request

type Request struct {
	TypeUrl string
	Data    []byte
	// contains filtered or unexported fields
}

func (*Request) RemoteAddr added in v1.0.2

func (req *Request) RemoteAddr() string

type ResponseWriter

type ResponseWriter interface {
	BufFlusher

	// Set the response status code of the current request.
	SetStatus(statusCode int)

	// Returns the response status code of the current request.
	Status() int

	// Returns false if the server should close the connection after flush the data.
	KeepAlive() bool

	// Returns false if the server should close the connection after flush the data.
	SetKeepAlive(value bool)

	// Write the data into sending buffer.
	Write(data *any.Any) error
}

ResponseWriter interface is used by a handler to construct an protobuf response.

type RouteInfo added in v1.0.2

type RouteInfo struct {
	Path        string
	Handler     string
	HandlerFunc HandlerFunc
}

RouteInfo represents a request route's specification which contains path and its handler.

type Router added in v1.0.2

type Router struct {
	RouterGroup
	// contains filtered or unexported fields
}

Router of the gamerouter

func Default added in v1.0.2

func Default() *Router

Default returns a Router instance with the Logger and Recovery middleware already attached.

func New added in v1.0.2

func New() *Router

New returns a new blank Router instance without any middleware attached.

func (*Router) Group added in v1.0.2

func (router *Router) Group(name string) *RouterGroup

func (*Router) HandleContext added in v1.0.2

func (router *Router) HandleContext(c *Context)

HandleContext re-enter a context that has been rewritten. This can be done by setting c.Request.URL.Path to your new target. Disclaimer: You can loop yourself to death with this, use wisely.

func (*Router) NoRoute added in v1.0.2

func (router *Router) NoRoute(handlers ...HandlerFunc)

NoRoute adds handlers for NoRoute. It return a 404 code by default.

func (*Router) Routes added in v1.0.2

func (router *Router) Routes() (routes RoutesInfo)

Routes returns a slice of registered routes, including some useful information, such as: the http method, path and the handler name.

func (*Router) Run added in v1.0.2

func (r *Router) Run(addr string, key []byte) (err error)

func (*Router) Serve added in v1.0.2

func (r *Router) Serve(w ResponseWriter, req *Request)

Serve conforms to the Handler interface.

func (*Router) Use added in v1.0.2

func (router *Router) Use(middleware ...HandlerFunc) IRoutes

Use attaches a global middleware to the router. ie. the middleware attached though Use() will be included in the handlers chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.

type RouterGroup added in v1.0.2

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

RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix and an array of handlers (middleware).

func (*RouterGroup) Handle added in v1.0.2

func (group *RouterGroup) Handle(name string, handlers ...HandlerFunc) IRoutes

Handle

func (*RouterGroup) Handlers added in v1.0.2

func (group *RouterGroup) Handlers() HandlersChain

Handle registers a new request handle and middleware with the given path and method. The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. See the example code in GitHub.

func (*RouterGroup) Name added in v1.0.2

func (group *RouterGroup) Name() string

func (*RouterGroup) Use added in v1.0.2

func (group *RouterGroup) Use(middlewares ...HandlerFunc) IRoutes

Use adds middleware to the group, see example code in GitHub.

type RoutesInfo added in v1.0.2

type RoutesInfo []RouteInfo

RoutesInfo defines a RouteInfo array.

type Server

type Server struct {
	Listener *kcp.Listener
	Handler  Handler
	Logger   *zap.SugaredLogger

	// max buf size
	MaxBufSize uint

	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body.
	ReadTimeout time.Duration
	// WriteTimeout is the maximum duration before timing out
	// writes of the response.
	WriteTimeout time.Duration
	// IdleTimeout is the maximum amount of time to wait for the
	// next request.
	IdleTimeout time.Duration

	// 'block' is the block encryption algorithm to encrypt packets.
	Block kcp.BlockCrypt
	// 'dataShards', 'parityShards' specifiy how many parity packets will be generated following the data packets.
	DataShards   int
	ParityShards int
	// contains filtered or unexported fields
}

func DefaultServer added in v1.0.2

func DefaultServer(addr string, key []byte, handler Handler) (*Server, error)

func (*Server) Close

func (srv *Server) Close() error

Close immediately closes all active net.Listeners and any connections in state StateNew, StateActive, or StateIdle. For a graceful shutdown, use Shutdown.

Close does not attempt to close (and does not even know about) any hijacked connections, such as WebSockets.

Close returns any error returned from closing the Server's underlying Listener(s).

func (*Server) Serve

func (srv *Server) Serve() error

func (*Server) Shutdown

func (srv *Server) Shutdown() error

Shutdown gracefully shuts down the server without interrupting any active connections. Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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