Go使用protocolbuffer快速开发api服务教程

本文档提供了一个使用Go、ProtocolBuffer(protobuf)、gRPC和HTTP快速开发API服务的实践教程。通过启用GoModule、定义proto文件、执行protogen生成代码、实现service逻辑并注册服务,以及客户端测试,详述了从环境搭建到服务运行的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果无法查看图片, 请跳转博客正文: 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

image

第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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值