Files
go-zero/example/rpc/server/unary/server.go

64 lines
1.3 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package main
import (
"context"
"flag"
"fmt"
2020-09-29 14:30:22 +08:00
"log"
2020-07-26 17:09:05 +08:00
"os"
"sync"
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/conf"
"github.com/tal-tech/go-zero/example/rpc/remote/unary"
2020-09-18 11:41:52 +08:00
"github.com/tal-tech/go-zero/zrpc"
2020-07-26 17:09:05 +08:00
"google.golang.org/grpc"
)
var configFile = flag.String("f", "etc/config.json", "the config file")
type GreetServer struct {
lock sync.Mutex
alive bool
downTime time.Time
}
func NewGreetServer() *GreetServer {
return &GreetServer{
alive: true,
}
}
func (gs *GreetServer) Greet(ctx context.Context, req *unary.Request) (*unary.Response, error) {
fmt.Println("=>", req)
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
return &unary.Response{
Greet: "hello from " + hostname,
}, nil
}
func main() {
flag.Parse()
2020-09-18 11:41:52 +08:00
var c zrpc.RpcServerConf
2020-07-26 17:09:05 +08:00
conf.MustLoad(*configFile, &c)
2020-09-18 11:41:52 +08:00
server := zrpc.MustNewServer(c, func(grpcServer *grpc.Server) {
2020-07-26 17:09:05 +08:00
unary.RegisterGreeterServer(grpcServer, NewGreetServer())
})
2020-09-29 14:30:22 +08:00
interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
st := time.Now()
resp, err = handler(ctx, req)
log.Printf("method: %s time: %v\n", info.FullMethod, time.Since(st))
return resp, err
}
server.AddUnaryInterceptors(interceptor)
2020-07-26 17:09:05 +08:00
server.Start()
}