Hertz 学习笔记(33)

374 阅读2分钟

使用 hz 接入第三方插件的示例

这里的两个例子还是 protobuf 和 thrift

protobuf

先看 makefile:

init_api:
	hz new -I=idl --idl=idl/hello/hello.proto --protoc-plugins=openapi::./docs --mod=middleware/hertz

update_api:
	hz update -I=idl --idl=idl/hello/hello.proto --protoc-plugins=openapi::./docs --mod=middleware/hertz

然后看 idl 文件夹里的内容:

// path: idl/hello/hello.proto
syntax = "proto3";

package hello;

option go_package = "middleware/hertz/biz/model/psm";

import "api.proto";
import "openapiv3/annotations.proto";
import "google/api/annotations.proto";

message HelloReq {
  option (openapi.v3.schema) = {
    title: "Hello - Request";
    description: "Hello - Request";
    required: [
      "Name"
    ];
  };

  string Name = 1[
    (api.query) = "name",
    (openapi.v3.property) = {
      title: "Name";
      description: "Name";
      type: "string";
      min_length: 1;
      max_length: 50;
    }
  ];
}

message HelloResp {
  string RespBody = 1[
    (openapi.v3.property) = {
      title: "response content";
      description: "response content";
      type: "string";
      min_length: 1;
      max_length: 80;
    }
  ];
}

service HelloService {
  rpc Method1(HelloReq) returns(HelloResp) {
    option (api.get) = "/hello";
    option(google.api.http) = {
      get: "/hello"
    };
    option(openapi.v3.operation) = {
      summary: "Hello - Get";
      description: "Hello - Get";
    };
  }
}

同样有一个用来扩展功能的文件:

// path: idl/api.proto
syntax = "proto2";

package api;

import "google/protobuf/descriptor.proto";

option go_package = "/api";

extend google.protobuf.FieldOptions {
  optional string raw_body = 50101;
  optional string query = 50102;
  optional string header = 50103;
  optional string cookie = 50104;
  optional string body = 50105;
  optional string path = 50106;
  optional string vd = 50107;
  optional string form = 50108;
  optional string go_tag = 51001;
  optional string js_conv = 50109;
}

extend google.protobuf.MethodOptions {
  optional string get = 50201;
  optional string post = 50202;
  optional string put = 50203;
  optional string delete = 50204;
  optional string patch = 50205;
  optional string options = 50206;
  optional string head = 50207;
  optional string any = 50208;
  optional string gen_path = 50301;
  optional string api_version = 50302;
  optional string tag = 50303;
  optional string name = 50304;
  optional string api_level = 50305;
  optional string serializer = 50306;
  optional string param = 50307;
  optional string baseurl = 50308;
}

extend google.protobuf.EnumValueOptions {
  optional int32 http_code = 50401;
}

然后其他的就没有什么了,你会发现这里这些设置和之前的例子里很相似,是因为 hz 这个命令行工具的例子里这些都不是重点。

thrift

所以在这个 thrift 的例子里就只有 makefile 值得一说,其他的部分之前已经提过了。

init_api:
	hz new --idl=idl/hello.thrift --thrift-plugins=validator

update_api:
	hz update --idl=idl/hello.thrift --thrift-plugins=validator