测试完成可进行登陆,获取视频列表,需要完善测试视频返回及插入。

This commit is contained in:
lijun 2024-05-18 18:16:34 +08:00
parent 218e00c17f
commit 6ebdf684b8
8 changed files with 44 additions and 13 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
./videoplayer

View File

@ -14,5 +14,15 @@ func Init() {
if err != nil { if err != nil {
panic("failed to connect database") panic("failed to connect database")
} }
db.AutoMigrate(&User{}) // 自动迁移,创建表,如果表已经存在,会自动更新表结构,不会删除表,只会创建不存在的表
db.AutoMigrate(&Video{})
DB = db DB = db
} }
func Close() {
sqlDB, err := DB.DB()
if err != nil {
panic("failed to connect database")
}
sqlDB.Close()
}

View File

@ -1,5 +1,7 @@
package dao package dao
import "fmt"
type User struct { type User struct {
ID int `gorm:"primaryKey column:id"` ID int `gorm:"primaryKey column:id"`
Name string `gorm:"column:name"` Name string `gorm:"column:name"`
@ -30,6 +32,8 @@ func FindUserByID(id int) User {
func FindUserByName(name string) User { func FindUserByName(name string) User {
var user User var user User
DB.Migrator().RenameTable(&User{}, "user")
fmt.Println("name:", name)
DB.Debug().Where("name = ?", name).First(&user) DB.Debug().Where("name = ?", name).First(&user)
return user return user
} }

View File

@ -9,7 +9,7 @@ type Video struct {
VideoName string `gorm:"column:video_name"` VideoName string `gorm:"column:video_name"`
AuthId int `gorm:"column:auth_id"` AuthId int `gorm:"column:auth_id"`
Human int `gorm:"column:human"` Human int `gorm:"column:human"`
IsDelete int `gorm:"column:is_delete"` IsDelete int `gorm:"column:isdelete"`
CreateTime string `gorm:"column:create_time"` CreateTime string `gorm:"column:create_time"`
EndTime string `gorm:"column:end_time"` EndTime string `gorm:"column:end_time"`
DeleteTime string `gorm:"column:delete_time"` DeleteTime string `gorm:"column:delete_time"`
@ -30,18 +30,18 @@ func DeleteVideoByID(id int) int {
func FindVideoByID(id, auth_id int) Video { func FindVideoByID(id, auth_id int) Video {
var video Video var video Video
DB.Debug().Where("id = ? and auth_id = ?", id, auth_id).First(&video) DB.Debug().Where("id = ? and auth_id = ?", id, auth_id).Where("isdelete = ?", 0).First(&video)
return video return video
} }
func FindVideoListsByAuthID(auth_id int) []Video { func FindVideoListsByAuthID(auth_id int) []Video {
var videos []Video var videos []Video
DB.Debug().Where("auth_id = ?", auth_id).Where("is_delete=0").Find(&videos).Limit(30) DB.Debug().Where("auth_id = ?", auth_id).Where("isdelete = ?", 0).Limit(30).Find(&videos)
return videos return videos
} }
func FindVideoListByTime(auth_id int, startTime, endTime string) []Video { func FindVideoListByTime(auth_id int, startTime, endTime string) []Video {
var videos []Video var videos []Video
DB.Debug().Where("auth_id = ?", auth_id).Where("is_delete=0").Where("create_time > ? and create_time < ?", startTime, endTime).Find(&videos) DB.Debug().Where("auth_id = ?", auth_id).Where("isdelete=0").Where("create_time > ? and create_time < ?", startTime, endTime).Find(&videos)
return videos return videos
} }

View File

@ -24,6 +24,7 @@ type RLReq struct {
} }
func loginHandler(c *gin.Context) { func loginHandler(c *gin.Context) {
var req_data RLReq var req_data RLReq
tokenString := "" tokenString := ""
if err := c.ShouldBindJSON(&req_data); err == nil { if err := c.ShouldBindJSON(&req_data); err == nil {
@ -40,7 +41,7 @@ func loginHandler(c *gin.Context) {
c.JSON(400, gin.H{"error": err.Error(), "code": 1, "message": "error"}) c.JSON(400, gin.H{"error": err.Error(), "code": 1, "message": "error"})
return return
} }
worker.SetRedisWithExpire(req_data.User, tokenString, 600) // 设置过期时间为10分钟 worker.SetRedisWithExpire(tokenString, tokenString, time.Second*100) // 设置过期时间为10分钟
// 返回令牌 // 返回令牌
c.JSON(200, gin.H{"token": tokenString, "username": req_data.User, "code": 0, "message": "success"}) c.JSON(200, gin.H{"token": tokenString, "username": req_data.User, "code": 0, "message": "success"})
} else { } else {

View File

@ -82,7 +82,7 @@ func CreateVideo(c *gin.Context) {
func GetVideoList(c *gin.Context) { func GetVideoList(c *gin.Context) {
var gvl_req gvlReq var gvl_req gvlReq
if err := c.ShouldBindJSON(&gvl_req); err == nil { if err := c.ShouldBindJSON(&gvl_req); err == nil {
videos := service.GetVideoList(c.GetInt("id")) videos := service.GetVideoList(1)
c.JSON(http.StatusOK, gin.H{"videos": videos, "code": 0, "message": "success"}) c.JSON(http.StatusOK, gin.H{"videos": videos, "code": 0, "message": "success"})
} else { } else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "code": 1, "message": "failed"}) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "code": 1, "message": "failed"})

22
main.go
View File

@ -3,6 +3,7 @@ package main
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt" "github.com/golang-jwt/jwt"
"strings"
"videoplayer/dao" "videoplayer/dao"
"videoplayer/handler" "videoplayer/handler"
"videoplayer/worker" "videoplayer/worker"
@ -13,12 +14,14 @@ var signingKey = []byte("my_secret_key")
func main() { func main() {
r := gin.Default() r := gin.Default()
dao.Init()
worker.InitRedis()
r.Use(JWTAuthMiddleware()) // 使用 JWT 认证中间件 r.Use(JWTAuthMiddleware()) // 使用 JWT 认证中间件
handler.SetUpVideoGroup(r) handler.SetUpVideoGroup(r)
handler.SetUpUserGroup(r) handler.SetUpUserGroup(r)
dao.Init() r.Run(":8082") // listen and serve on 0.0.0.0:8082
worker.InitRedis() defer dao.Close()
r.Run("8082") // listen and serve on 0.0.0.0:8082 defer worker.CloseRedis()
} }
func JWTAuthMiddleware() gin.HandlerFunc { func JWTAuthMiddleware() gin.HandlerFunc {
@ -32,7 +35,7 @@ func JWTAuthMiddleware() gin.HandlerFunc {
} }
//如果请求为login或register则不需要验证token //如果请求为login或register则不需要验证token
if c.Request.URL.Path == "/login" || c.Request.URL.Path == "/register" { if strings.Contains(c.Request.URL.Path, "/login") || strings.Contains(c.Request.URL.Path, "/register") {
c.Next() c.Next()
return return
} }
@ -45,6 +48,17 @@ func JWTAuthMiddleware() gin.HandlerFunc {
}) })
return return
} }
redisToken := worker.GetRedis(tokenString)
if redisToken == "" {
c.AbortWithStatus(401)
c.JSON(401, gin.H{
"message": "Unauthorized",
"error": "server token is empty",
"code": "4",
})
return
}
// 解析 JWT 令牌 // 解析 JWT 令牌
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {

View File

@ -1,6 +1,7 @@
package worker package worker
import ( import (
"fmt"
"log" "log"
"time" "time"
) )
@ -15,7 +16,7 @@ func InitRedis() {
ctx := context.Background() ctx := context.Background()
// 连接redis // 连接redis
redisClient = redis.NewClient(&redis.Options{ redisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379", // Redis 服务器地址 Addr: "127.0.0.1:6379", // Redis 服务器地址
Password: "", // 如果 Redis 设置了密码 Password: "", // 如果 Redis 设置了密码
DB: 0, // 使用的数据库编号 DB: 0, // 使用的数据库编号
}) })
@ -57,7 +58,7 @@ func SetRedis(key string, value string) {
} }
// 设置redis // 设置redis
func SetRedisWithExpire(key string, value string, expire time.Duration) { func SetRedisWithExpire(key string, value string, expire time.Duration) { // 设置键值对, 0 表示不设置过期时间, 如果需要设置过期时间, 可以设置为 time.Second * 10 等
ctx := context.Background() ctx := context.Background()
// 设置键值对, 0 表示不设置过期时间, 如果需要设置过期时间, 可以设置为 time.Second * 10 等 // 设置键值对, 0 表示不设置过期时间, 如果需要设置过期时间, 可以设置为 time.Second * 10 等
err := redisClient.Set(ctx, key, value, expire).Err() err := redisClient.Set(ctx, key, value, expire).Err()
@ -71,7 +72,7 @@ func GetRedis(key string) string {
ctx := context.Background() ctx := context.Background()
val, err := redisClient.Get(ctx, key).Result() // 从 Redis 读取键值, 如果键不存在则返回空字符串, 如果出现错误则返回错误 val, err := redisClient.Get(ctx, key).Result() // 从 Redis 读取键值, 如果键不存在则返回空字符串, 如果出现错误则返回错误
if err != nil { if err != nil {
log.Fatalf("Error getting key: %v", err) fmt.Println("Error getting key: %v", err)
} }
return val return val
} }