当前位置: 首页>后端>正文

go-zero网关的简单实用

依赖上文中的服务端代码部署

1. 初始化项目

mkdir Gateway
cd Gateway
mkdir proto
cd proto
touch user.proto

user.proto

syntax = "proto3";

package user;
  
// protoc-gen-go 版本大于1.4.0, proto文件需要加上go_package,否则无法生成
option go_package = "./user";

message IdRequest {
    int32 id = 1;
}
  
message UserResponse {
    // 用户id
    int32 id = 1;
    // 用户名称
    string name = 2;
    // 用户性别
    int32 gender = 3;
}

message UserOauthResponse {
    int32 id = 1;
    string nickname = 2;
    string avatar = 3;
}

message UserNameResponse {
    // 用户id
    int32 id = 1;
    // 用户名称
    string name = 2;
}

service User {
    rpc getUser(IdRequest) returns(UserResponse);
    rpc getUserOauth(IdRequest) returns(UserOauthResponse);
    rpc getUserName(IdRequest) returns(UserNameResponse);
}

2. 生成ProtocolBuff.pb文件

cd proto && mkdir pb

根目录下执行

protoc --descriptor_set_out=proto/pb/user.pb proto/user.proto

目录结构为

└── proto
    ├── pb
    │   └── user.pb
    └── user.proto

3. 创建配置文件

mkdir etc
touch gateway.yaml

gateway.yaml

Name: qt-api
Host: 0.0.0.0
Port: 8888
Upstreams:
  - Grpc:
      Etcd:
        Hosts:
        - 127.0.0.1:2379
        Key: user.rpc
      # protoset mode
    ProtoSets:
        - proto/pb/user.pb
    # Mappings can also be written in proto options
    Mappings:
      - Method: get
        Path: /ping
        RpcPath: user.User/getUser

4. 启动程序

初始化项目,新建main.go文件

go mod init gateway

main.go

package main

import (
    "flag"
    "fmt"

    "github.com/zeromicro/go-zero/core/conf"
    "github.com/zeromicro/go-zero/gateway"
)

var configFile = flag.String("f", "etc/gateway.yaml", "the config file")

func main() {
    flag.Parse()
    var c gateway.GatewayConf
    conf.MustLoad(*configFile, &c)
    server := gateway.MustNewServer(c)
    defer server.Stop()

    fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
    server.Start()
}
go mod tidy
go run main.go

此时,按照gateway.yaml中定义的路径,将会转发到rpc服务中

wancheng@MacBook-Pro-4 ~ % curl 127.0.0.1:8888/ping
{"id":0,"name":"来自rpc服务器0.0.0.0:8081返回的名字","gender":1}%    

源码 https://gitee.com/qq_connect-60293/gateway


https://www.xamrdz.com/backend/3u31931815.html

相关文章: