Easily create middleware layer in Golang.
Forked from martini.
Dependence inject package.
// ware.go
package main
import (
"log"
"github.com/futurespace/ware"
)
func main() {
w := ware.New()
w.Use(func(c ware.Context, log *log.Logger) {
log.Println("before")
c.Next()
log.Println("after")
})
w.Run()
}
Install the Ware package:
go get github.com/futurespace/ware
Run test:
go run ware.go
Compose Wares:
package main
import (
"log"
"github.com/codegangsta/inject"
. "github.com/futurespace/ware"
)
type Builder struct {
inject.Injector
*Ware
}
func NewBuilder() *Builder {
w := New()
b := &Builder{inject.New(), w}
b.Map(w)
return b
}
type Packer struct {
inject.Injector
*Ware
}
func (p *Packer) Handle() {
p.Run()
}
func NewPacker() *Packer {
w := New()
p := &Packer{inject.New(), w}
p.Map(w)
return p
}
b := NewBuilder()
b.Use(func (log *log.Logger) {
log.Println("build...")
})
b.Run()
// Compose other Ware
p := NewPacker()
p.Use(func (log *log.Logger) {
log.Println("pack...")
})
b.Action(p.Handle)
b.Run()
Mapping values to interface
type Deploy interface {
Do()
}
type deploy struct{}
func (d *deploy) Do() {}
func NewDeploy() Deploy {
return &deploy{}
}
type Compress struct {
inject.Injector
*Ware
d Deploy
}
func NewCompress() *Compress {
w := New()
d := NewDeploy()
w.MapTo(d, (*Deploy)(nil))
c := &Compress{inject.New(), w, d}
c.Map(w)
return c
}
c := NewCompress()
c.Use(func(d Deploy) {
fmt.Println(d)
})
c.Run()
Sets the output prefix for the logger. (Default [ware]
)
w.Use(func(log *log.Logger) {
log.SetPrefix("[martini]")
})
Creates a Ware instance.
Sets middlewares.
Sets the handler that will be called after all the middleware has been invoked.
Adds a middleware.
Invokes the ware app.
Creates a new context.
NOTE: In martini, this api is private, but sometime we need to hack the context!
Sets response instance.
Stops to invoke next middleware handler, the response instance responded.
Invokes the context.
See inject.
MIT