理解proto3协议
服务和方法
以 Service 结尾的API成为服务,比如 ServerService,每个服务下有很多方法,比如:
createServer
updateServerBasic
updateServerGroupIds
在通过HTTP协议调用API时,你需要组合服务和方法,作为方法的地址:
API接口地址/服务名/方法名
比如:
http://192.168.2.100/ServerService/createServer
接口参数解读
假设我们看到以下的接口参数定义:
// 创建服务
{
int64 userId;
int64 adminId;
string type;
string name;
string description;
// 配置相关
bytes serverNamesJSON;
bytes httpJSON;
bytes httpsJSON;
bytes tcpJSON;
bytes tlsJSON;
bytes unixJSON;
bytes udpJSON;
int64 webId;
bytes reverseProxyJSON;
[]int64 serverGroupIds;
int64 userPlanId;
}
其中:
- 每个字段定义都至少由两部分组成,最简单的定义为
字段类型 字段名,这里我们省略了字段编号; int64和string等都是字段数据类型,目前支持以下常用的数据类型:int64- 64位整型int32- 32位整型uint64- 无符号的64位整型uint32- 无符号的32位整型double- 双精度浮点数字float- 单精度浮点数字string- 字符串bool- 布尔值,在JSON中为true或者falsebytes- 二进制字节数组,通过JSON调用时,你需要先将数据转换为Base64格式,再传递到接口,比如:- 一个字符串的内容为
Hello, World,那么传递到bytes类型字段的时候就需要传递base64_encode('Hello, World'),最终值应该为SGVsbG8sIFdvcmxk - 一个JSON数据的内容为
{ "name": "goedge.cloud", "type": "domain"},那么传递到bytes类型字段的时候就需要传递base64_encode('{ "name": "goedge.cloud", "type": "domain"}'),最终值应该为eyAibmFtZSI6ICJnb2VkZ2UuY24iLCAidHlwZSI6ICJkb21haW4ifQ== - 一个文件内容的二进制内容同样也需要Base64编码处理
- 反之,对于接口返回的响应数据来说,你需要Base64 Decode处理才能得到原始数据
- 一个字符串的内容为
[]字段类型 字段名表示一个数组,字段类型部分表示字段值数组中的元素的类型,比如:[]int64 serverGroupIds表示serverGroupIds是一个数组,通过JSON调用时需要传递[ 1, 2, 3 ]这样格式的数据,其中int64规定了数组中的每一项必须是一个整型;[]string types表示types的值为[ "type1", "type2" ]这样的数组[]ServerGroup serverGroups表示serverGroups的只为[ serverGroup1, serverGroup2, serverGroup3 ]这样的数组,因为ServerGroup也是一个对象,所以我们可以展开来,最终的JSON为:[ { "id":1, "name": "分组1" }, { "id":2, "name": "分组2" }, { "id":3, "name": "分组3" } ]
整体转换为JSON
通过JSON调用API时,需要将proto3协议的数据转换为JSON。对于这个示例中,和JSON的对应关系为:
{
"userId": 35,
"adminId": 1,
"type": "httpProxy",
"name": "My site",
"description": "This is my site",
"serverNamesJSON": "ewogICJuYW1lIjogImdvZWRnZS5jbiIKfQ==",
"httpJSON": "...",
"httpsJSON": "...",
"tcpJSON": "...",
"tlsJSON": "...",
"unixJSON": "...",
"udpJSON": "...",
"webId": "...",
"reverseProxyJSON": "...",
"serverGroupIds": [1, 3, 5],
"userPlanId": 12
}
嵌套
JSON数据也支持嵌套:
{
"name": "Site",
"addr": {
"protocol": "http",
"host": "example.com",
"portRange": "80"
}
}
空参数
有些接口参数定义为:
{
}
像这样的接口需要传递的JSON为:
{}
即可。
字符集
GoEdge所有API都只支持UTF-8。