go语言进阶——项目实战

261 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 6 天

go语言进阶、依赖管理、项目实战(下)——项目实战

项目实战

image.png

以掘金的社区话题入口页面为需求模型,页面的功能包括活题详情,回帖例表,支持回帖,点赞,和回帖回复,开发一个惊页面交涉及的服务端小功能,

image.png

需求背景

需求描述

image.png

需求用例

image.png

ER图

image.png

分层结构

分层

(大体如此,具体的要根据项目的难度来分)

  • repository:封装模型,封装外部数据的curd,(类比pojo + mapper)
    • 主要是对外部数据进行封装。
    • 定义一些方法,和 “ db ” 打交道,返回查找到的结果。

image.png

image.png

单例模式 & 方法定义(以其中一个方法为例)

image.png

image.png

service:通过接收repository的一些数据做打包封装,会返回需要的数据(类比pojo+service)

以这个service为例,讲解一下执行过程:

image.png

image.png 续--------------

image.png 另外一个pageinfo的service同理:

  • 先写要定义本次的service需要用到的结构体。

  • 同样用链式的方法去执行Do

    • func QueryPageInfo(topicId int64) (*PageInfo, error) { return NewQueryPageInfoFlow(topicId).Do() }
  • 经过校验等一系列处理后,返回结构体中需要的信息。

controller:作为视图层,对上游负责,包装一些数据格式(比如json化一个数据结果)(类比controller)

  1. 处理接收到的参数,

  2. 调用service里面的方法,得到指定的返回数据,

  3. 将数据进行处理(如json化),进行返回。

    1. 上述步骤借助service.go一起完成

image.png

image.png

image.png

image.png

运行测试

  1. 执行service.go
  2. 在浏览器输入指定的url,如: http://localhost:8080/community/pagelget/1
  3. 得到json数据

image.png

{ "code" :0, "msg" : "success" , "data" :{ "TopicInfo" :{ "Topic" :{ "Id" :1, "UserId" :1, "Title" : "微服务的使用" , "Content" : "希望大家和我一起学习微服务" , "CreateTime" : "2023-01-16T17:52:30+08:00" }, "User" :{ "Id" :1, "Name" : "冰航" , "Avatar" : "" , "Level" :7, "CreateTime" : "2023-01-16T17:50:52+08:00" , "ModifyTime" : "2023-01-16T17:50:55+08:00" } }, "PostList" :[ { "Post" :{ "Id" :1, "ParentId" :1, "UserId" :2, "Content" : "收到" , "DiggCount" :0, "CreateTime" : "2023-01-16T17:53:16+08:00" }, "User" :{ "Id" :2, "Name" : "梁新锐" , "Avatar" : "" , "Level" :2, "CreateTime" : "2023-01-18T17:51:31+08:00" , "ModifyTime" : "2023-01-16T17:51:38+08:00" } }, { "Post" :{ "Id" :2, "ParentId" :1, "UserId" :1, "Content" : "收到请回复" , "DiggCount" :0, "CreateTime" : "2023-01-16T17:54:00+08:00" }, "User" :{ "Id" :1, "Name" : "冰航" , "Avatar" : "" , "Level" :7, "CreateTime" : "2023-01-16T17:50:52+08:00" , "ModifyTime" : "2023-01-16T17:50:55+08:00" } } ] } }