当前位置: 首页 > news >正文

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.PostDtopostDto, 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).Errorreturn err
}func GetPostDetail(id int64) (*models.Post, error) {var post models.Posterr := db.Where("post_id = ?", id).First(&post).Errorif err != nil {return nil, err}return &post, nil
}

相关文章:

  • 数值与字典解决方案第二十六讲:FILTER函数在去除数据的方法
  • 旧版本NotionNext图片失效最小改动解决思路
  • 对第三方软件开展安全测评,如何保障其安全使用?
  • AimRT从入门到精通 - 04RPC客户端和服务器
  • 【网络安全实验】SSL协议的应用
  • 【AI提示词】系统分析员
  • react + antd 实现后台管理系统
  • 计算机视觉的未来发展趋势
  • 【学习笔记】深入理解Java虚拟机学习笔记——第1章 走进Java
  • python实现基于Windows系统计算器程序
  • 复刻低成本机械臂 SO-ARM100 舵机配置篇(WSL)
  • FastAPI 与数据库交互示例
  • QGraphicsView QGraphicsScene QGraphicsItem 的关系
  • 文本中地理位置提取方法—正则和NLP模型
  • 吴恩达深度学习作业 RNN模型——字母级语言模型
  • Web 应用服务器:功能、类型与核心作用全解析
  • 写了个脚本将pdf转markdown
  • 题解传送门
  • 2025年- H18-Lc126-54.螺旋矩阵(矩阵)---java版
  • 【c++】【STL】priority_queue详解
  • 图忆|上海车展40年:中国人的梦中情车有哪些变化(下)
  • 马上评|启动最高层级医政调查,维护医学一方净土
  • “五一”假期首日国铁郑州局迎大客流,预计发送旅客逾95万人次
  • 北京亦庄启动青年人才创新创业生态示范区
  • 习近平主持召开部分省区市“十五五”时期经济社会发展座谈会
  • 出行注意防晒补水,上海五一假期以多云天气为主最高33℃