当前位置: 首页 > 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
}
http://www.xdnf.cn/news/256213.html

相关文章:

  • 纯前端Word文档在线预览工具
  • Fedora升级Google Chrome出现GPG check FAILED问题解决办法
  • PyTorch_创建张量
  • 爱胜品ICSP YPS-1133DN Plus黑白激光打印机报“自动进纸盒进纸失败”处理方法之一
  • 解决Flutter项目中Gradle构建Running Gradle task ‘assembleDebug‘卡顿问题的终极指南
  • 【AI面试准备】元宇宙测试:AI+低代码构建虚拟场景压力测试
  • InnoDB索引的原理
  • 模型上下文协议(MCP)
  • 学习记录:DAY22
  • 数字智慧方案5873丨智慧交通设计方案(57页PPT)(文末有下载方式)
  • 动态库与静态库的区别
  • 内置类型成员变量的初始化详解
  • PostgreSQL 的 VACUUM 与 VACUUM FULL 详解
  • 6.DOS
  • 数字世界的“私人车道“:网络切片如何用Python搭建专属通信高速路?
  • 情境领导理论——AI与思维模型【89】
  • 单片机-STM32部分:0、学习资料汇总
  • RISCV的smstateen-ssstateen扩展
  • Flutter——数据库Drift开发详细教程(二)
  • 使用python爬取百度搜索中关于python相关的数据信息
  • 重构编程范式:解码字节跳动 AI 原生 IDE Trae 的技术哲学与实践价值
  • 【数据库】四种连表查询:内连接,外连接,左连接,右连接
  • 【Vue】Vue与UI框架(Element Plus、Ant Design Vue、Vant)
  • 传奇各职业/战士/法师/道士手套/手镯/护腕/神秘腰带爆率及出处产出地/圣战/法神/天尊/祈祷/虹魔/魔血
  • Codex CLI轻量级 AI 编程智能体 :openai又放大招了
  • 西游记4:从弼马温到齐天大圣;太白金星的计划;
  • P1308 统计单词数详解
  • 关于CSDN创作的常用模板内容
  • 人车交叉作业防撞系统介绍
  • 第一章:A Primer on Memory Consistency and Cache Coherence - 2nd Edition