青训营项目实战1

项目实战

实现掘金青训营报名页码的后端部分

image-20230126130343565

需求描述

  • 展示话题(标题、文字描述)和回帖列表
  • 不考虑前端页面实现,仅实现一个本地web服务
  • 话题和回帖数据用文件存储

附加要求:

  • 支持发布帖子
  • 本地id生成要保证不重复
  • append文件 更新索引要注意Map的并发安全问题

项目概述

示例图如下:

https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ec319dffe6ae49ad977a8d6a092c7d42~tplv-k3u1fbpfcp-watermark.image?

项目分层结构如下:

https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d578dcdb48674044a09f6144daa380af~tplv-k3u1fbpfcp-watermark.image?
  • 数据层:Repository 直接同数据库或数据存储文件打交道,该部分需要对数据做初步的反序列化(将以二进制形式存储的数据转换为对象)并封装对数据的增删改查操作
  • 逻辑层: Service 处理核心业务的逻辑输出,接收Repository层的数据并进行打包封装
  • 视图层:Controller 处理和外部的交互逻辑,将经过上两层处理的数据以客户端需要的格式发送

代码实现

Repository部分:

首先使用map数据结构定义索引(按值查找,感觉像是一个哈希表),仅展示部分关键代码

//使用索引数据结构提高查询速度
var (
	topicIndexMap map[int64]*Topic
	postIndexMap  map[int64][]*Post
)
//将在磁盘中存储的数据映射到内存中的Map
func initTopicIndexMap(filePath string) error {
	open, err := os.Open(filePath + "topic")
	if err != nil {
		return err
	}
	scanner := bufio.NewScanner(open)
	topicTmpMap := make(map[int64]*Topic)
	for scanner.Scan() {
		text := scanner.Text()
		var topic Topic
		if err := json.Unmarshal([]byte(text), &topic); err != nil {
			return err
		}
		topicTmpMap[topic.Id] = &topic
	}
	topicIndexMap = topicTmpMap
	return nil
}

接着实现查询操作

type Topic struct {
	Id         int64  `json:"id"`
	Title      string `json:"title"`
	Content    string `json:"content"`
	CreateTime int64  `json:"create_time"`
}
//TopicDao没有实际效果,可能是类似c++中的命名空间,用来防止函数重名
type TopicDao struct {
}
var (
	topicDao  *TopicDao
	topicOnce sync.Once
)
func NewTopicDaoInstance() *TopicDao {
	topicOnce.Do(
		func() {
			topicDao = &TopicDao{}
		})
	return topicDao
}
//查询操作,直接按值查找
func (*TopicDao) QueryTopicById(id int64) *Topic {
	return topicIndexMap[id]
}

Service部分

实体:

type PageInfo struct {
	Topic    *repository.Topic
	PostList []*repository.Post
}

Service部分要执行的操作如下:

参数校验
准备数据
组装实体
func (f *QueryPageInfoFlow) Do() (*PageInfo, error) {
	//参数校验
	if err := f.checkParam(); err != nil {
		return nil, err
	}
	//准备数据
	if err := f.prepareInfo(); err != nil {
		return nil, err
	}
	//组装实体
	if err := f.packPageInfo(); err != nil {
		return nil, err
	}
	return f.pageInfo, nil
}
func (f *QueryPageInfoFlow) checkParam() error {
	if f.topicId <= 0 {
		return errors.New("topic id must be larger than 0")
	}
	return nil
}

func (f *QueryPageInfoFlow) prepareInfo() error {
	//获取topic信息
	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		defer wg.Done()
		topic := repository.NewTopicDaoInstance().QueryTopicById(f.topicId)
		f.topic = topic
	}()
	//获取post列表
	go func() {
		defer wg.Done()
		posts := repository.NewPostDaoInstance().QueryPostsByParentId(f.topicId)
		f.posts = posts
	}()
	wg.Wait() //等待信息从repository层返回
	return nil
}

func (f *QueryPageInfoFlow) packPageInfo() error {
	f.pageInfo = &PageInfo{
		Topic:    f.topic,
		PostList: f.posts,
	}
	return nil
}

Controller部分

定义返回的数据格式

type PageData struct {
	Code int64       `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

定义QueryPageInfo方法,根据topicId获取返回的数据

func QueryPageInfo(topicIdStr string) *PageData {
	topicId, err := strconv.ParseInt(topicIdStr, 10, 64)
	if err != nil {
		return &PageData{
			Code: -1,
			Msg:  err.Error(),
		}
	}
    //调用service层方法获得数据
	pageInfo, err := service.QueryPageInfo(topicId)
	if err != nil {
		return &PageData{
			Code: -1,
			Msg:  err.Error(),
		}
	}
	return &PageData{
		Code: 0,
		Msg:  "success",
		Data: pageInfo,
	}
}

Router部分

该部分主要实现以下操作:

  1. 初始化数据索引
  2. 初始化引擎配置
  3. 构建路由
  4. 启动服务
func main() {
	//初始化数据索引
	if err := Init("./data/"); err != nil {
		os.Exit(-1)
	}
	//初始化引擎配置
	r := gin.Default()
	//构建路由
	r.GET("/community/page/get/:id", func(c *gin.Context) {
		topicId := c.Param("id")
		topicId = strings.TrimLeft(topicId, ":,")
		println(topicId)
		data := cotroller.QueryPageInfo(topicId)
		c.JSON(200, data)
	})
	//启动服务
	err := r.Run()
	if err != nil {
		return
	}
}

使用postman测试接口:http://localhost:8080/community/page/get/:2

返回的json数据如下:

{
    "code": 0,
    "msg": "success",
    "data": {
        "Topic": {
            "id": 2,
            "title": "青训营来啦!",
            "content": "小哥哥,快到碗里来~",
            "create_time": 1650437640
        },
        "PostList": [
            {
                "id": 6,
                "parent_id": 2,
                "content": "小哥哥快来1",
                "create_time": 1650437621
            },
            {
                "id": 7,
                "parent_id": 2,
                "content": "小哥哥快来2",
                "create_time": 1650437622
            },
            {
                "id": 8,
                "parent_id": 2,
                "content": "小哥哥快来3",
                "create_time": 1650437623
            },
            {
                "id": 9,
                "parent_id": 2,
                "content": "小哥哥快来4",
                "create_time": 1650437624
            },
            {
                "id": 10,
                "parent_id": 2,
                "content": "小哥哥快来5",
                "create_time": 1650437625
            }
        ]
    }
}
      "content": "小哥哥快来4",
            "create_time": 1650437624
        },
        {
            "id": 10,
            "parent_id": 2,
            "content": "小哥哥快来5",
            "create_time": 1650437625
        }
    ]
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值