文章目录
- 一、建立路由
- 二、开发GetPostDetailHandler
- 三、编写logic
- 四、编写dao层
- 五、编译测试运行
一、建立路由
router/route.go
v1.GET("/post/:id", controller.GetPostDetailHandler)
二、开发GetPostDetailHandler
controller/post.go
func GetPostDetailHandler(c *gin.Context) {postIdStr := c.Param("id")postId, err := strconv.ParseInt(postIdStr, 10, 64)if err != nil {zap.L().Error("get post detail with invalid param", zap.Error(err))ResponseError(c, CodeInvalidParam)return}data, err := logic.GetPostById(postId)if err != nil {zap.L().Error("logic.GetPostById() failed", zap.Error(err))ResponseError(c, CodeServerBusy)return}ResponseSuccess(c, data)
三、编写logic
logic/post.go
package logicimport ("bluebell/dao/mysql""bluebell/models""go.uber.org/zap"
)// GetPostById 根据帖子id查询帖子详情数据
func GetPostById(pid int64) (data *models.ApiPostDetail, err error) {// 查询并组合我们接口想用的数据post, err := mysql.GetPostById(pid)if err != nil {zap.L().Error("mysql.GetPostById(pid) failed",zap.Int64("pid", pid),zap.Error(err))return}// 根据作者id查询作者信息user, err := mysql.GetUserById(post.AuthorId)fmt.Println(user.UserId, user.Username, *user)if err != nil {zap.L().Error("mysql.GetUserById(post.AuthorID) failed",zap.Int64("author_id", post.AuthorId),zap.Error(err))return}// 根据社区id查询社区详细信息community, err := mysql.GetCommunityDetailByID(post.CommunityId)if err != nil {zap.L().Error("mysql.GetUserById(post.AuthorID) failed",zap.Int64("community_id", post.CommunityId),zap.Error(err))return}// 接口数据拼接data = &models.ApiPostDetail{AuthorName: user.Username,Post: post,Community: community,}return
}
四、编写dao层
mysql/post.go:增加获取帖子详情函数
func GetPostById(id int64) (*models.Post, error) {post := &models.Post{}err := db.Where("id = ?", id).Find(&post).Errorreturn post, err
}