hello.proto
syntax="proto3";
package pb;
option go_package = "./pb";
service Greeter {
rpc SayHello(HelloRequest) returns(HelloReply){}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
protoc -I . --go_out=. --go-grpc_out=. ./hello.proto
server
package main
import (
"context"
"flag"
"fmt"
"demo/protos"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"log"
"net"
)
var host = "127.0.0.1"
var (
ServiceName = flag.String("ServiceName", "hello_service", "service name")
Port = flag.Int("Port", 50001, "listening port")
)
type server struct {
}
func main() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", *Port))
if err != nil {
log.Fatalf("failed to listen:%s", err)
} else {
fmt.Printf("listen at :%d\n", *Port)
}
defer lis.Close()
s := grpc.NewServer()
defer s.GracefulStop()
protos.RegisterGreeterServer(s, &server{})
addr := fmt.Sprintf("%s:%d", host, *Port)
fmt.Printf("server add:%s\n", addr)
if err := s.Serve(lis); err != nil {
fmt.Printf("failed to server: %s", err)
}
}
func (s *server) SayHello(ctx context.Context, in *protos.HelloRequest) (*protos.HelloReply, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
fmt.Printf("get metadata error")
}else{
fmt.Println("get metadata success: ",md)
}
if t, ok := md["timestamp"]; ok {
fmt.Printf("timestamp from metadata:\n")
for i, e := range t {
fmt.Printf(" %d. %s\n", i, e)
}
}
if t1, ok1 := md["key1"]; ok1 {
fmt.Printf("key1 from metadata:\n")
for i, e := range t1 {
fmt.Printf(" %d . %s\n", i, e)
}
}
if len(md) > 0 {
for k, v := range md {
fmt.Printf("%v:%v\n", k, v)
}
}
return &protos.HelloReply{Message: "server: " + in.Name}, nil
}
client
package main
import (
"context"
"fmt"
"demo/protos"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"time"
)
const (
timestampFormat = time.StampNano
)
func main() {
conn, err := grpc.Dial("127.0.0.1:50001", grpc.WithInsecure())
if err != nil {
panic(err)
}
client := protos.NewGreeterClient(conn)
md := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
md = metadata.New(map[string]string{"key1": "val1", "key2": "val2"})
ctx := metadata.NewOutgoingContext(context.Background(), md)
resp, err := client.SayHello(ctx, &protos.HelloRequest{Name: "Hello"})
if err == nil {
fmt.Printf("Reply is : %s\n", resp.Message)
} else {
fmt.Printf("call server error:%s\n", err)
}
}
运行
go run server.go
listen at :50001
server add:127.0.0.1:50001
get metadata success: map[:authority:[127.0.0.1:50001] content-type:[application/grpc] key1:[val1] key2:[val2] user-agent:[grpc-go/1.53.0]]
key1 from metadata:
0 . val1
:authority:[127.0.0.1:50001]
content-type:[application/grpc]
user-agent:[grpc-go/1.53.0]
key2:[val2]
key1:[val1]
#########################
go run client.go
Reply is : server: Hello
标签:err,Grpc,fmt,server,grpc,Printf,metadata
From: https://www.cnblogs.com/qcy-blog/p/18408215