首页
/ gRPC-Gateway 示例项目教程

gRPC-Gateway 示例项目教程

2024-09-16 16:37:57作者:谭伦延

1. 项目目录结构及介绍

grpc-gateway-example/
├── Makefile
├── README.md
├── api/
│   ├── annotations.proto
│   ├── echo_service.proto
│   ├── http.proto
│   └── http.pb.gw.go
├── cmd/
│   └── server/
│       └── main.go
├── go.mod
├── go.sum
└── third_party/
    └── google/
        └── api/
            ├── annotations.proto
            └── http.proto

目录结构说明

  • api/: 包含项目的 Protobuf 文件和生成的 Go 代码。

    • annotations.proto: 定义了 gRPC-Gateway 所需的注解。
    • echo_service.proto: 定义了 Echo 服务的接口。
    • http.proto: 定义了 HTTP 相关的注解。
    • http.pb.gw.go: 生成的 gRPC-Gateway 代码。
  • cmd/server/: 包含项目的启动文件。

    • main.go: 项目的入口文件,负责启动 gRPC 和 HTTP 服务。
  • third_party/: 包含第三方依赖的 Protobuf 文件。

    • google/api/: 包含 Google API 的注解定义。
  • Makefile: 项目构建和生成代码的脚本。

  • go.modgo.sum: Go 模块依赖管理文件。

2. 项目的启动文件介绍

cmd/server/main.go

package main

import (
    "context"
    "flag"
    "net/http"

    "github.com/golang/glog"
    "github.com/grpc-ecosystem/grpc-gateway/runtime"
    "google.golang.org/grpc"

    gw "github.com/philips/grpc-gateway-example/api"
)

var (
    echoEndpoint = flag.String("echo_endpoint", "localhost:9090", "endpoint of YourService")
)

func run() error {
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    mux := runtime.NewServeMux()
    opts := []grpc.DialOption{grpc.WithInsecure()}
    err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts)
    if err != nil {
        return err
    }

    return http.ListenAndServe(":8080", mux)
}

func main() {
    flag.Parse()
    defer glog.Flush()

    if err := run(); err != nil {
        glog.Fatal(err)
    }
}

启动文件说明

  • main.go: 项目的入口文件,负责启动 gRPC 和 HTTP 服务。
    • run(): 函数负责初始化 gRPC-Gateway 的 HTTP 服务,并将其绑定到指定的端口(默认 8080)。
    • main(): 主函数,解析命令行参数并启动服务。

3. 项目的配置文件介绍

Makefile

all: generate

generate:
    protoc -I/usr/local/include -I. \
      -I$(GOPATH)/src \
      -I$(GOPATH)/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
      --go_out=plugins=grpc:. \
      --grpc-gateway_out=logtostderr=true:. \
      api/echo_service.proto

clean:
    rm -f api/*.pb.go
    rm -f api/*.pb.gw.go

配置文件说明

  • Makefile: 用于生成 Protobuf 文件的 Go 代码和 gRPC-Gateway 代码。
    • generate: 目标用于生成代码,使用 protoc 工具生成 gRPC 和 gRPC-Gateway 代码。
    • clean: 目标用于清理生成的代码文件。

通过以上步骤,您可以了解如何使用 gRPC-Gateway 示例项目,并根据需要进行扩展和修改。

登录后查看全文
热门项目推荐