===== A lightweight, composable and high performance web service framework for Go.
package main
import (
"fmt"
"github.com/teambition/gear"
"github.com/teambition/gear/logging"
)
func main() {
app := gear.New()
// Add logging middleware
app.UseHandler(logging.Default())
// Add router middleware
router := gear.NewRouter()
router.Use(func(ctx *gear.Context) error {
// do some thing.
fmt.Println("Router middleware...", ctx.Path)
return nil
})
router.Get("/", func(ctx *gear.Context) error {
return ctx.HTML(200, "<h1>Hello, Gear!</h1>")
})
app.UseHandler(router)
app.Error(app.Listen(":3000"))
}
https://github.com/teambition/gear/tree/master/example/http2
package main
import (
"net/http"
"github.com/teambition/gear"
"github.com/teambition/gear/logging"
"github.com/teambition/gear/middleware/favicon"
)
// go run app.go
func main() {
const htmlBody = `
<!DOCTYPE html>
<html>
<head>
<link href="/hello.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello, Gear!</h1>
</body>
</html>`
const pushBody = `
h1 {
color: red;
}
`
app := gear.New()
app.UseHandler(logging.Default())
app.Use(favicon.New("../../testdata/favicon.ico"))
router := gear.NewRouter()
router.Get("/", func(ctx *gear.Context) error {
ctx.Res.Push("/hello.css", &http.PushOptions{Method: "GET"})
return ctx.HTML(200, htmlBody)
})
router.Get("/hello.css", func(ctx *gear.Context) error {
ctx.Type("text/css")
return ctx.End(200, []byte(pushBody))
})
app.UseHandler(router)
app.Error(app.ListenTLS(":3000", "../../testdata/server.crt", "../../testdata/server.key"))
}
https://github.com/teambition/gear/tree/master/example/staticgo
Install it with go:
go install github.com/teambition/gear/example/staticgo
It is a useful CMD tool that serve your local files as web server (support TLS).
You can build osx
, linux
, windows
version with make build
.
package main
import (
"flag"
"github.com/teambition/gear"
"github.com/teambition/gear/logging"
"github.com/teambition/gear/middleware/cors"
"github.com/teambition/gear/middleware/static"
)
var (
address = flag.String("addr", "127.0.0.1:3000", `address to listen on.`)
path = flag.String("path", "./", `static files path to serve.`)
certFile = flag.String("certFile", "", `certFile path, used to create TLS static server.`)
keyFile = flag.String("keyFile", "", `keyFile path, used to create TLS static server.`)
)
func main() {
flag.Parse()
app := gear.New()
app.UseHandler(logging.Default())
app.Use(cors.New())
app.Use(static.New(static.Options{Root: *path}))
logging.Println("staticgo v1.1.0, created by https://github.com/teambition/gear")
logging.Printf("listen: %s, serve: %s\n", *address, *path)
if *certFile != "" && *keyFile != "" {
app.Error(app.ListenTLS(*address, *certFile, *keyFile))
} else {
app.Error(app.Listen(*address))
}
}
// package gear
import "github.com/teambition/gear"
gear.Router is a tire base HTTP request handler. Features:
- Support regexp
- Support multi-router
- Support router layer middlewares
- Support fixed path automatic redirection
- Support trailing slash automatic redirection
- Automatic handle
405 Method Not Allowed
- Automatic handle
501 Not Implemented
- Automatic handle
OPTIONS
method - Best Performance
The registered path, against which the router matches incoming requests, can contain three types of parameters:
Syntax | Description |
---|---|
:name |
named parameter |
:name* |
named with catch-all parameter |
:name(regexp) |
named with regexp parameter |
::name |
not named parameter, it is literal :name |
Named parameters are dynamic path segments. They match anything until the next '/' or the path end:
Defined: /api/:type/:ID
/api/user/123 matched: type="user", ID="123"
/api/user no match
/api/user/123/comments no match
Named with catch-all parameters match anything until the path end, including the directory index (the '/' before the catch-all). Since they match anything until the end, catch-all parameters must always be the final path element.
Defined: /files/:filepath*
/files no match
/files/LICENSE matched: filepath="LICENSE"
/files/templates/article.html matched: filepath="templates/article.html"
Named with regexp parameters match anything using regexp until the next '/' or the path end:
Defined: /api/:type/:ID(^\d+$)
/api/user/123 matched: type="user", ID="123"
/api/user no match
/api/user/abc no match
/api/user/123/comments no match
The value of parameters is saved on the gear.Context. Retrieve the value of a parameter by name:
type := ctx.Param("type")
id := ctx.Param("ID")
// Middleware defines a function to process as middleware.
type Middleware func(*gear.Context) error
Middleware
can be used in app layer or router layer or middleware inside. It be good at composition.
We should write any module as a middleware. We should use middleware to compose all our business.
There are three build-in middlewares currently: https://godoc.org/github.com/teambition/gear/middleware
// package middleware
import (
"github.com/teambition/gear/middleware/cors"
"github.com/teambition/gear/middleware/favicon"
"github.com/teambition/gear/middleware/static"
)
- CORS middleware Use to serve CORS request.
- Favicon middleware Use to serve favicon.ico.
- Static server middleware Use to serve static files.
All this middlewares can be use in app layer, router layer or middleware layer.
Hook
can be used to some teardowm job dynamically. For example, Logger middleware use ctx.OnEnd
to write logs to underlayer. Hooks are executed in LIFO order, just like go defer
. Hook
can only be add in middleware. You can't add another hook in a hook.
ctx.After(hook func())
Add one or more "after hook" to current request process. They will run after middleware process(means context process ended
), and before Response.WriteHeader
. If some middleware return error
, the middleware process will stop, all "after hooks" will be clear and not run.
ctx.OnEnd(hook func())
Add one or more "end hook" to current request process. They will run after Response.WriteHeader
called. The middleware error will not stop "end hook" process.
Here is example using "end hook" in Logger middleware.
func (l *Logger) Serve(ctx *gear.Context) error {
// Add a "end hook" to flush logs.
ctx.OnEnd(func() {
log := l.FromCtx(ctx)
log["Status"] = ctx.Status()
log["Type"] = ctx.Res.Get(gear.HeaderContentType)
log["Length"] = ctx.Res.Get(gear.HeaderContentLength)
// Don't block current process.
go l.consume(log, ctx)
})
return nil
}
https://godoc.org/github.com/teambition/gear
Gear is licensed under the MIT license. Copyright © 2016 Teambition.