grpc/example/example.go

109 lines
2.4 KiB
Go
Raw Normal View History

2020-01-22 13:02:06 +00:00
package main
import (
"context"
"errors"
2020-01-22 13:02:06 +00:00
"fmt"
"io"
"time"
2020-01-22 13:02:06 +00:00
"github.com/sirupsen/logrus"
2021-07-17 20:40:06 +00:00
"go.linka.cloud/grpc/client"
"go.linka.cloud/grpc/registry/mdns"
"go.linka.cloud/grpc/service"
2020-01-22 13:02:06 +00:00
)
type GreeterHandler struct{
UnimplementedGreeterServer
}
2020-01-22 13:02:06 +00:00
func hello(name string) string {
return fmt.Sprintf("Hello %s !", name)
}
func (g *GreeterHandler) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) {
return &HelloReply{Message: hello(req.Name)}, nil
}
func (g *GreeterHandler) SayHelloStream(req *HelloStreamRequest, s Greeter_SayHelloStreamServer) error {
for i := int64(0); i < req.Count; i++ {
if err := s.Send(&HelloReply{Message: fmt.Sprintf("Hello %s (%d)!", req.Name, i+1)}); err != nil {
2020-01-22 13:02:06 +00:00
return err
}
time.Sleep(time.Second)
2020-01-22 13:02:06 +00:00
}
return nil
}
func main() {
name := "greeter"
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
ready := make(chan struct{})
2020-01-22 13:02:06 +00:00
defer cancel()
2020-01-22 20:20:18 +00:00
var svc service.Service
2020-01-22 13:02:06 +00:00
var err error
2020-01-22 20:20:18 +00:00
svc, err = service.New(
service.WithContext(ctx),
service.WithName(name),
service.WithVersion("v0.0.1"),
service.WithAddress("0.0.0.0:9991"),
service.WithRegistry(mdns.NewRegistry()),
service.WithReflection(true),
service.WithSecure(true),
2020-01-22 20:20:18 +00:00
service.WithAfterStart(func() error {
2020-01-22 13:02:06 +00:00
fmt.Println("Server listening on", svc.Options().Address())
close(ready)
2020-01-22 13:02:06 +00:00
return nil
}),
2020-01-22 20:20:18 +00:00
service.WithAfterStop(func() error {
2020-01-22 13:02:06 +00:00
fmt.Println("Stopping server")
close(done)
2020-01-22 13:02:06 +00:00
return nil
}),
)
if err != nil {
panic(err)
}
RegisterGreeterServer(svc, &GreeterHandler{})
go func() {
if err := svc.Start(); err != nil {
panic(err)
}
}()
<-ready
s, err := client.New(
client.WithName("greeter"),
client.WithVersion("v0.0.1"),
client.WithRegistry(mdns.NewRegistry()),
client.WithSecure(true),
)
if err != nil {
logrus.Fatal(err)
}
g := NewGreeterClient(s)
defer cancel()
res, err := g.SayHello(context.Background(), &HelloRequest{Name: "test"})
if err != nil {
logrus.Fatal(err)
2020-01-22 13:02:06 +00:00
}
logrus.Infof("received message: %s", res.Message)
stream, err := g.SayHelloStream(context.Background(), &HelloStreamRequest{Name: "test", Count: 10})
if err != nil {
logrus.Fatal(err)
}
for {
m, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
logrus.Fatal(err)
}
logrus.Infof("received stream message: %s", m.Message)
}
cancel()
<-done
2020-01-22 13:02:06 +00:00
}