remove transport draft, add grpc web and gateway support

This commit is contained in:
2021-09-18 01:39:15 +02:00
parent 4085420f6f
commit 1eea54f18a
37 changed files with 2884 additions and 290 deletions

View File

@ -2,10 +2,13 @@ package main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"time"
"io/ioutil"
"net/http"
"strings"
"github.com/sirupsen/logrus"
@ -14,7 +17,7 @@ import (
"go.linka.cloud/grpc/service"
)
type GreeterHandler struct{
type GreeterHandler struct {
UnimplementedGreeterServer
}
@ -31,27 +34,29 @@ func (g *GreeterHandler) SayHelloStream(req *HelloStreamRequest, s Greeter_SayHe
if err := s.Send(&HelloReply{Message: fmt.Sprintf("Hello %s (%d)!", req.Name, i+1)}); err != nil {
return err
}
time.Sleep(time.Second)
// time.Sleep(time.Second)
}
return nil
}
func main() {
name := "greeter"
secure := true
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
ready := make(chan struct{})
defer cancel()
var svc service.Service
var err error
address := "0.0.0.0:9991"
svc, err = service.New(
service.WithContext(ctx),
service.WithName(name),
service.WithVersion("v0.0.1"),
service.WithAddress("0.0.0.0:9991"),
service.WithAddress(address),
service.WithRegistry(mdns.NewRegistry()),
service.WithReflection(true),
service.WithSecure(true),
service.WithSecure(secure),
service.WithAfterStart(func() error {
fmt.Println("Server listening on", svc.Options().Address())
close(ready)
@ -62,6 +67,10 @@ func main() {
close(done)
return nil
}),
service.WithGateway(RegisterGreeterHandler),
service.WithGatewayPrefix("/rest"),
service.WithGRPCWeb(true),
service.WithGRPCWebPrefix("/grpc"),
)
if err != nil {
panic(err)
@ -77,7 +86,7 @@ func main() {
client.WithName("greeter"),
client.WithVersion("v0.0.1"),
client.WithRegistry(mdns.NewRegistry()),
client.WithSecure(true),
client.WithSecure(secure),
)
if err != nil {
logrus.Fatal(err)
@ -91,7 +100,7 @@ func main() {
logrus.Infof("received message: %s", res.Message)
stream, err := g.SayHelloStream(context.Background(), &HelloStreamRequest{Name: "test", Count: 10})
if err != nil {
logrus.Fatal(err)
logrus.Fatal(err)
}
for {
m, err := stream.Recv()
@ -99,10 +108,38 @@ func main() {
break
}
if err != nil {
logrus.Fatal(err)
logrus.Fatal(err)
}
logrus.Infof("received stream message: %s", m.Message)
}
scheme := "http://"
if secure {
scheme = "https://"
}
httpc := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
req := `{"name":"test"}`
do := func(url, contentType string) {
resp, err := httpc.Post(url, contentType, strings.NewReader(req))
if err != nil {
logrus.Fatal(err)
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
logrus.Fatal(err)
}
logrus.Info(string(b))
}
do(scheme+address+"/rest/api/v1/greeter/hello", "application/json")
do(scheme+address+"/grpc/helloworld.Greeter/SayHello", "application/grpc-web+json")
cancel()
<-done
}