Documentation ¶
Index ¶
- Constants
- Variables
- func DefaultNoRouteHandler(c *Context)
- func DisableConsoleColor()
- func ForceConsoleColor()
- func IsDebugging() bool
- func Key(pass, salt string) (key []byte)
- func ListenAndServe(addr string, key []byte, handler Handler) error
- func NewResponseWriter(w io.Writer) *responseWriter
- func SetMode(value string)
- func Unmarshal(data []byte, req *Request) error
- type BufFlusher
- type ConnState
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithStatus(code int)
- func (c *Context) Error(err error) *Error
- func (c *Context) Get(key string) (value interface{}, exists bool)
- func (c *Context) GetBool(key string) (b bool)
- func (c *Context) GetDuration(key string) (d time.Duration)
- func (c *Context) GetFloat64(key string) (f64 float64)
- func (c *Context) GetInt(key string) (i int)
- func (c *Context) GetInt64(key string) (i64 int64)
- func (c *Context) GetString(key string) (s string)
- func (c *Context) GetStringMap(key string) (sm map[string]interface{})
- func (c *Context) GetStringMapString(key string) (sms map[string]string)
- func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)
- func (c *Context) GetStringSlice(key string) (ss []string)
- func (c *Context) GetTime(key string) (t time.Time)
- func (c *Context) Handler() HandlerFunc
- func (c *Context) HandlerName() string
- func (c *Context) HandlerNames() []string
- func (c *Context) IsAborted() bool
- func (c *Context) MustGet(key string) interface{}
- func (c *Context) Next()
- func (c *Context) Set(key string, value interface{})
- func (c *Context) Write(msg *any.Any) error
- type Error
- type ErrorType
- type Handler
- type HandlerFunc
- type HandlersChain
- type IHandlers
- type IRoutes
- type LogFormatter
- type LogFormatterParams
- type LoggerConfig
- type Request
- type ResponseWriter
- type RouteInfo
- type Router
- func (router *Router) Group(name string) *RouterGroup
- func (router *Router) HandleContext(c *Context)
- func (router *Router) NoRoute(handlers ...HandlerFunc)
- func (router *Router) Routes() (routes RoutesInfo)
- func (r *Router) Run(addr string, key []byte) (err error)
- func (r *Router) Serve(w ResponseWriter, req *Request)
- func (router *Router) Use(middleware ...HandlerFunc) IRoutes
- type RouterGroup
- type RoutesInfo
- type Server
Constants ¶
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 ¶
var DebugPrintRouteFunc func(absolutePath, handlerName string, nuHandlers int)
DebugPrintRouteFunc indicates debug log output format.
var DefaultErrorWriter io.Writer = os.Stderr
var DefaultWriter io.Writer = os.Stdout
var ErrHybridPath error = errors.New("hybrid type path is not allowed.")
var (
ErrNotFlusher = errors.New("this writer is not a flusher")
)
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 NewResponseWriter ¶ added in v1.0.1
Types ¶
type BufFlusher ¶ added in v1.0.1
type ConnState ¶
type ConnState int
A ConnState represents the state of a client connection to a server.
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 (*Context) Error ¶ added in v1.0.2
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
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
GetBool returns the value associated with the key as a boolean.
func (*Context) GetDuration ¶ added in v1.0.2
GetDuration returns the value associated with the key as a duration.
func (*Context) GetFloat64 ¶ added in v1.0.2
GetFloat64 returns the value associated with the key as a float64.
func (*Context) GetInt ¶ added in v1.0.2
GetInt returns the value associated with the key as an integer.
func (*Context) GetInt64 ¶ added in v1.0.2
GetInt64 returns the value associated with the key as an integer.
func (*Context) GetString ¶ added in v1.0.2
GetString returns the value associated with the key as a string.
func (*Context) GetStringMap ¶ added in v1.0.2
GetStringMap returns the value associated with the key as a map of interfaces.
func (*Context) GetStringMapString ¶ added in v1.0.2
GetStringMapString returns the value associated with the key as a map of strings.
func (*Context) GetStringMapStringSlice ¶ added in v1.0.2
GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
func (*Context) GetStringSlice ¶ added in v1.0.2
GetStringSlice returns the value associated with the key as a slice of strings.
func (*Context) GetTime ¶ added in v1.0.2
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
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
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
IsAborted returns true if the current context was aborted.
func (*Context) MustGet ¶ added in v1.0.2
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.
type Error ¶ added in v1.0.2
Error represents a error's specification.
type ErrorType ¶ added in v1.0.2
type ErrorType uint64
ErrorType is an unsigned 64-bit error code as defined in the gotham spec.
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 ¶
func (*Request) RemoteAddr ¶ added in v1.0.2
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
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) 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 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 (*Server) Close ¶
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).