micro/examples/server/wrapper/main.go

80 lines
1.7 KiB
Go
Raw Normal View History

2016-01-02 03:38:57 +03:00
package main
import (
2016-03-15 23:48:09 +03:00
"log"
2016-01-02 03:38:57 +03:00
"github.com/micro/go-micro/cmd"
"github.com/micro/go-micro/examples/server/handler"
"github.com/micro/go-micro/examples/server/subscriber"
"github.com/micro/go-micro/server"
"golang.org/x/net/context"
)
func logWrapper(fn server.HandlerFunc) server.HandlerFunc {
return func(ctx context.Context, req server.Request, rsp interface{}) error {
2016-03-15 23:48:09 +03:00
log.Printf("[Log Wrapper] Before serving request method: %v", req.Method())
2016-01-02 03:38:57 +03:00
err := fn(ctx, req, rsp)
2016-03-15 23:48:09 +03:00
log.Printf("[Log Wrapper] After serving request")
2016-01-02 03:38:57 +03:00
return err
}
}
func logSubWrapper(fn server.SubscriberFunc) server.SubscriberFunc {
return func(ctx context.Context, req server.Publication) error {
2016-03-15 23:48:09 +03:00
log.Printf("[Log Sub Wrapper] Before serving publication topic: %v", req.Topic())
2016-01-02 03:38:57 +03:00
err := fn(ctx, req)
2016-03-15 23:48:09 +03:00
log.Printf("[Log Sub Wrapper] After serving publication")
2016-01-02 03:38:57 +03:00
return err
}
}
func main() {
// optionally setup command line usage
cmd.Init()
md := server.DefaultOptions().Metadata
md["datacenter"] = "local"
server.DefaultServer = server.NewServer(
server.WrapHandler(logWrapper),
server.WrapSubscriber(logSubWrapper),
server.Metadata(md),
)
// Initialise Server
server.Init(
server.Name("go.micro.srv.example"),
)
// Register Handlers
server.Handle(
server.NewHandler(
new(handler.Example),
),
)
// Register Subscribers
if err := server.Subscribe(
server.NewSubscriber(
"topic.go.micro.srv.example",
new(subscriber.Example),
),
); err != nil {
log.Fatal(err)
}
if err := server.Subscribe(
server.NewSubscriber(
"topic.go.micro.srv.example",
subscriber.Handler,
),
); err != nil {
log.Fatal(err)
}
// Run server
if err := server.Run(); err != nil {
log.Fatal(err)
}
}