Go-web开发之帖子功能

帖子功能

route.go

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

post.go 定义帖子结构

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

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 处理请求

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 处理逻辑

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 操作数据库

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
}
相关推荐
sharemylove7 小时前
Java集合框架全面详解
java·开发语言·经验分享·笔记·学习
圆心角9 小时前
代码也有折旧率
前端·程序员
CoderYanger9 小时前
Java EE 进阶:14.案例综合练习-博客系统(第二弹):博客详情+令牌技术
服务器·前端·spring boot·后端·spring·java-ee·github
郝学胜-神的一滴12 小时前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
kyriewen12 小时前
我测了 5 种关页上报,两种老写法一条都没发出去
前端·javascript·程序员
好焊孙辉13 小时前
一条产线省下 30 个电机位:Z 轴和 R 轴,该合成一个了
开发语言·r语言
布莱克60513 小时前
Swift 中的逃逸闭包与非逃逸闭包:@escaping 到底在做什么
开发语言·ios·swift·闭包·逃逸
郝学胜-神的一滴13 小时前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
吃我一窝jio14 小时前
Java IO流核心分类与应用
java·开发语言·笔记
不一样的少年_14 小时前
受够了当人肉传话筒:我把这 9 个 Agent 塞进了同一个聊天框
前端·agent·ai编程