feat : grpc小demo

master
liuhaotian 2022-01-14 19:55:07 +08:00
parent fa25d64ef0
commit e941a62b5e
3 changed files with 74 additions and 0 deletions

View File

@ -1,14 +1,19 @@
package handler
import (
"context"
"fmt"
"git.icechen.cn/monorepo/backend/app/brahma/api/murder/internal/error_process"
"git.icechen.cn/monorepo/backend/app/brahma/api/murder/internal/model"
"git.icechen.cn/monorepo/backend/app/brahma/api/murder/internal/service"
"git.icechen.cn/monorepo/backend/pkg/proto/brahma/murder"
"github.com/gofiber/fiber/v2"
ctxLogger "github.com/luizsuper/ctxLoggers"
"go.uber.org/zap"
"google.golang.org/grpc"
"log"
"strconv"
"time"
)
func GetScriptsH(ctx *fiber.Ctx) error {
@ -75,3 +80,24 @@ func DeleteScriptsH(ctx *fiber.Ctx) error {
}
return ctx.JSON(success(nil))
}
func HelloWorld() error {
// Set up a connection to the server.
conn, err := grpc.Dial("localhost:3000", grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := murder.NewHelloWorldClient(conn)
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.Login(ctx, &murder.HelloRequest{Code: "lht"})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Token)
return nil
}

View File

@ -0,0 +1,31 @@
package servesr
import (
"context"
"fmt"
"git.icechen.cn/monorepo/backend/pkg/proto/brahma/murder"
"google.golang.org/grpc"
"log"
"net"
)
type helloRequet struct {
murder.UnimplementedHelloWorldServer
}
func (helloRequet) Login(ctx context.Context, name *murder.HelloRequest) (*murder.HelloResponse, error) {
return &murder.HelloResponse{Token: name.Code}, nil
}
func RpcServer() {
lis, err := net.Listen("tcp", ":3000")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
murder.RegisterHelloWorldServer(s, &helloRequet{})
fmt.Println("lark server run in :3000")
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}

View File

@ -0,0 +1,17 @@
syntax = "proto3";
option go_package = "git.icechen.cn/monorepo/backend/pkg/proto/brahma/murder";
package example_service;
service HelloWorld {
rpc Login (HelloRequest) returns (HelloResponse) {}
}
message HelloRequest {
string code = 1;
}
message HelloResponse {
string token = 1;
}