使用 Gin 和 GORM 实现视频 Feed 流、视频投稿和个人主页功能(demo版) | 青训营

257 阅读2分钟

本笔记将介绍如何使用 Go 语言中的Gin 框架和 GORM 框架实现一个简单的视频分享平台,包括视频 Feed 流、视频投稿和个人主页功能。

步骤 1: 安装 Gin 和 GORM

首先,我们需要使用 Go 模块管理工具来安装 Gin 和 GORM。在终端中执行以下命令:

go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql

步骤 2: 创建数据库表和模型

我们首先需要在数据库中创建两个表,一个用于存储用户信息,另一个用于存储视频信息。接下来,我们创建相应的 GORM 模型:

type User struct {
	ID       uint   `gorm:"primaryKey"`
	Username string `gorm:"unique"`
	// 其他用户信息...
	Videos   []Video // 用户的投稿视频
}

type Video struct {
	ID        uint   `gorm:"primaryKey"`
	Title     string
	URL       string
	UploadBy  uint // 关联 User 表
	CreatedAt time.Time
	// 其他视频信息...
}

步骤 3: 初始化 Gin 和数据库连接

main 函数中,我们初始化 Gin 和数据库连接,并进行路由设置:

func main() {
	// 连接数据库
	dsn := "username:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("Failed to connect to database")
	}
	Migrate(db) // 执行迁移

	// 初始化 Gin
	r := gin.Default()

	// 设置路由
	r.GET("/feed", GetFeed)
	r.POST("/upload", UploadVideo)
	r.GET("/user/:id", GetUserProfile)

	// 启动服务器
	r.Run(":8080")
}

步骤 4: 视频 Feed 流

实现视频 Feed 流功能,当用户访问 /feed 路由时,会获取按投稿时间倒序排列的视频列表并返回:

func GetFeed(c *gin.Context) {
	var videos []Video
	db.Order("created_at desc").Find(&videos)

	c.JSON(200, videos)
}

步骤 5: 视频投稿

实现视频投稿功能,当登录用户访问 /upload 路由时,将接收 POST 请求,解析请求体中的 JSON 数据,然后将用户投稿插入数据库:

func UploadVideo(c *gin.Context) {
	var newVideo Video
	if err := c.BindJSON(&newVideo); err != nil {
		c.JSON(400, gin.H{"error": "Invalid input"})
		return
	}

	// 获取登录用户信息(可以通过登录态或 Token 实现)
	// 假设 userId 是登录用户的 ID
	userId := uint(1)

	newVideo.UploadBy = userId
	newVideo.CreatedAt = time.Now()

	// 在数据库中创建新视频
	if err := db.Create(&newVideo).Error; err != nil {
		c.JSON(500, gin.H{"error": "Failed to upload video"})
		return
	}

	c.JSON(200, gin.H{"message": "Video uploaded successfully"})
}

步骤 6: 个人主页

实现个人主页功能,当用户访问 /user/:id 路由时,将根据用户 ID 查询用户基本信息和投稿列表并返回:

func GetUserProfile(c *gin.Context) {
	userId := c.Param("id")

	var user User
	if err := db.Preload("Videos").First(&user, userId).Error; err != nil {
		c.JSON(404, gin.H{"error": "User not found"})
		return
	}

	c.JSON(200, user)
}

总结

通过以上步骤,我们已经成功使用 Gin 和 GORM 实现了视频 Feed 流、视频投稿和个人主页功能。当用户访问 /feed 路由时,可以查看视频 Feed 流;当登录用户访问 /upload 路由时,可以投稿新视频;当用户访问 /user/:id 路由时,可以查看指定用户的基本信息和投稿列表。