日志加入(测试用)
package main
import (
"context"
"flag"
"fmt"
"gitee.com/Hind3ight/easy-go-micro/go-micro/Server"
"gitee.com/Hind3ight/easy-go-micro/go-micro/Services"
"github.com/gin-gonic/gin"
"github.com/micro/go-micro"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/metadata"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/web"
"github.com/micro/go-plugins/registry/consul" // micro版本变迁
"log"
)
type logWrapper struct {
client.Client
}
func (this *logWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
md,_ := metadata.FromContext(ctx)
fmt.Printf("[Log Wrapper] ctx : %v service: %s method: %s\n", md, req.Service(), req.Endpoint())
return this.Client.Call(ctx, req, rsp)
}
func NewLogWrapper(c client.Client) client.Client {
return &logWrapper{c}
}
func main() {
consulReg := consul.NewRegistry(registry.Addrs("192.168.31.246:8500"))
r := gin.Default()
httpServer := web.NewService(
web.Name("httpService"),
//web.Address(flagParser()),
web.Address(":8001"),
web.Handler(r),
web.Registry(consulReg),
web.Metadata(map[string]string{"protocol": "http"}), // 为注册的服务添加Metadata,指定请求协议为http
)
myService := micro.NewService(micro.Name("prodService.client"), micro.WrapClient(NewLogWrapper))
prodService := Services.NewProdService("prodService", myService.Client())
v1Group := r.Group("/v1")
{
v1Group.Use(Server.InitMiddleware(prodService))
v1Group.Handle("POST", "/prods", func(c *gin.Context) {
Server.GetProdListServer(c)
})
}
err := httpServer.Init()
if err != nil {
log.Fatalln("Server Init error: ", err)
}
err = httpServer.Run()
if err != nil {
log.Fatal("Server Run error: ", err)
}
}
// simple 自定义命令行解析
func flagParser() string {
serverAddress := flag.String("server_address", ":8080", "服务端口")
flag.Parse()
fmt.Println("端口号:", *serverAddress)
return *serverAddress
}
测试接口时,终端输出
[Log Wrapper] ctx : map[Micro-From-Service:prodService.client] service: prodService method: ProdService.GetProdList