Go-web开发之帖子功能

帖子功能

route.go

	r.Use(middleware.JWTAuthMiddleware())
	{
		r.POST("/post", controller.CreatePostHandler)
		r.GET("/post/:id", controller.GetPostDetailHandler)
	}

post.go 定义帖子结构

type Post struct {
	Id          int64     `json:"id" gorm:"primaryKey"`
	PostId      int64     `json:"post_id" gorm:"column:post_id"`
	CommunityId int64     `json:"community_id" gorm:"column:community_id"`
	Status      int       `json:"status" gorm:"column:status" default:"0"`
	AuthorName  string    `json:"author_name" gorm:"column:author_name"`
	Title       string    `json:"title" gorm:"column:title"`
	Content     string    `json:"content" gorm:"column:content"`
	CreateTime  time.Time `json:"create_time" gorm:"column:create_time"`
	UpdateTime  time.Time `json:"update_time" gorm:"column:update_time"`
}

func (p *Post) TableName() string {
	return "post"
}

postDto.go

type PostDto struct {
	Status        int       `json:"status"`
	AuthorName    string    `json:"author_name"`
	Title         string    `json:"title"`
	Content       string    `json:"content"`
	CommunityName string    `json:"community_name"`
	CreateTime    time.Time `json:"create_time"`
	UpdateTime    time.Time `json:"update_time"`
}

postController.go 处理请求

func CreatePostHandler(c *gin.Context) {
    // 1. 获取参数和参数校验
    p := new(models.Post)
    err := c.ShouldBindJSON(p)
    if err != nil {
       c.JSON(http.StatusOK, gin.H{
          "code": 30001,
          "msg":  err.Error(),
       })
       zap.L().Error("Bad query params", zap.Error(err))
       return
    }
    if len(p.Title) == 0 || len(p.Content) == 0 {
       c.JSON(http.StatusOK, gin.H{
          "code": 30002,
          "msg":  errors.New("标题和内容不能为空").Error(),
       })
       return
    }
    authorName := c.GetString("username")
    p.AuthorName = authorName
    // 2. 业务处理
    success := logic.CreatePost(p)
    if !success {
       c.JSON(http.StatusOK, gin.H{
          "msg": "创建帖子失败",
       })
       return
    }

    // 3. 返回响应
    c.JSON(http.StatusOK, gin.H{
       "code": 20000,
       "msg":  "创建帖子成功",
    })
}

func GetPostDetailHandler(c *gin.Context) {
    // 1. 获取参数和参数校验
    p := new(models.Post)
    err := c.ShouldBindQuery(p)
    if err != nil {
       c.JSON(http.StatusOK, gin.H{
          "code": 30002,
          "msg":  err.Error(),
       })
       zap.L().Error("Bad query params", zap.Error(err))
       return
    }
    idStr, ok := c.Params.Get("id")
    if len(idStr) == 0 || !ok {
       c.JSON(http.StatusOK, gin.H{
          "code": 30003,
          "msg":  err.Error(),
       })
       return
    }
    pId, _ := strconv.ParseInt(idStr, 10, 64)
    // 2. 业务处理
    var postDto *models.PostDto
    postDto, err = logic.GetPostDetail(pId)
    if err != nil {
       c.JSON(http.StatusOK, gin.H{
          "code": 30004,
          "msg":  "获取帖子详情失败",
       })
       return
    }

    // 3. 返回响应
    c.JSON(http.StatusOK, gin.H{
       "code": 20000,
       "msg":  "获取帖子详情成功",
       "data": postDto,
    })
}

postLogic.go 处理逻辑

func CreatePost(post *models.Post) bool {
    if post == nil {
       return false
    }
    postUid, _ := snowflake.GetID()
    post.PostId = int64(postUid)
    post.CreateTime = time.Now()
    post.UpdateTime = time.Now()
    // 操作数据库
    err := mysql.CreatePost(post)
    if err != nil {
       zap.L().Error("CreatePost failed", zap.Error(err))
       return false
    }

    return true

}

func GetPostDetail(id int64) (*models.PostDto, error) {
    // 1. 参数校验
    if id <= 0 {
       return nil, nil
    }
    // 2. 业务处理
    post, err := mysql.GetPostDetail(id)
    if err != nil {
       zap.L().Error("GetPostDetail failed", zap.Error(err))
       return nil, err
    }
    community, err := mysql.QueryCommunityById(post.CommunityId)
    postDto := &models.PostDto{
       Status:        post.Status,
       AuthorName:    post.AuthorName,
       Title:         post.Title,
       Content:       post.Content,
       CommunityName: community.CommunityName,
       CreateTime:    post.CreateTime,
       UpdateTime:    post.UpdateTime,
    }

    return postDto, nil
}

postDao.go 操作数据库

func CreatePost(post *models.Post) error {
    err := db.Create(post).Error
    return err
}

func GetPostDetail(id int64) (*models.Post, error) {
    var post models.Post
    err := db.Where("post_id = ?", id).First(&post).Error
    if err != nil {
       return nil, err
    }
    return &post, nil
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值