Documentation
¶
Index ¶
- Constants
- func ColorMethod(method string) string
- func ColorStatus(code int) string
- func ColorString(code int, str string) string
- func NewFavicon(iconpath string) gear.Middleware
- func NewLogger(logger Logger) gear.Middleware
- func NewStatic(opts StaticOptions) gear.Middleware
- func NewTimeout(du time.Duration, hook gear.Hook) gear.Middleware
- type DefaultLogger
- type Log
- type Logger
- type StaticOptions
Constants ¶
const ( ColorCodeRed = 31 ColorCodeGreen = 32 ColorCodeYellow = 33 ColorCodeBlue = 34 ColorCodeMagenta = 35 ColorCodeCyan = 36 ColorCodeWhite = 37 ColorCodeGray = 90 )
Color Code https://en.wikipedia.org/wiki/ANSI_escape_code 30–37: set text color to one of the colors 0 to 7, 40–47: set background color to one of the colors 0 to 7, 39: reset text color to default, 49: reset background color to default, 1: make text bold / bright (this is the standard way to access the bright color variants), 22: turn off bold / bright effect, and 0: reset all text properties (color, background, brightness, etc.) to their default values. For example, one could select bright purple text on a green background (eww!) with the code `\x1B[35;1;42m`
Variables ¶
This section is empty.
Functions ¶
func ColorMethod ¶ added in v0.10.0
ColorMethod convert a HTTP method to a color string.
func ColorStatus ¶ added in v0.10.0
ColorStatus convert a HTTP status code to a color string.
func ColorString ¶ added in v0.10.0
ColorString convert a string to a color string with color code.
func NewFavicon ¶ added in v0.8.0
func NewFavicon(iconpath string) gear.Middleware
NewFavicon returns a middleware to serve favicon from the provided directory.
package main
import (
"github.com/teambition/gear"
"github.com/teambition/gear/middleware"
)
func main() {
app := gear.New()
app.Use(gear.NewDefaultLogger())
app.Use(middleware.NewFavicon("./testdata/favicon.ico"))
app.Use(func(ctx *gear.Context) error {
return ctx.HTML(200, "<h1>Hello, Gear!</h1>")
})
app.Error(app.Listen(":3000"))
}
func NewLogger ¶ added in v0.10.0
func NewLogger(logger Logger) gear.Middleware
NewLogger creates a middleware with a Logger instance.
app := gear.New()
logger := &myLogger{os.Stdout}
app.Use(middleware.NewLogger(logger))
app.Use(func(ctx *gear.Context) error {
log := logger.FromCtx(ctx)
log["Data"] = []int{1, 2, 3}
return ctx.HTML(200, "OK")
})
`appLogger` Output:
2016-10-25T08:52:19+08:00 INFO {"Data":{},"IP":"127.0.0.1","Length":2,"Method":"GET","Status":200,"Time":0,"URL":"/","UserAgent":"go-request/0.6.0"}
func NewStatic ¶
func NewStatic(opts StaticOptions) gear.Middleware
NewStatic returns a Static middleware to serves static content from the provided root directory.
package main
import (
"github.com/teambition/gear"
"github.com/teambition/gear/middleware"
)
func main() {
app := gear.New()
app.Use(middleware.NewDefaultLogger())
app.Use(middleware.NewFavicon("./testdata/favicon.ico"))
app.Use(middleware.NewStatic(middleware.StaticOptions{
Root: "./testdata",
Prefix: "/",
StripPrefix: false,
}))
app.Use(func(ctx *gear.Context) error {
return ctx.HTML(200, "<h1>Hello, Gear!</h1>")
})
app.Error(app.Listen(":3000"))
}
func NewTimeout ¶ added in v0.7.0
NewTimeout returns a timeout middleware with time.Duration and timeout hook. A timeout middleware example:
app := gear.New()
app.Use(NewTimeout(time.Second, func(ctx *gear.Context) {
// timeout hook
ctx.Status(504)
ctx.String("Service timeout")
}))
app.Use(func(ctx *gear.Context) error {
// some process maybe timeout...
c, _ := ctx.WithTimeout(time.Second * 2)
select {
case <-ctx.Done(): // this case will always reached
case <-c.Done(): // this case maybe reached... but elapsed time should be 1 sec.
}
return nil
})
app.Use(func(ctx *gear.Context) error {
// if timeout, the rest of middleware will not run.
panic("this middleware unreachable")
})
Types ¶
type DefaultLogger ¶ added in v0.10.0
DefaultLogger is Gear's default logger, useful for development. A custom logger example:
type myLogger struct {
W io.Writer
}
func (logger *myLogger) FromCtx(ctx *gear.Context) Log {
if any, err := ctx.Any(logger); err == nil {
return any.(Log)
}
log := Log{}
ctx.SetAny(logger, log)
log["IP"] = ctx.IP()
log["Method"] = ctx.Method
log["URL"] = ctx.Req.URL.String()
log["Start"] = time.Now()
log["UserAgent"] = ctx.Get(gear.HeaderUserAgent)
return log
}
func (logger *myLogger) WriteLog(log middleware.Log) {
// Format: ":Date INFO :JSONString"
end := time.Now()
info := map[string]interface{}{
"IP": log["IP"],
"Method": log["Method"],
"URL": log["URL"],
"UserAgent": log["UserAgent"],
"Status": log["Status"],
"Length": log["Length"],
"Data": log["Data"],
"Time": end.Sub(log["Start"].(time.Time)) / 1e6,
}
var str string
switch res, err := json.Marshal(info); err == nil {
case true:
str = fmt.Sprintf("%s INFO %s", end.Format(time.RFC3339), bytes.NewBuffer(res).String())
default:
str = fmt.Sprintf("%s ERROR %s", end.Format(time.RFC3339), err.Error())
}
// Don't block current process.
go func() {
if _, err := fmt.Fprintln(logger.W, str); err != nil {
panic(err)
}
}()
}
func (*DefaultLogger) FromCtx ¶ added in v0.11.0
func (logger *DefaultLogger) FromCtx(ctx *gear.Context) Log
FromCtx implements Logger interface
func (*DefaultLogger) WriteLog ¶ added in v0.10.0
func (logger *DefaultLogger) WriteLog(log Log)
WriteLog implements Logger interface
type Log ¶ added in v0.10.0
type Log map[string]interface{}
Log recodes key-value pairs for logs. It will be initialized by NewLogger middleware.
type Logger ¶ added in v0.10.0
type Logger interface {
// FromCtx retrieve the log instance from the ctx with ctx.Any.
// if log instance not exists, FromCtx should create one and save it to the ctx with ctx.SetAny.
// Here also some initialization work run after created. See DefaultLogger.
FromCtx(*gear.Context) Log
// WriteLog will be called on a "end hook". WriteLog should write the log to underlayer logging system.
WriteLog(Log)
}
Logger is a interface for logging. See DefaultLogger.
type StaticOptions ¶
type StaticOptions struct {
Root string // The directory you wish to serve
Prefix string // The url prefix you wish to serve as static request, default to `'/'`.
StripPrefix bool // Strip the prefix from URL path, default to `false`.
}
StaticOptions is static middleware options