如果无法查看图片, 请跳转博客正文: https://www.cnblogs.com/zolo/p/14066444.html
前述
本教程只说"实践",不谈"理论". 如果哪位觉得有趣, 可以加本人QQ(1255422783)详细交流!
问题
对于后端开发, 经常"众口难调". 一套业务逻辑却要三套不同实现API!
- 网页端要"http(json) api"(如restful api)
- 移动端要"websocket api"
- 服务端要"grpc api"
正题
本教程主要介绍如何使用"protogen + protoapi"的开发步骤.
源码仓库:https://github.com/fasgo/demo
开发步骤
第1步: Goland启用"GoModule"支持
Settings > Go > Go Modules > 打勾 Enable go modules intergration
第2步: 根据需求定义proto
syntax = "proto3";
package api;
// 学生数据结构
message Student {
uint64 sno = 1; // 学生编号
string name = 2; // 学生名称
uint32 age = 3; // 学生年龄
bool male = 4; // 性别为男
string desc = 5; // 学生介绍
}
// 搜索请求
message AllReq {
int32 from = 1; // 分页开始下标(从0开始)
int32 size = 2; // 分页大小
string search = 3; // 模糊查询的输入内容
string field = 4; // 查询结果排序字段
bool desc = 5; // 查询结果排序是否DESC
}
// 搜索响应
message AllRsp{
int32 total = 1; //查询结果总数
repeated Student data = 2; // 查询结果数据
}
// 所有方法都支持+JSON与+FORM,根据需求灵活配置
// 1. +JSON(Content-Type:application/json)
// 2. +FORM(Content-Type:application/x-www-form-urlencode或multipart/form-data)
service StudentService {
// +POST /demo/students
rpc Add(Student) returns (Student);
// +DELETE /demo/students/:sno
rpc Del(Student) returns (Student);
// +PUT /demo/students/:sno
rpc Upd(Student) returns (Student);
// +WBSK /demo/student/ws
// +GET /demo/students/:sno
rpc Get(Student) returns (Student);
// +GET /demo/students
rpc All(AllReq) returns (AllRsp);
}