Golang如何用工具一天内开发出社区后端服务的极简版本

Golang如何用工具一天内开发出社区后端服务的极简版本 点击查看完整的项目代码 https://github.com/zhufuyi/sponge_examples/blob/main/7_community-single

使用 sponge 工具,在代码生成过程中自动分离业务逻辑代码和非业务逻辑代码,使得开发只需专注于业务逻辑代码。

将一个完整的Web服务代码看作一个鸡蛋。蛋壳代表Web服务框架代码。蛋白和蛋黄代表业务逻辑代码。蛋黄是业务逻辑的核心(需要手动编写的代码),例如定义MySQL表、定义API接口、编写具体的逻辑代码。蛋白是连接核心业务逻辑代码与Web框架代码的桥梁(自动生成,无需手动编码),例如根据proto文件生成注册路由代码、handler方法函数代码、参数验证代码、错误码、Swagger文档等。Web服务鸡蛋模型分析图如下图所示:

en_web-http-pb-anatomy


更多关于Golang如何用工具一天内开发出社区后端服务的极简版本的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang如何用工具一天内开发出社区后端服务的极简版本的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用 sponge 工具确实可以快速生成社区后端服务的骨架代码,以下是一个基于 sponge 的极简开发流程示例:

  1. 安装 sponge
go install github.com/zhufuyi/sponge/cmd/sponge@latest
  1. 生成项目骨架
# 创建项目目录
mkdir community-service && cd community-service

# 初始化 go module
go mod init community-service

# 生成 HTTP 服务代码(基于 proto 文件)
sponge http server --module-name=community-service --server-name=community --project-name=community-service --protobuf-file=./api/community/v1/community.proto
  1. 定义业务数据结构(示例 proto 文件)
syntax = "proto3";

package api.community.v1;
option go_package = "community-service/api/community/v1;v1";

service Community {
  rpc CreatePost(CreatePostRequest) returns (CreatePostReply);
  rpc GetPost(GetPostRequest) returns (GetPostReply);
}

message CreatePostRequest {
  string title = 1;
  string content = 2;
  int64 user_id = 3;
}

message CreatePostReply {
  int64 id = 1;
}

message GetPostRequest {
  int64 id = 1;
}

message GetPostReply {
  int64 id = 1;
  string title = 2;
  string content = 3;
  int64 user_id = 4;
}
  1. 生成完整服务代码
# 生成 CRUD 代码(自动创建 handler、dao、model 等)
sponge http handler --module-name=community-service --server-name=community --project-name=community-service --protobuf-file=./api/community/v1/community.proto --out=./internal/service
  1. 实现业务逻辑(只需修改核心业务文件)
// internal/service/community.go
package service

import (
	"context"
	"community-service/internal/model"
)

func (s *communityService) CreatePost(ctx context.Context, req *v1.CreatePostRequest) (*v1.CreatePostReply, error) {
	post := &model.Post{
		Title:   req.Title,
		Content: req.Content,
		UserID:  req.UserId,
	}
	
	// 自动生成的 DAO 层方法
	err := s.dao.CreatePost(ctx, post)
	if err != nil {
		return nil, err
	}
	
	return &v1.CreatePostReply{Id: post.ID}, nil
}

func (s *communityService) GetPost(ctx context.Context, req *v1.GetPostRequest) (*v1.GetPostReply, error) {
	post, err := s.dao.GetPost(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	
	return &v1.GetPostReply{
		Id:      post.ID,
		Title:   post.Title,
		Content: post.Content,
		UserId:  post.UserID,
	}, nil
}
  1. 运行服务
# 生成 wire 依赖注入代码
sponge run

# 启动服务
go run cmd/community/main.go
  1. 自动生成的 API 文档访问
http://localhost:8080/apis/swagger/index.html

通过 sponge 工具,开发者只需完成第 3 步的 proto 定义和第 5 步的业务逻辑实现,其他代码(路由注册、参数校验、错误处理、数据库操作等)均由工具自动生成。这种方式确实可以在一天内完成社区后端服务的基础版本开发。

回到顶部