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

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 {
panic("failed to connect database")
}
db.AutoMigrate(&User{}) // 自动迁移,创建表,如果表已经存在,会自动更新表结构,不会删除表,只会创建不存在的表
db.AutoMigrate(&Video{})
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
import "fmt"
type User struct {
ID int `gorm:"primaryKey column:id"`
Name string `gorm:"column:name"`
@ -30,6 +32,8 @@ func FindUserByID(id int) User {
func FindUserByName(name string) User {
var user User
DB.Migrator().RenameTable(&User{}, "user")
fmt.Println("name:", name)
DB.Debug().Where("name = ?", name).First(&user)
return user
}

View File

@ -9,7 +9,7 @@ type Video struct {
VideoName string `gorm:"column:video_name"`
AuthId int `gorm:"column:auth_id"`
Human int `gorm:"column:human"`
IsDelete int `gorm:"column:is_delete"`
IsDelete int `gorm:"column:isdelete"`
CreateTime string `gorm:"column:create_time"`
EndTime string `gorm:"column:end_time"`
DeleteTime string `gorm:"column:delete_time"`
@ -30,18 +30,18 @@ func DeleteVideoByID(id int) int {
func FindVideoByID(id, auth_id int) 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
}
func FindVideoListsByAuthID(auth_id int) []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
}
func FindVideoListByTime(auth_id int, startTime, endTime string) []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
}

View File

@ -24,6 +24,7 @@ type RLReq struct {
}
func loginHandler(c *gin.Context) {
var req_data RLReq
tokenString := ""
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"})
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"})
} else {

View File

@ -82,7 +82,7 @@ func CreateVideo(c *gin.Context) {
func GetVideoList(c *gin.Context) {
var gvl_req gvlReq
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"})
} else {
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 (
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"strings"
"videoplayer/dao"
"videoplayer/handler"
"videoplayer/worker"
@ -13,12 +14,14 @@ var signingKey = []byte("my_secret_key")
func main() {
r := gin.Default()
dao.Init()
worker.InitRedis()
r.Use(JWTAuthMiddleware()) // 使用 JWT 认证中间件
handler.SetUpVideoGroup(r)
handler.SetUpUserGroup(r)
dao.Init()
worker.InitRedis()
r.Run("8082") // listen and serve on 0.0.0.0:8082
r.Run(":8082") // listen and serve on 0.0.0.0:8082
defer dao.Close()
defer worker.CloseRedis()
}
func JWTAuthMiddleware() gin.HandlerFunc {
@ -32,7 +35,7 @@ func JWTAuthMiddleware() gin.HandlerFunc {
}
//如果请求为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()
return
}
@ -45,6 +48,17 @@ func JWTAuthMiddleware() gin.HandlerFunc {
})
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 令牌
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {

View File

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