用golang grpc-gateway 写一个demo
时间: 2024-10-25 17:17:04 浏览: 15
go-grpc-gateway-v2-microservice:使用 Go + gRPC-Gateway 实战小程序登录鉴权微服务
在Go语言中,GRPC Gateway是一个工具,它允许你将现有的gRPC服务转换成HTTP API,而无需修改服务端代码。下面是一个简单的gRPC到HTTP的示例,我们将创建一个简单的`HelloService` gRPC服务,并通过Gateway将其暴露为RESTful API。
首先,安装必要的依赖:
```sh
go get google.golang.org/grpc
go get github.com/grpc-ecosystem/grpc-gateway/v2
```
然后,假设我们有一个名为`hello.proto`的协议定义文件,内容如下:
```protobuf
syntax = "proto3";
package hello;
service Hello {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
```
接下来,生成服务器和客户端代码:
```sh
protoc -I=$GOPATH/src -I=$SRC_DIR -o $GOPATH/src/hello/hello.pb.go $SRC_DIR/hello.proto
protoc -I=$GOPATH/src -I=$SRC_DIR --grpc-gateway_out=logtostderr=true:. $SRC_DIR/hello.proto
```
创建一个简单的`server/main.go`:
```go
package main
import (
"context"
"fmt"
"log"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
_ "github.com/grpc-ecosystem/grpc-gateway/v2/examples/helloworld"
"golang.org/x/net/context"
"hello/hellopb"
)
func main() {
lis, err := grpc.Listen("0.0.0.0:50051", nil)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
srv := grpc.NewServer()
hellopb.RegisterHelloServer(srv, &HelloServiceImpl{})
runtime.ServeGRPC(mux, srv)
fmt.Println("Starting server on port 50051")
if err := lis.Serve(); err != nil {
log.Fatal(err)
}
}
type HelloServiceImpl struct{}
func (h *HelloServiceImpl) SayHello(ctx context.Context, req *hellopb.HelloRequest) (*hellopb.HelloReply, error) {
return &hellopb.HelloReply{Message: fmt.Sprintf("Hello, %s!", req.Name)}, nil
}
```
最后,在`gateway/gateway.yaml`里配置路由:
```yaml
# gateway.yaml
openapi: 3.0.2
info:
title: Simple Greeting Service
version: 1.0.0
servers:
- url: http://localhost:8000/
paths:
/hello:
post:
summary: Greet a user
operationId: SayHello
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name:
type: string
description: The user's name
responses:
'200':
description: A successful response with the greeting.
content:
application/json:
schema:
type: object
properties:
message:
type: string
```
运行`server`和`gateway`:
```sh
go run server/main.go
go run gateway/gateway_main.go
```
现在你可以访问`http://localhost:8000/hello`并发送POST请求,数据包含`name`字段,服务器会返回一个问候消息。
阅读全文