From 4fef8c4d7ab766d16acd79c3efdd6efd9e375bc0 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Sat, 14 May 2022 00:24:58 +0800 Subject: [PATCH 01/70] =?UTF-8?q?=E5=88=9B=E5=BB=BAdev=E5=88=86=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d2f8f7..c322238 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -# tiktok +# tiktok-dev \ No newline at end of file From 375d96a8e793476484ed1bc8b4ca32ba24c4263e Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Mon, 16 May 2022 23:41:52 +0800 Subject: [PATCH 02/70] =?UTF-8?q?dev-20220516-=E6=9E=B6=E6=9E=84=20?= =?UTF-8?q?=E6=9E=B6=E6=9E=84=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/comment/commentService.go | 1 - service/comment/commentServiceImpl.go | 1 - service/comment/commentSub.go | 1 - service/commentService.go | 1 + service/commentServiceImpl.go | 1 + service/commentSub.go | 1 + service/follow/followService.go | 1 - service/follow/followServiceImpl.go | 1 - service/follow/followSub.go | 1 - service/followService.go | 1 + service/followServiceImpl.go | 1 + service/followSub.go | 1 + service/like/likeService.go | 1 - service/like/likeServiceImpl.go | 1 - service/like/likeSub.go | 1 - service/likeService.go | 1 + service/likeServiceImpl.go | 1 + service/likeSub.go | 1 + service/user/userService.go | 1 - service/user/userServiceImpl.go | 1 - service/user/userSub.go | 1 - service/userService.go | 1 + service/userServiceImpl.go | 1 + service/userSub.go | 1 + service/video/videoService.go | 1 - service/video/videoServiceImpl.go | 1 - service/video/videoSub.go | 1 - service/videoService.go | 1 + service/videoServiceImpl.go | 1 + service/videoSub.go | 1 + 30 files changed, 15 insertions(+), 15 deletions(-) delete mode 100644 service/comment/commentService.go delete mode 100644 service/comment/commentServiceImpl.go delete mode 100644 service/comment/commentSub.go create mode 100644 service/commentService.go create mode 100644 service/commentServiceImpl.go create mode 100644 service/commentSub.go delete mode 100644 service/follow/followService.go delete mode 100644 service/follow/followServiceImpl.go delete mode 100644 service/follow/followSub.go create mode 100644 service/followService.go create mode 100644 service/followServiceImpl.go create mode 100644 service/followSub.go delete mode 100644 service/like/likeService.go delete mode 100644 service/like/likeServiceImpl.go delete mode 100644 service/like/likeSub.go create mode 100644 service/likeService.go create mode 100644 service/likeServiceImpl.go create mode 100644 service/likeSub.go delete mode 100644 service/user/userService.go delete mode 100644 service/user/userServiceImpl.go delete mode 100644 service/user/userSub.go create mode 100644 service/userService.go create mode 100644 service/userServiceImpl.go create mode 100644 service/userSub.go delete mode 100644 service/video/videoService.go delete mode 100644 service/video/videoServiceImpl.go delete mode 100644 service/video/videoSub.go create mode 100644 service/videoService.go create mode 100644 service/videoServiceImpl.go create mode 100644 service/videoSub.go diff --git a/service/comment/commentService.go b/service/comment/commentService.go deleted file mode 100644 index a19b847..0000000 --- a/service/comment/commentService.go +++ /dev/null @@ -1 +0,0 @@ -package comment diff --git a/service/comment/commentServiceImpl.go b/service/comment/commentServiceImpl.go deleted file mode 100644 index a19b847..0000000 --- a/service/comment/commentServiceImpl.go +++ /dev/null @@ -1 +0,0 @@ -package comment diff --git a/service/comment/commentSub.go b/service/comment/commentSub.go deleted file mode 100644 index a19b847..0000000 --- a/service/comment/commentSub.go +++ /dev/null @@ -1 +0,0 @@ -package comment diff --git a/service/commentService.go b/service/commentService.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/commentService.go @@ -0,0 +1 @@ +package service diff --git a/service/commentServiceImpl.go b/service/commentServiceImpl.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/commentServiceImpl.go @@ -0,0 +1 @@ +package service diff --git a/service/commentSub.go b/service/commentSub.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/commentSub.go @@ -0,0 +1 @@ +package service diff --git a/service/follow/followService.go b/service/follow/followService.go deleted file mode 100644 index 68b614d..0000000 --- a/service/follow/followService.go +++ /dev/null @@ -1 +0,0 @@ -package follow diff --git a/service/follow/followServiceImpl.go b/service/follow/followServiceImpl.go deleted file mode 100644 index 68b614d..0000000 --- a/service/follow/followServiceImpl.go +++ /dev/null @@ -1 +0,0 @@ -package follow diff --git a/service/follow/followSub.go b/service/follow/followSub.go deleted file mode 100644 index 68b614d..0000000 --- a/service/follow/followSub.go +++ /dev/null @@ -1 +0,0 @@ -package follow diff --git a/service/followService.go b/service/followService.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/followService.go @@ -0,0 +1 @@ +package service diff --git a/service/followServiceImpl.go b/service/followServiceImpl.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/followServiceImpl.go @@ -0,0 +1 @@ +package service diff --git a/service/followSub.go b/service/followSub.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/followSub.go @@ -0,0 +1 @@ +package service diff --git a/service/like/likeService.go b/service/like/likeService.go deleted file mode 100644 index b887788..0000000 --- a/service/like/likeService.go +++ /dev/null @@ -1 +0,0 @@ -package like diff --git a/service/like/likeServiceImpl.go b/service/like/likeServiceImpl.go deleted file mode 100644 index b887788..0000000 --- a/service/like/likeServiceImpl.go +++ /dev/null @@ -1 +0,0 @@ -package like diff --git a/service/like/likeSub.go b/service/like/likeSub.go deleted file mode 100644 index b887788..0000000 --- a/service/like/likeSub.go +++ /dev/null @@ -1 +0,0 @@ -package like diff --git a/service/likeService.go b/service/likeService.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/likeService.go @@ -0,0 +1 @@ +package service diff --git a/service/likeServiceImpl.go b/service/likeServiceImpl.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/likeServiceImpl.go @@ -0,0 +1 @@ +package service diff --git a/service/likeSub.go b/service/likeSub.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/likeSub.go @@ -0,0 +1 @@ +package service diff --git a/service/user/userService.go b/service/user/userService.go deleted file mode 100644 index a00006b..0000000 --- a/service/user/userService.go +++ /dev/null @@ -1 +0,0 @@ -package user diff --git a/service/user/userServiceImpl.go b/service/user/userServiceImpl.go deleted file mode 100644 index a00006b..0000000 --- a/service/user/userServiceImpl.go +++ /dev/null @@ -1 +0,0 @@ -package user diff --git a/service/user/userSub.go b/service/user/userSub.go deleted file mode 100644 index a00006b..0000000 --- a/service/user/userSub.go +++ /dev/null @@ -1 +0,0 @@ -package user diff --git a/service/userService.go b/service/userService.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/userService.go @@ -0,0 +1 @@ +package service diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/userServiceImpl.go @@ -0,0 +1 @@ +package service diff --git a/service/userSub.go b/service/userSub.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/userSub.go @@ -0,0 +1 @@ +package service diff --git a/service/video/videoService.go b/service/video/videoService.go deleted file mode 100644 index 2c9ffe7..0000000 --- a/service/video/videoService.go +++ /dev/null @@ -1 +0,0 @@ -package video diff --git a/service/video/videoServiceImpl.go b/service/video/videoServiceImpl.go deleted file mode 100644 index 2c9ffe7..0000000 --- a/service/video/videoServiceImpl.go +++ /dev/null @@ -1 +0,0 @@ -package video diff --git a/service/video/videoSub.go b/service/video/videoSub.go deleted file mode 100644 index 2c9ffe7..0000000 --- a/service/video/videoSub.go +++ /dev/null @@ -1 +0,0 @@ -package video diff --git a/service/videoService.go b/service/videoService.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/videoService.go @@ -0,0 +1 @@ +package service diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/videoServiceImpl.go @@ -0,0 +1 @@ +package service diff --git a/service/videoSub.go b/service/videoSub.go new file mode 100644 index 0000000..6d43c33 --- /dev/null +++ b/service/videoSub.go @@ -0,0 +1 @@ +package service From 5fa776d4291a7ccd3a70a3f1289f330c7a5b8c69 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Mon, 16 May 2022 23:52:35 +0800 Subject: [PATCH 03/70] =?UTF-8?q?dev-20220516-video=20=E8=A7=86=E9=A2=91?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E7=BC=96=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/videoService.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/service/videoService.go b/service/videoService.go index 6d43c33..6618fc5 100644 --- a/service/videoService.go +++ b/service/videoService.go @@ -1 +1,32 @@ package service + +import ( + "mime/multipart" + "time" +) + +type Video struct { + Id int64 + Author User //todo 等user接口 + PlayUrl string + CoverUrl string + FavoriteCount int64 + CommentCount int64 + IsFavorite bool +} + +type VideoService interface { + // Feed + // 通过传入时间戳,当前用户的id,返回对应的视频数组,以及视频数组中最早的发布时间 + Feed(lastTime time.Time, userId int64) ([]Video, time.Time, error) + + // GetVideo + // 传入视频id获得对应的视频对象 + GetVideo(videoId int64) (Video, error) + // Publish + // 将传入的视频流保存在文件服务器中,并存储在mysql表中 + Publish(data *multipart.FileHeader, userId int64) error + // List + // 通过userId来查询对应用户发布的视频,并返回对应的视频数组 + List(userId int64) ([]Video, error) +} From 5cd3d4e089218922fe4adc7e346dd04464ee8bb1 Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Mon, 16 May 2022 23:55:46 +0800 Subject: [PATCH 04/70] init service interface -- lls --- service/followService.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/service/followService.go b/service/followService.go index 6d43c33..43cd0f9 100644 --- a/service/followService.go +++ b/service/followService.go @@ -1 +1,38 @@ +// Package service +// @Description 定义用户关系接口及方法 +// @Author lls +// @Update 20220516 package service + +// FollowService 定义用户关系接口以及用户关系中的各种方法 +type FollowService interface { + /* + 一、其他同学需要调用的业务方法。 + */ + // IsFollowing 根据当前用户id和目标用户id来判断当前用户是否关注了目标用户 + IsFollowing(userId int64, targetId int64) (bool, error) + // GetFollowerCnt 根据用户id来查询用户被多少其他用户关注 + GetFollowerCnt(userId int64) (int64, error) + // GetFollowingCnt 根据用户id来查询用户关注了多少其它用户 + GetFollowingCnt(userId int64) (int64, error) + /* + 二、直接request需要的业务方法 + */ + // AddFollowRelation 当前用户关注目标用户 + AddFollowRelation(userId int64, targetId int64) (bool, error) + // DeleteFollowRelation 当前用户取消对目标用户的关注 + DeleteFollowRelation(userId int64, targetId int64) (bool, error) + // GetFollowing 获取当前用户的关注列表 + GetFollowing(userId int64) ([]User, error) + // GetFollowers 获取当前用户的粉丝列表 + GetFollowers(userId int64) ([]User, error) +} + +// User 用户结构信息 +type User struct { + Id int64 `json:"id"` + Name string `json:"name"` + FollowCount int64 `json:"follow_count"` + FollowerCount int64 `json:"follower_count"` + isFollow bool `json:"is_follow"` +} From ee10a50f166ec926361c10971c0c06fa1f11b90f Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Tue, 17 May 2022 00:25:15 +0800 Subject: [PATCH 05/70] =?UTF-8?q?dev-20220517-like=20like=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E7=BC=96=E5=86=99=E5=92=8Clike=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/likeService.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/service/likeService.go b/service/likeService.go index 6d43c33..71d96e6 100644 --- a/service/likeService.go +++ b/service/likeService.go @@ -1 +1,29 @@ package service + +//Service 定义点赞状态和点赞数量 +type LikeService interface { + /* + 1.其他模块(video)需要使用的业务方法。 + */ + //IsFavorit 根据当前视频id判断是否点赞了该视频。 + IsFavourit(videoId int64, userId int64) (bool, error) + //FavouriteCount 根据当前视频id获取当前视频点赞数量。 + FavouriteCount(videoId int64) (int64, error) + + /* + 2.request需要实现的功能 + */ + + //当前用户对视频的点赞操作 ,并把这个行为更新到like表中。 + //当前操作行为,1点赞,2取消点赞。 + FavouriteAction(userId int64, videoId int64, action_type int32) error + //获取当前用户的所有点赞视频,调用videoService的方法 + GetFavouriteList(userId int64) ([]Video, error) +} + +type Like struct { + Id int64 + User_id int64 + Video_id int64 + Cancel int8 +} From 102c033f364d38c8e18a6dd449d9645a81a13b3e Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Tue, 17 May 2022 01:55:50 +0800 Subject: [PATCH 06/70] =?UTF-8?q?dev-20220517-like=20IsFavourit=E3=80=81Fa?= =?UTF-8?q?vouriteCount=E5=B7=B2=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/Initdao.go | 17 +++++++++++++++++ dao/LikeDao.go | 9 +++++++++ go.mod | 35 +++++++++++++++++++++++++++++++++++ service/likeService.go | 7 ------- service/likeServiceImpl.go | 37 +++++++++++++++++++++++++++++++++++++ 5 files changed, 98 insertions(+), 7 deletions(-) create mode 100644 dao/Initdao.go create mode 100644 dao/LikeDao.go diff --git a/dao/Initdao.go b/dao/Initdao.go new file mode 100644 index 0000000..d4de926 --- /dev/null +++ b/dao/Initdao.go @@ -0,0 +1,17 @@ +package dao + +import ( + "github.com/jinzhu/gorm" + _ "github.com/jinzhu/gorm/dialects/mysql" + "log" +) + +var Db *gorm.DB + +func init() { + var err error + Db, err = gorm.Open("mysql", "douyin:zjqxy@tcp(43.138.25.60:3306)/douyin/") + if err != nil { + log.Panicln("err:", err.Error()) + } +} diff --git a/dao/LikeDao.go b/dao/LikeDao.go new file mode 100644 index 0000000..3fff45f --- /dev/null +++ b/dao/LikeDao.go @@ -0,0 +1,9 @@ +package dao + +//like表的结构。 +type Like struct { + Id int64 //自增主键 + User_id int64 //点赞用户id + Video_id int64 //视频id + Cancel int8 //是否点赞,0为点赞,1为取消赞 +} diff --git a/go.mod b/go.mod index 0424739..7605bbd 100644 --- a/go.mod +++ b/go.mod @@ -2,3 +2,38 @@ module TikTok go 1.18 +require ( + github.com/dgrijalva/jwt-go v3.2.0+incompatible + github.com/gin-gonic/gin v1.7.7 + github.com/jinzhu/gorm v1.9.16 + github.com/swaggo/swag v1.8.1 +) + +require ( + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.20.0 // indirect + github.com/go-openapi/spec v0.20.6 // indirect + github.com/go-openapi/swag v0.21.1 // indirect + github.com/go-playground/locales v0.14.0 // indirect + github.com/go-playground/universal-translator v0.18.0 // indirect + github.com/go-playground/validator/v10 v10.11.0 // indirect + github.com/go-sql-driver/mysql v1.5.0 // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/leodido/go-urn v1.2.1 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattn/go-isatty v0.0.14 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/ugorji/go/codec v1.2.7 // indirect + golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f // indirect + golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 // indirect + golang.org/x/text v0.3.7 // indirect + golang.org/x/tools v0.1.10 // indirect + google.golang.org/protobuf v1.28.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) \ No newline at end of file diff --git a/service/likeService.go b/service/likeService.go index 71d96e6..3e9d6c4 100644 --- a/service/likeService.go +++ b/service/likeService.go @@ -20,10 +20,3 @@ type LikeService interface { //获取当前用户的所有点赞视频,调用videoService的方法 GetFavouriteList(userId int64) ([]Video, error) } - -type Like struct { - Id int64 - User_id int64 - Video_id int64 - Cancel int8 -} diff --git a/service/likeServiceImpl.go b/service/likeServiceImpl.go index 6d43c33..385162d 100644 --- a/service/likeServiceImpl.go +++ b/service/likeServiceImpl.go @@ -1 +1,38 @@ package service + +import ( + "TikTok/dao" + "errors" +) + +type LikeServiceImpl struct { + VideoService +} + +func (like *LikeServiceImpl) IsFavourit(videoId int64, userId int64) (bool, error) { + likedata := new(dao.Like) + if err := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId).First(&likedata); err != nil { + return true, errors.New("can't find this data") + } + if likedata.Cancel == 0 { + return true, nil + } else { + return false, nil + } +} + +func (like *LikeServiceImpl) FavouriteCount(videoId int64) (int64, error) { + var count int64 + if err := dao.Db.Table("likes").Where("video_id = ?", videoId).First(&count); err != nil { + return 0, errors.New("can't find this data") + } + return count, nil +} + +//func (like *LikeServiceImpl) FavouriteAction(userId int64, videoId int64, action_type int32) error { +// panic("implement me") +//} +// +//func (like *LikeServiceImpl) GetFavouriteList(userId int64) ([]Video, error) { +// panic("implement me") +//} From f0a8468ec3cf7d2dc36434d1c2f2a32d7979463c Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Mon, 16 May 2022 23:55:46 +0800 Subject: [PATCH 07/70] =?UTF-8?q?dev-20220516-follow=20=E5=88=9D=E5=A7=8B?= =?UTF-8?q?=E5=8C=96=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/followService.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/service/followService.go b/service/followService.go index 6d43c33..43cd0f9 100644 --- a/service/followService.go +++ b/service/followService.go @@ -1 +1,38 @@ +// Package service +// @Description 定义用户关系接口及方法 +// @Author lls +// @Update 20220516 package service + +// FollowService 定义用户关系接口以及用户关系中的各种方法 +type FollowService interface { + /* + 一、其他同学需要调用的业务方法。 + */ + // IsFollowing 根据当前用户id和目标用户id来判断当前用户是否关注了目标用户 + IsFollowing(userId int64, targetId int64) (bool, error) + // GetFollowerCnt 根据用户id来查询用户被多少其他用户关注 + GetFollowerCnt(userId int64) (int64, error) + // GetFollowingCnt 根据用户id来查询用户关注了多少其它用户 + GetFollowingCnt(userId int64) (int64, error) + /* + 二、直接request需要的业务方法 + */ + // AddFollowRelation 当前用户关注目标用户 + AddFollowRelation(userId int64, targetId int64) (bool, error) + // DeleteFollowRelation 当前用户取消对目标用户的关注 + DeleteFollowRelation(userId int64, targetId int64) (bool, error) + // GetFollowing 获取当前用户的关注列表 + GetFollowing(userId int64) ([]User, error) + // GetFollowers 获取当前用户的粉丝列表 + GetFollowers(userId int64) ([]User, error) +} + +// User 用户结构信息 +type User struct { + Id int64 `json:"id"` + Name string `json:"name"` + FollowCount int64 `json:"follow_count"` + FollowerCount int64 `json:"follower_count"` + isFollow bool `json:"is_follow"` +} From 91604cc05997f5e91bf017e05c331012f1117580 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Mon, 16 May 2022 23:52:35 +0800 Subject: [PATCH 08/70] =?UTF-8?q?dev-20220516-video=20=E8=A7=86=E9=A2=91?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E7=BC=96=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/videoService.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/service/videoService.go b/service/videoService.go index 6d43c33..6618fc5 100644 --- a/service/videoService.go +++ b/service/videoService.go @@ -1 +1,32 @@ package service + +import ( + "mime/multipart" + "time" +) + +type Video struct { + Id int64 + Author User //todo 等user接口 + PlayUrl string + CoverUrl string + FavoriteCount int64 + CommentCount int64 + IsFavorite bool +} + +type VideoService interface { + // Feed + // 通过传入时间戳,当前用户的id,返回对应的视频数组,以及视频数组中最早的发布时间 + Feed(lastTime time.Time, userId int64) ([]Video, time.Time, error) + + // GetVideo + // 传入视频id获得对应的视频对象 + GetVideo(videoId int64) (Video, error) + // Publish + // 将传入的视频流保存在文件服务器中,并存储在mysql表中 + Publish(data *multipart.FileHeader, userId int64) error + // List + // 通过userId来查询对应用户发布的视频,并返回对应的视频数组 + List(userId int64) ([]Video, error) +} From 360a9d53f33a1e2911afc1a667673fe5cb3c015c Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Tue, 17 May 2022 00:25:15 +0800 Subject: [PATCH 09/70] =?UTF-8?q?dev-20220517-like=20like=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E7=BC=96=E5=86=99=E5=92=8Clike=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/likeService.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/service/likeService.go b/service/likeService.go index 6d43c33..71d96e6 100644 --- a/service/likeService.go +++ b/service/likeService.go @@ -1 +1,29 @@ package service + +//Service 定义点赞状态和点赞数量 +type LikeService interface { + /* + 1.其他模块(video)需要使用的业务方法。 + */ + //IsFavorit 根据当前视频id判断是否点赞了该视频。 + IsFavourit(videoId int64, userId int64) (bool, error) + //FavouriteCount 根据当前视频id获取当前视频点赞数量。 + FavouriteCount(videoId int64) (int64, error) + + /* + 2.request需要实现的功能 + */ + + //当前用户对视频的点赞操作 ,并把这个行为更新到like表中。 + //当前操作行为,1点赞,2取消点赞。 + FavouriteAction(userId int64, videoId int64, action_type int32) error + //获取当前用户的所有点赞视频,调用videoService的方法 + GetFavouriteList(userId int64) ([]Video, error) +} + +type Like struct { + Id int64 + User_id int64 + Video_id int64 + Cancel int8 +} From 18d3663d765a293dec7e747d6ce958a1d6204262 Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Tue, 17 May 2022 01:55:50 +0800 Subject: [PATCH 10/70] =?UTF-8?q?dev-20220517-like=20IsFavourit=E3=80=81Fa?= =?UTF-8?q?vouriteCount=E5=B7=B2=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/Initdao.go | 17 +++++++++++++++++ dao/LikeDao.go | 9 +++++++++ go.mod | 35 +++++++++++++++++++++++++++++++++++ service/likeService.go | 7 ------- service/likeServiceImpl.go | 37 +++++++++++++++++++++++++++++++++++++ 5 files changed, 98 insertions(+), 7 deletions(-) create mode 100644 dao/Initdao.go create mode 100644 dao/LikeDao.go diff --git a/dao/Initdao.go b/dao/Initdao.go new file mode 100644 index 0000000..d4de926 --- /dev/null +++ b/dao/Initdao.go @@ -0,0 +1,17 @@ +package dao + +import ( + "github.com/jinzhu/gorm" + _ "github.com/jinzhu/gorm/dialects/mysql" + "log" +) + +var Db *gorm.DB + +func init() { + var err error + Db, err = gorm.Open("mysql", "douyin:zjqxy@tcp(43.138.25.60:3306)/douyin/") + if err != nil { + log.Panicln("err:", err.Error()) + } +} diff --git a/dao/LikeDao.go b/dao/LikeDao.go new file mode 100644 index 0000000..3fff45f --- /dev/null +++ b/dao/LikeDao.go @@ -0,0 +1,9 @@ +package dao + +//like表的结构。 +type Like struct { + Id int64 //自增主键 + User_id int64 //点赞用户id + Video_id int64 //视频id + Cancel int8 //是否点赞,0为点赞,1为取消赞 +} diff --git a/go.mod b/go.mod index 0424739..7605bbd 100644 --- a/go.mod +++ b/go.mod @@ -2,3 +2,38 @@ module TikTok go 1.18 +require ( + github.com/dgrijalva/jwt-go v3.2.0+incompatible + github.com/gin-gonic/gin v1.7.7 + github.com/jinzhu/gorm v1.9.16 + github.com/swaggo/swag v1.8.1 +) + +require ( + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.20.0 // indirect + github.com/go-openapi/spec v0.20.6 // indirect + github.com/go-openapi/swag v0.21.1 // indirect + github.com/go-playground/locales v0.14.0 // indirect + github.com/go-playground/universal-translator v0.18.0 // indirect + github.com/go-playground/validator/v10 v10.11.0 // indirect + github.com/go-sql-driver/mysql v1.5.0 // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/leodido/go-urn v1.2.1 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattn/go-isatty v0.0.14 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/ugorji/go/codec v1.2.7 // indirect + golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f // indirect + golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 // indirect + golang.org/x/text v0.3.7 // indirect + golang.org/x/tools v0.1.10 // indirect + google.golang.org/protobuf v1.28.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) \ No newline at end of file diff --git a/service/likeService.go b/service/likeService.go index 71d96e6..3e9d6c4 100644 --- a/service/likeService.go +++ b/service/likeService.go @@ -20,10 +20,3 @@ type LikeService interface { //获取当前用户的所有点赞视频,调用videoService的方法 GetFavouriteList(userId int64) ([]Video, error) } - -type Like struct { - Id int64 - User_id int64 - Video_id int64 - Cancel int8 -} diff --git a/service/likeServiceImpl.go b/service/likeServiceImpl.go index 6d43c33..385162d 100644 --- a/service/likeServiceImpl.go +++ b/service/likeServiceImpl.go @@ -1 +1,38 @@ package service + +import ( + "TikTok/dao" + "errors" +) + +type LikeServiceImpl struct { + VideoService +} + +func (like *LikeServiceImpl) IsFavourit(videoId int64, userId int64) (bool, error) { + likedata := new(dao.Like) + if err := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId).First(&likedata); err != nil { + return true, errors.New("can't find this data") + } + if likedata.Cancel == 0 { + return true, nil + } else { + return false, nil + } +} + +func (like *LikeServiceImpl) FavouriteCount(videoId int64) (int64, error) { + var count int64 + if err := dao.Db.Table("likes").Where("video_id = ?", videoId).First(&count); err != nil { + return 0, errors.New("can't find this data") + } + return count, nil +} + +//func (like *LikeServiceImpl) FavouriteAction(userId int64, videoId int64, action_type int32) error { +// panic("implement me") +//} +// +//func (like *LikeServiceImpl) GetFavouriteList(userId int64) ([]Video, error) { +// panic("implement me") +//} From f25dcd5b13252b029654741394f03ebf2ce91b74 Mon Sep 17 00:00:00 2001 From: siyuanli Date: Tue, 17 May 2022 09:40:39 +0800 Subject: [PATCH 11/70] =?UTF-8?q?dev-20220517-Comment=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=AF=84=E8=AE=BA=E6=A8=A1=E5=9D=97=E6=8E=A5=E5=8F=A3=EF=BC=8C?= =?UTF-8?q?dao=E5=B1=82=E6=B7=BB=E5=8A=A0CommentDao.go=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/CommentDao.go | 11 +++++++++ service/commentService.go | 38 +++++++++++++++++++++++++++++++ service/commentServiceImpl.go | 42 +++++++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 dao/CommentDao.go diff --git a/dao/CommentDao.go b/dao/CommentDao.go new file mode 100644 index 0000000..e92e4d9 --- /dev/null +++ b/dao/CommentDao.go @@ -0,0 +1,11 @@ +package dao + +//评论信息-数据库中的结构体-dao层使用 +type Comment struct { + Id int64 //评论id + User_id int64 //评论用户id + Video_id int64 //视频id + Content string //评论内容 + Create_date string //评论发布的日期mm-dd + Cancel int32 //取消评论为1,发布评论为0 +} diff --git a/service/commentService.go b/service/commentService.go index 6d43c33..f44c88f 100644 --- a/service/commentService.go +++ b/service/commentService.go @@ -1 +1,39 @@ package service + +//发表评论-使用的结构体-service层引用dao层↑的Comment。 +//接口定义(CommentService.go) +type CommentService interface { + /* + 一、其他同学(video)需要使用的方法: + */ + //1.根据videoid获取视频评论数量的接口 + CountFromVideoId(id int64) (int64, error) + + /* + 二、评论模块自己request实现的方法: + */ + //2、发表评论,传进来评论的基本信息,返回保存是否成功的状态描述 + Send(comment *Comment) error + //3、删除评论,传入评论id即可,返回错误状态信息 + DelComment(id int64) error + //4、查看评论列表-返回评论list-在controller层再封装外层的状态信息 + GetList(vedioId int64, userId int64) ([]CommentInfo, error) +} + +//查看评论-传出的结构体-service +type CommentInfo struct { + Id int64 //评论id + UserInfo User //评论用户的信息-由用户模块赞助 + Content string //评论内容 + Create_date string //评论发布的日期mm-dd +} + +//评论信息-数据库中的结构体-dao层使用-先放这,import不了 +type Comment struct { + Id int64 //评论id + User_id int64 //评论用户id + Video_id int64 //视频id + Content string //评论内容 + Create_date string //评论发布的日期mm-dd + Cancel int32 //取消评论为1,发布评论为0 +} diff --git a/service/commentServiceImpl.go b/service/commentServiceImpl.go index 6d43c33..f0b157a 100644 --- a/service/commentServiceImpl.go +++ b/service/commentServiceImpl.go @@ -1 +1,43 @@ package service + +import ( + "TikTok/dao" + "errors" +) + +type CommentServiceImpl struct { +} + +//1、使用video id 查询Comment数量 +func (c CommentServiceImpl) CountFromVideoId(id int64) (int64, error) { + var count int64 + if err := dao.Db.Table("comments").Where("id = ?", id).First(&count); err != nil { + return -1, errors.New("can't find commentsCount") + } + return count, nil +} + +//2、发表评论 +func (c CommentServiceImpl) Send(comment *Comment) error { + if comment.Id == 0 { + return errors.New("Comment id = 0") + } + return nil +} + +//3、删除评论,传入评论id +func (c CommentServiceImpl) DelComment(id int64) error { + if id == 0 { + return errors.New("Comment id = 0") + } + return nil +} + +//4、查看评论列表-返回评论list +func (c CommentServiceImpl) GetList(vedioId int64, userId int64) ([]CommentInfo, error) { + //comment := new(dao.Comment) + if vedioId == 0 || userId == 0 { + return nil, errors.New("id = 0") + } + return nil, nil +} From b32bb343193083d9a594dc5d537dccae1278e659 Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Tue, 17 May 2022 09:44:31 +0800 Subject: [PATCH 12/70] =?UTF-8?q?dev-20220517-like=20IsFavourit=E3=80=81Fa?= =?UTF-8?q?vouriteCount=E5=B7=B2=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/likeServiceImpl.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service/likeServiceImpl.go b/service/likeServiceImpl.go index 385162d..29e2068 100644 --- a/service/likeServiceImpl.go +++ b/service/likeServiceImpl.go @@ -12,7 +12,7 @@ type LikeServiceImpl struct { func (like *LikeServiceImpl) IsFavourit(videoId int64, userId int64) (bool, error) { likedata := new(dao.Like) if err := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId).First(&likedata); err != nil { - return true, errors.New("can't find this data") + return false, errors.New("can't find this data") } if likedata.Cancel == 0 { return true, nil @@ -23,7 +23,7 @@ func (like *LikeServiceImpl) IsFavourit(videoId int64, userId int64) (bool, erro func (like *LikeServiceImpl) FavouriteCount(videoId int64) (int64, error) { var count int64 - if err := dao.Db.Table("likes").Where("video_id = ?", videoId).First(&count); err != nil { + if err := dao.Db.Table("likes").Where("video_id = ?", videoId).Count(&count); err != nil { return 0, errors.New("can't find this data") } return count, nil From d41c12f5d4ff546f3ef8bd745726f26cb1e9a4dd Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Tue, 17 May 2022 10:03:27 +0800 Subject: [PATCH 13/70] =?UTF-8?q?dev-20220517-user=20userService=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 1 - go.sum | 2 -- service/userService.go | 43 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 7605bbd..62c7cc2 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module TikTok go 1.18 require ( - github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gin-gonic/gin v1.7.7 github.com/jinzhu/gorm v1.9.16 github.com/swaggo/swag v1.8.1 diff --git a/go.sum b/go.sum index 45d36ac..d2d2f11 100644 --- a/go.sum +++ b/go.sum @@ -9,8 +9,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM= github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= -github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= diff --git a/service/userService.go b/service/userService.go index 6d43c33..427f41d 100644 --- a/service/userService.go +++ b/service/userService.go @@ -1 +1,44 @@ package service + +type UserService interface { + /* + 个人使用 + */ + // GetTableUserList GetUserList 获得全部TableUser对象 + GetTableUserList(users *[]TableUser) bool + + // GetTableUserByUsername GetUserByUsername 根据username获得TableUser对象 + GetTableUserByUsername(name string) bool + + // GetTableUserById GetUserById 根据user_id获得TableUser对象 + GetTableUserById(id int64) bool + + /* + 他人使用 + */ + // GetUserById 未登录情况下,根据user_id获得User对象 + //(调用方法:user.GetUserById,user会被填充;若填充失败,则返回false,成功,返回true) + GetUserById(id int64) (User, error) + + // GetUserByIdWithCurId 已登录(curID)情况下,根据user_id获得User对象 + GetUserByIdWithCurId(id int64, curId int64) (User, error) + + // 根据token返回id + // 接口:auth中间件,解析完token,将userid放入context + //(调用方法:直接在context内拿参数"user_id"的值) +} + +type TableUser struct { + Id int64 + Name string + Password string +} + +/*type User struct { + Id int64 `json:"id,omitempty"` + Name string `json:"name,omitempty"` + FollowCount int64 `json:"follow_count,omitempty"` + FollowerCount int64 `json:"follower_count,omitempty"` + IsFollow bool `json:"is_follow,omitempty"` +} +*/ From ede6da308e032857bee937a2a9fec2f50dc69cc6 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Tue, 17 May 2022 10:08:33 +0800 Subject: [PATCH 14/70] =?UTF-8?q?dev-20220517-user=20userService=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/userService.go | 1 - 1 file changed, 1 deletion(-) diff --git a/service/userService.go b/service/userService.go index 427f41d..ad003e1 100644 --- a/service/userService.go +++ b/service/userService.go @@ -17,7 +17,6 @@ type UserService interface { 他人使用 */ // GetUserById 未登录情况下,根据user_id获得User对象 - //(调用方法:user.GetUserById,user会被填充;若填充失败,则返回false,成功,返回true) GetUserById(id int64) (User, error) // GetUserByIdWithCurId 已登录(curID)情况下,根据user_id获得User对象 From 5fc72a1a0067beeacf3e8c27c9f023d8f9a67a40 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Tue, 17 May 2022 10:44:52 +0800 Subject: [PATCH 15/70] =?UTF-8?q?dev-20220517-user=20userServiceImpl?= =?UTF-8?q?=E7=BB=93=E6=9E=84=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.go | 7 ++++ dao/UserDao.go | 8 +++++ go.mod | 3 +- go.sum | 2 ++ middleware/Auth.go | 50 +++++++++++++++++++++++++++++ service/userService.go | 18 +++++------ service/userServiceImpl.go | 65 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 143 insertions(+), 10 deletions(-) create mode 100644 config/config.go create mode 100644 dao/UserDao.go create mode 100644 middleware/Auth.go diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..216d3db --- /dev/null +++ b/config/config.go @@ -0,0 +1,7 @@ +package config + +var Secret = "tiktok" + +var OneDayOfHours = 60 * 60 * 24 +var OneMinute = 60 * 1 +var OneMonth = 60 * 60 * 24 * 30 diff --git a/dao/UserDao.go b/dao/UserDao.go new file mode 100644 index 0000000..85f5bf2 --- /dev/null +++ b/dao/UserDao.go @@ -0,0 +1,8 @@ +package dao + +// TableUser 对应数据库User表结构的结构体 +type TableUser struct { + Id int64 + Name string + Password string +} diff --git a/go.mod b/go.mod index 62c7cc2..313bbac 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module TikTok go 1.18 require ( + github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gin-gonic/gin v1.7.7 github.com/jinzhu/gorm v1.9.16 github.com/swaggo/swag v1.8.1 @@ -35,4 +36,4 @@ require ( golang.org/x/tools v0.1.10 // indirect google.golang.org/protobuf v1.28.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect -) \ No newline at end of file +) diff --git a/go.sum b/go.sum index d2d2f11..45d36ac 100644 --- a/go.sum +++ b/go.sum @@ -9,6 +9,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM= github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= diff --git a/middleware/Auth.go b/middleware/Auth.go new file mode 100644 index 0000000..9b84e61 --- /dev/null +++ b/middleware/Auth.go @@ -0,0 +1,50 @@ +package middleware + +import ( + "TikTok/config" + "github.com/dgrijalva/jwt-go" + "github.com/gin-gonic/gin" + "net/http" + "strings" +) + +type Response struct { + StatusCode int32 `json:"status_code"` + StatusMsg string `json:"status_msg,omitempty"` +} + +func Auth() gin.HandlerFunc { + return func(context *gin.Context) { + auth := context.Request.Header.Get("Authorization") + if len(auth) == 0 { + context.Abort() + context.JSON(http.StatusUnauthorized, Response{ + StatusCode: 0, + StatusMsg: "Unauthorized", + }) + } + auth = strings.Fields(auth)[1] + _, err := parseToken(auth) + if err != nil { + context.Abort() + context.JSON(http.StatusUnauthorized, Response{ + StatusMsg: "token 无效", + }) + } else { + println("token 正确") + } + context.Next() + } +} + +func parseToken(token string) (*jwt.StandardClaims, error) { + jwtToken, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(token *jwt.Token) (i interface{}, e error) { + return []byte(config.Secret), nil + }) + if err == nil && jwtToken != nil { + if claim, ok := jwtToken.Claims.(*jwt.StandardClaims); ok && jwtToken.Valid { + return claim, nil + } + } + return nil, err +} diff --git a/service/userService.go b/service/userService.go index ad003e1..a42e4e7 100644 --- a/service/userService.go +++ b/service/userService.go @@ -5,13 +5,13 @@ type UserService interface { 个人使用 */ // GetTableUserList GetUserList 获得全部TableUser对象 - GetTableUserList(users *[]TableUser) bool + GetTableUserList() ([]TableUser, bool) // GetTableUserByUsername GetUserByUsername 根据username获得TableUser对象 - GetTableUserByUsername(name string) bool + GetTableUserByUsername(name string) (TableUser, bool) // GetTableUserById GetUserById 根据user_id获得TableUser对象 - GetTableUserById(id int64) bool + GetTableUserById(id int64) (TableUser, bool) /* 他人使用 @@ -27,12 +27,6 @@ type UserService interface { //(调用方法:直接在context内拿参数"user_id"的值) } -type TableUser struct { - Id int64 - Name string - Password string -} - /*type User struct { Id int64 `json:"id,omitempty"` Name string `json:"name,omitempty"` @@ -41,3 +35,9 @@ type TableUser struct { IsFollow bool `json:"is_follow,omitempty"` } */ + +type TableUser struct { + Id int64 + Name string + Password string +} diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index 6d43c33..461e18b 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -1 +1,66 @@ package service + +import ( + "TikTok/config" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" + "github.com/dgrijalva/jwt-go" + "strconv" + "time" +) + +type UserServiceImpl struct { +} + +func (usi *UserServiceImpl) GetTableUserList() ([]TableUser, bool) { + return nil, false +} + +func (usi *UserServiceImpl) GetTableUserByUsername(name string) (TableUser, bool) { + return TableUser{}, false +} + +func (usi *UserServiceImpl) GetTableUserById(id int64) (TableUser, bool) { + return TableUser{}, false +} + +func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { + return User{}, nil +} + +func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, error) { + return User{}, nil +} + +func NewToken(u *TableUser) string { + expiresTime := time.Now().Unix() + int64(config.OneDayOfHours) + fmt.Printf("%v\n", expiresTime) + claims := jwt.StandardClaims{ + Audience: u.Name, + ExpiresAt: expiresTime, + Id: strconv.FormatInt(1, 10), + IssuedAt: time.Now().Unix(), + Issuer: "tiktok", + NotBefore: time.Now().Unix(), + Subject: "token", + } + var jwtSecret = []byte(config.Secret) + tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + if token, err := tokenClaims.SignedString(jwtSecret); err == nil { + token = "Bearer " + token + println("generate token success!\n") + return token + } else { + println("generate token fail\n") + return "fail" + } +} + +func EnCoder(password string) string { + h := hmac.New(sha256.New, []byte(password)) + sha := hex.EncodeToString(h.Sum(nil)) + fmt.Println("Result: " + sha) + return sha +} From 830fd6ae76228af9ab1aaf1e0b888df9e6ba8c7d Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Tue, 17 May 2022 13:15:37 +0800 Subject: [PATCH 16/70] init service interface -- lls --- service/followService.go | 9 --------- 1 file changed, 9 deletions(-) diff --git a/service/followService.go b/service/followService.go index 43cd0f9..07cff76 100644 --- a/service/followService.go +++ b/service/followService.go @@ -27,12 +27,3 @@ type FollowService interface { // GetFollowers 获取当前用户的粉丝列表 GetFollowers(userId int64) ([]User, error) } - -// User 用户结构信息 -type User struct { - Id int64 `json:"id"` - Name string `json:"name"` - FollowCount int64 `json:"follow_count"` - FollowerCount int64 `json:"follower_count"` - isFollow bool `json:"is_follow"` -} From 71bf7a9e4297575e2234d1104305f3823269dfd4 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Tue, 17 May 2022 14:49:09 +0800 Subject: [PATCH 17/70] =?UTF-8?q?dev-20220517-user=20userServiceImpl?= =?UTF-8?q?=E7=BB=93=E6=9E=84=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/followService.go | 9 --------- 1 file changed, 9 deletions(-) diff --git a/service/followService.go b/service/followService.go index 43cd0f9..07cff76 100644 --- a/service/followService.go +++ b/service/followService.go @@ -27,12 +27,3 @@ type FollowService interface { // GetFollowers 获取当前用户的粉丝列表 GetFollowers(userId int64) ([]User, error) } - -// User 用户结构信息 -type User struct { - Id int64 `json:"id"` - Name string `json:"name"` - FollowCount int64 `json:"follow_count"` - FollowerCount int64 `json:"follower_count"` - isFollow bool `json:"is_follow"` -} From 28cdb2611daca2316c5632b9b58475133bbb35b6 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Tue, 17 May 2022 14:52:08 +0800 Subject: [PATCH 18/70] =?UTF-8?q?dev-20220517-user=20userServiceImpl?= =?UTF-8?q?=E7=BB=93=E6=9E=84=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/userController.go | 94 ++++++++++++++++++++++++++++++++++++ router.go | 10 ++++ service/userService.go | 9 ++-- service/userServiceImpl.go | 88 ++++++++++++++++++++++++++++++--- 4 files changed, 188 insertions(+), 13 deletions(-) create mode 100644 controller/userController.go diff --git a/controller/userController.go b/controller/userController.go new file mode 100644 index 0000000..df5a43c --- /dev/null +++ b/controller/userController.go @@ -0,0 +1,94 @@ +package controller + +import ( + "TikTok/service" + "github.com/gin-gonic/gin" +) + +type Response struct { + StatusCode int32 `json:"status_code"` + StatusMsg string `json:"status_msg,omitempty"` +} + +type UserLoginResponse struct { + Response + UserId int64 `json:"user_id,omitempty"` + Token string `json:"token"` +} + +type UserResponse struct { + Response + User service.User `json:"user"` +} + +func Register(c *gin.Context) { + /*username := c.Query("username") + password := c.Query("password") + + u := new(service.User) + + if u.GetUserByUsername(username) { + c.JSON(http.StatusOK, UserLoginResponse{ + Response: pojo.Response{StatusCode: 1, StatusMsg: "User already exist"}, + }) + } else { + newUser := &service.User{ + Name: username, + Password: service.EnCoder(password), + } + if newUser.InsertUser() != true { + println("insert data fail") + } + token := service.GenerateToken(username) + c.JSON(http.StatusOK, UserLoginResponse{ + Response: pojo.Response{StatusCode: 0}, + UserId: u.Id, + Token: token, + }) + }*/ +} + +func Login(c *gin.Context) { + /*username := c.Query("username") + password := c.Query("password") + encoderPassword := service.EnCoder(password) + println(encoderPassword) + u := new(service.User) + u.GetUserByUsername(username) + + if encoderPassword == u.Password { + token := service.GenerateToken(username) + c.JSON(http.StatusOK, UserLoginResponse{ + Response: pojo.Response{StatusCode: 0}, + UserId: u.Id, + Token: token, + }) + } else { + c.JSON(http.StatusOK, UserLoginResponse{ + Response: pojo.Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, + }) + }*/ +} + +func UserInfo(c *gin.Context) { + /*user_id := c.Query("user_id") + id, _ := strconv.ParseInt(user_id, 10, 64) + u := new(service.User) + if u.GetUserById(id) { + user := pojo.User{ + Id: u.Id, + Name: u.Name, + FollowCount: 1, + FollowerCount: 1, + IsFollow: true, + } + c.JSON(http.StatusOK, UserResponse{ + Response: pojo.Response{StatusCode: 0}, + User: user, + }) + } else { + c.JSON(http.StatusOK, UserResponse{ + Response: pojo.Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, + }) + }*/ +} diff --git a/router.go b/router.go index 67ea7c1..400e674 100644 --- a/router.go +++ b/router.go @@ -1,5 +1,15 @@ package main +import ( + "TikTok/controller" + "TikTok/middleware" + "github.com/gin-gonic/gin" +) + func initRouter(r *gin.Engine) { + apiRouter := r.Group("/douyin") + apiRouter.GET("/user/", middleware.Auth(), controller.UserInfo) + apiRouter.POST("/user/register/", controller.Register) + apiRouter.POST("/user/login/", controller.Login) } diff --git a/service/userService.go b/service/userService.go index a42e4e7..7b4e1ff 100644 --- a/service/userService.go +++ b/service/userService.go @@ -5,13 +5,13 @@ type UserService interface { 个人使用 */ // GetTableUserList GetUserList 获得全部TableUser对象 - GetTableUserList() ([]TableUser, bool) + GetTableUserList() []TableUser // GetTableUserByUsername GetUserByUsername 根据username获得TableUser对象 - GetTableUserByUsername(name string) (TableUser, bool) + GetTableUserByUsername(name string) TableUser // GetTableUserById GetUserById 根据user_id获得TableUser对象 - GetTableUserById(id int64) (TableUser, bool) + GetTableUserById(id int64) TableUser /* 他人使用 @@ -27,14 +27,13 @@ type UserService interface { //(调用方法:直接在context内拿参数"user_id"的值) } -/*type User struct { +type User struct { Id int64 `json:"id,omitempty"` Name string `json:"name,omitempty"` FollowCount int64 `json:"follow_count,omitempty"` FollowerCount int64 `json:"follower_count,omitempty"` IsFollow bool `json:"is_follow,omitempty"` } -*/ type TableUser struct { Id int64 diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index 461e18b..1affb64 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -2,36 +2,108 @@ package service import ( "TikTok/config" + "TikTok/dao" "crypto/hmac" "crypto/sha256" "encoding/hex" + "errors" "fmt" "github.com/dgrijalva/jwt-go" + "log" "strconv" "time" ) type UserServiceImpl struct { + FollowService } -func (usi *UserServiceImpl) GetTableUserList() ([]TableUser, bool) { - return nil, false +func (tableUser TableUser) TableName() string { + return "users" } -func (usi *UserServiceImpl) GetTableUserByUsername(name string) (TableUser, bool) { - return TableUser{}, false +func (usi *UserServiceImpl) GetTableUserList() []TableUser { + tableUsers := []TableUser{} + if err := dao.Db.Find(&tableUsers).Error; err != nil { + log.Panicln("err:", err.Error()) + return tableUsers + } + return tableUsers } -func (usi *UserServiceImpl) GetTableUserById(id int64) (TableUser, bool) { - return TableUser{}, false +func (usi *UserServiceImpl) GetTableUserByUsername(name string) TableUser { + tableUser := TableUser{} + if err := dao.Db.Where("name = ?", name).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + } + if tableUser.Name == name { + log.Println("查询成功") + return tableUser + } else { + log.Println("未找到该用户") + return tableUser + } +} + +func (usi *UserServiceImpl) GetTableUserById(id int64) TableUser { + tableUser := TableUser{} + if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + } + if tableUser.Id == id { + log.Println("查询成功") + return tableUser + } else { + log.Println("未找到该用户") + return tableUser + } } func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { - return User{}, nil + tableUser := TableUser{} + if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + } + if tableUser.Id == id { + log.Println("查询成功") + } else { + log.Println("未找到该用户") + } + impl := UserServiceImpl{} + followCount, _ := impl.FollowService.GetFollowingCnt(id) + followerCount, _ := impl.FollowService.GetFollowerCnt(id) + user := User{ + Id: id, + Name: tableUser.Name, + FollowCount: followCount, + FollowerCount: followerCount, + IsFollow: false, + } + return user, errors.New("query fail") } func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, error) { - return User{}, nil + tableUser := TableUser{} + if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + } + if tableUser.Id == id { + log.Println("查询成功") + } else { + log.Println("未找到该用户") + } + impl := UserServiceImpl{} + followCount, _ := impl.FollowService.GetFollowingCnt(id) + followerCount, _ := impl.FollowService.GetFollowerCnt(id) + isfollow, _ := impl.FollowService.IsFollowing(curId, id) + user := User{ + Id: id, + Name: tableUser.Name, + FollowCount: followCount, + FollowerCount: followerCount, + IsFollow: isfollow, + } + return user, errors.New("query fail") } func NewToken(u *TableUser) string { From 674c828d6691b1b624d89f15a015423534b2a8b9 Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Tue, 17 May 2022 16:58:25 +0800 Subject: [PATCH 19/70] =?UTF-8?q?dev-20220517-like=20=E6=89=80=E6=9C=89?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=9D=87=E6=B5=8B=E8=AF=95=E5=B9=B6=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/likeconfig.go | 5 +++ controller/likeController.go | 61 +++++++++++++++++++++++++++ dao/Initdao.go | 2 +- main.go | 3 +- router.go | 23 +++++++++++ service/likeServiceImpl.go | 80 ++++++++++++++++++++++++++++++------ service/likeSub.go | 21 ++++++++++ 7 files changed, 180 insertions(+), 15 deletions(-) create mode 100644 config/likeconfig.go create mode 100644 controller/likeController.go diff --git a/config/likeconfig.go b/config/likeconfig.go new file mode 100644 index 0000000..72c04d4 --- /dev/null +++ b/config/likeconfig.go @@ -0,0 +1,5 @@ +package config + +const Islike = 0 //点赞的状态 +const Unlike = 1 //取消赞的状态 +const Likeaction = 1 //点赞的行为 diff --git a/controller/likeController.go b/controller/likeController.go new file mode 100644 index 0000000..d7bb70b --- /dev/null +++ b/controller/likeController.go @@ -0,0 +1,61 @@ +package controller + +import ( + "TikTok/service" + "github.com/gin-gonic/gin" + "net/http" + "strconv" +) + +type likeResponse struct { + StatusCode int32 `json:"status_code"` + StatusMsg string `json:"status_msg,omitempty"` +} + +type GetFavouriteListResponse struct { + StatusCode int32 `json:"status_code"` + StatusMsg string `json:"status_msg,omitempty"` + Videolist []service.Video `json:"video_list,omitempty"` +} + +//点赞或者取消赞操作; +func Favorite_Action(c *gin.Context) { + user_id := c.Query("user_id") + userid, _ := strconv.ParseInt(user_id, 10, 64) + video_id := c.Query("video_id") + videoid, _ := strconv.ParseInt(video_id, 10, 64) + action_type := c.Query("action_type") + actiontype, _ := strconv.ParseInt(action_type, 10, 64) + like := new(service.LikeServiceImpl) + if like.FavouriteAction(userid, videoid, int32(actiontype)) == nil { + c.JSON(http.StatusOK, likeResponse{ + StatusCode: 0, + StatusMsg: "favourite action success", + }) + } else { + c.JSON(http.StatusOK, likeResponse{ + StatusCode: 1, + StatusMsg: "favourite action fail", + }) + } +} + +//获取点赞列表; +func GetFavouriteList(c *gin.Context) { + user_id := c.Query("user_id") + userid, _ := strconv.ParseInt(user_id, 10, 64) + like := new(service.LikeServiceImpl) + videos, err := like.GetFavouriteList(userid) + if err == nil { + c.JSON(http.StatusOK, GetFavouriteListResponse{ + StatusCode: 0, + StatusMsg: "get favouritelist success", + Videolist: videos, + }) + } else { + c.JSON(http.StatusOK, GetFavouriteListResponse{ + StatusCode: 1, + StatusMsg: "can't find favouritelist ", + }) + } +} diff --git a/dao/Initdao.go b/dao/Initdao.go index d4de926..864b34c 100644 --- a/dao/Initdao.go +++ b/dao/Initdao.go @@ -10,7 +10,7 @@ var Db *gorm.DB func init() { var err error - Db, err = gorm.Open("mysql", "douyin:zjqxy@tcp(43.138.25.60:3306)/douyin/") + Db, err = gorm.Open("mysql", "douyin:zjqxy@tcp(43.138.25.60:3306)/douyin") if err != nil { log.Panicln("err:", err.Error()) } diff --git a/main.go b/main.go index 84c5a5f..842ec0b 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,7 @@ package main import ( -"github.com/gin-gonic/gin" + "github.com/gin-gonic/gin" ) func main() { @@ -10,4 +10,5 @@ func main() { initRouter(r) r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") + } diff --git a/router.go b/router.go index 67ea7c1..835a336 100644 --- a/router.go +++ b/router.go @@ -1,5 +1,28 @@ package main +import ( + "TikTok/controller" + "github.com/gin-gonic/gin" +) + func initRouter(r *gin.Engine) { + apiRouter := r.Group("/douyin") + // basic apis + //apiRouter.GET("/feed/", controller.Feed) + //apiRouter.GET("/user/", middleware.Auth(), controller.UserInfo) + //apiRouter.POST("/user/register/", controller.Register) + //apiRouter.POST("/user/login/", controller.Login) + //apiRouter.POST("/publish/action/", controller.Publish) + //apiRouter.GET("/publish/list/", controller.PublishList) + + // extra apis - I + apiRouter.POST("/favorite/action/", controller.Favorite_Action) + apiRouter.GET("/favorite/list/", controller.GetFavouriteList) + //apiRouter.POST("/comment/action/", controller.CommentAction) + //apiRouter.GET("/comment/list/", controller.CommentList) + // extra apis - II + //apiRouter.POST("/relation/action/", controller.RelationAction) + //apiRouter.GET("/relation/follow/list/", controller.FollowList) + //apiRouter.GET("/relation/follower/list/", controller.FollowerList) } diff --git a/service/likeServiceImpl.go b/service/likeServiceImpl.go index 29e2068..14d9cb3 100644 --- a/service/likeServiceImpl.go +++ b/service/likeServiceImpl.go @@ -1,8 +1,10 @@ package service import ( + "TikTok/config" "TikTok/dao" "errors" + "log" ) type LikeServiceImpl struct { @@ -11,10 +13,11 @@ type LikeServiceImpl struct { func (like *LikeServiceImpl) IsFavourit(videoId int64, userId int64) (bool, error) { likedata := new(dao.Like) - if err := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId).First(&likedata); err != nil { + //未查询到数据,返回未点赞; + if result := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId).First(&likedata); result.RowsAffected == 0 { return false, errors.New("can't find this data") - } - if likedata.Cancel == 0 { + } //查询到数据,根据Cancel值判断是否点赞; + if likedata.Cancel == config.Islike { return true, nil } else { return false, nil @@ -23,16 +26,67 @@ func (like *LikeServiceImpl) IsFavourit(videoId int64, userId int64) (bool, erro func (like *LikeServiceImpl) FavouriteCount(videoId int64) (int64, error) { var count int64 - if err := dao.Db.Table("likes").Where("video_id = ?", videoId).Count(&count); err != nil { - return 0, errors.New("can't find this data") + err := dao.Db.Table("likes").Where("video_id = ? AND cancel = ?", videoId, config.Islike). + Count(&count).Error + //当查询出现异常时 + if err != nil { + return 0, errors.New("An unknown exception occurred in the query") + } else { + return count, nil + } +} + +func (like *LikeServiceImpl) FavouriteAction(userId int64, videoId int64, action_type int32) error { + likedata := new(dao.Like) + //先查询是否有这条数据。 + result := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId).First(&likedata) + //点赞行为,否则取消赞 + if action_type == config.Likeaction { + //没查到这条数据,则新建这条数据,否则更新即可; + if result.RowsAffected == 0 { + likedata.User_id = userId + likedata.Video_id = videoId + likedata.Cancel = config.Islike + if result1 := dao.Db.Table("likes").Create(&likedata); result1.RowsAffected == 0 { + return errors.New("insert data fail") + } + } else { + if result2 := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId). + Update("cancel", config.Islike); result2.RowsAffected == 0 { + return errors.New("update data fail") + } + } + } else { + //只有当前是点赞状态才能取消点赞这个行为,如果查询不到数据则返回错误; + if result.RowsAffected == 0 { + return errors.New("can't find this data") + } else { + if result3 := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId). + Update("cancel", config.Unlike); result3.RowsAffected == 0 { + return errors.New("update data fail") + } + } } - return count, nil + return nil } -//func (like *LikeServiceImpl) FavouriteAction(userId int64, videoId int64, action_type int32) error { -// panic("implement me") -//} -// -//func (like *LikeServiceImpl) GetFavouriteList(userId int64) ([]Video, error) { -// panic("implement me") -//} +func (like *LikeServiceImpl) GetFavouriteList(userId int64) ([]Video, error) { + var favorite_videolist []Video + var video_ids []int64 + if result := dao.Db.Table("likes").Select("video_id").Where("user_id = ? AND cancel = ?", userId, config.Islike). + Find(&video_ids); result.RowsAffected == 0 { //如果查询不到数据,说明这个用户没有点赞视频,返回空; + return favorite_videolist, errors.New("can't find favourite video") + } + //如果查询到数据,遍历video_id,将每个video对象添加到集合中去; + //likesub := new(LikeSub) + for video_id := range video_ids { + //video, err1 := likesub.GetVideo(int64(video_id)) + video, err1 := like.GetVideo(int64(video_id)) + if err1 != nil { //如果没有获取这个video_id的视频,视频可能被删除了,跳过 + log.Panicln(errors.New("can't find this favourite video")) + continue + } + favorite_videolist = append(favorite_videolist, video) + } + return favorite_videolist, nil +} diff --git a/service/likeSub.go b/service/likeSub.go index 6d43c33..d6a2c33 100644 --- a/service/likeSub.go +++ b/service/likeSub.go @@ -1 +1,22 @@ package service + +type LikeSub struct { +} + +func (like *LikeSub) GetVideo(videoId int64) (Video, error) { + return Video{ + Id: 1, + Author: User{ + Id: 1, + Name: "lzz", + FollowCount: 12, + FollowerCount: 13, + IsFollow: true, + }, + PlayUrl: "www.baidu.com", + CoverUrl: "www.baidu.com", + FavoriteCount: 2, + CommentCount: 3, + IsFavorite: true, + }, nil +} From c8418adec14bd6a15029acb5b1aa220902170448 Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Tue, 17 May 2022 18:57:52 +0800 Subject: [PATCH 20/70] =?UTF-8?q?dev-20220517-like=20=E6=89=80=E6=9C=89?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=9D=87=E6=B5=8B=E8=AF=95=E5=B9=B6=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.go | 7 ++ controller/userController.go | 94 ++++++++++++++++++++++++ dao/UserDao.go | 8 ++ go.mod | 2 +- middleware/Auth.go | 50 +++++++++++++ service/followService.go | 9 --- service/userService.go | 41 +++++++++++ service/userServiceImpl.go | 137 +++++++++++++++++++++++++++++++++++ 8 files changed, 338 insertions(+), 10 deletions(-) create mode 100644 config/config.go create mode 100644 controller/userController.go create mode 100644 dao/UserDao.go create mode 100644 middleware/Auth.go diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..216d3db --- /dev/null +++ b/config/config.go @@ -0,0 +1,7 @@ +package config + +var Secret = "tiktok" + +var OneDayOfHours = 60 * 60 * 24 +var OneMinute = 60 * 1 +var OneMonth = 60 * 60 * 24 * 30 diff --git a/controller/userController.go b/controller/userController.go new file mode 100644 index 0000000..df5a43c --- /dev/null +++ b/controller/userController.go @@ -0,0 +1,94 @@ +package controller + +import ( + "TikTok/service" + "github.com/gin-gonic/gin" +) + +type Response struct { + StatusCode int32 `json:"status_code"` + StatusMsg string `json:"status_msg,omitempty"` +} + +type UserLoginResponse struct { + Response + UserId int64 `json:"user_id,omitempty"` + Token string `json:"token"` +} + +type UserResponse struct { + Response + User service.User `json:"user"` +} + +func Register(c *gin.Context) { + /*username := c.Query("username") + password := c.Query("password") + + u := new(service.User) + + if u.GetUserByUsername(username) { + c.JSON(http.StatusOK, UserLoginResponse{ + Response: pojo.Response{StatusCode: 1, StatusMsg: "User already exist"}, + }) + } else { + newUser := &service.User{ + Name: username, + Password: service.EnCoder(password), + } + if newUser.InsertUser() != true { + println("insert data fail") + } + token := service.GenerateToken(username) + c.JSON(http.StatusOK, UserLoginResponse{ + Response: pojo.Response{StatusCode: 0}, + UserId: u.Id, + Token: token, + }) + }*/ +} + +func Login(c *gin.Context) { + /*username := c.Query("username") + password := c.Query("password") + encoderPassword := service.EnCoder(password) + println(encoderPassword) + u := new(service.User) + u.GetUserByUsername(username) + + if encoderPassword == u.Password { + token := service.GenerateToken(username) + c.JSON(http.StatusOK, UserLoginResponse{ + Response: pojo.Response{StatusCode: 0}, + UserId: u.Id, + Token: token, + }) + } else { + c.JSON(http.StatusOK, UserLoginResponse{ + Response: pojo.Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, + }) + }*/ +} + +func UserInfo(c *gin.Context) { + /*user_id := c.Query("user_id") + id, _ := strconv.ParseInt(user_id, 10, 64) + u := new(service.User) + if u.GetUserById(id) { + user := pojo.User{ + Id: u.Id, + Name: u.Name, + FollowCount: 1, + FollowerCount: 1, + IsFollow: true, + } + c.JSON(http.StatusOK, UserResponse{ + Response: pojo.Response{StatusCode: 0}, + User: user, + }) + } else { + c.JSON(http.StatusOK, UserResponse{ + Response: pojo.Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, + }) + }*/ +} diff --git a/dao/UserDao.go b/dao/UserDao.go new file mode 100644 index 0000000..85f5bf2 --- /dev/null +++ b/dao/UserDao.go @@ -0,0 +1,8 @@ +package dao + +// TableUser 对应数据库User表结构的结构体 +type TableUser struct { + Id int64 + Name string + Password string +} diff --git a/go.mod b/go.mod index 7605bbd..313bbac 100644 --- a/go.mod +++ b/go.mod @@ -36,4 +36,4 @@ require ( golang.org/x/tools v0.1.10 // indirect google.golang.org/protobuf v1.28.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect -) \ No newline at end of file +) diff --git a/middleware/Auth.go b/middleware/Auth.go new file mode 100644 index 0000000..9b84e61 --- /dev/null +++ b/middleware/Auth.go @@ -0,0 +1,50 @@ +package middleware + +import ( + "TikTok/config" + "github.com/dgrijalva/jwt-go" + "github.com/gin-gonic/gin" + "net/http" + "strings" +) + +type Response struct { + StatusCode int32 `json:"status_code"` + StatusMsg string `json:"status_msg,omitempty"` +} + +func Auth() gin.HandlerFunc { + return func(context *gin.Context) { + auth := context.Request.Header.Get("Authorization") + if len(auth) == 0 { + context.Abort() + context.JSON(http.StatusUnauthorized, Response{ + StatusCode: 0, + StatusMsg: "Unauthorized", + }) + } + auth = strings.Fields(auth)[1] + _, err := parseToken(auth) + if err != nil { + context.Abort() + context.JSON(http.StatusUnauthorized, Response{ + StatusMsg: "token 无效", + }) + } else { + println("token 正确") + } + context.Next() + } +} + +func parseToken(token string) (*jwt.StandardClaims, error) { + jwtToken, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(token *jwt.Token) (i interface{}, e error) { + return []byte(config.Secret), nil + }) + if err == nil && jwtToken != nil { + if claim, ok := jwtToken.Claims.(*jwt.StandardClaims); ok && jwtToken.Valid { + return claim, nil + } + } + return nil, err +} diff --git a/service/followService.go b/service/followService.go index 43cd0f9..07cff76 100644 --- a/service/followService.go +++ b/service/followService.go @@ -27,12 +27,3 @@ type FollowService interface { // GetFollowers 获取当前用户的粉丝列表 GetFollowers(userId int64) ([]User, error) } - -// User 用户结构信息 -type User struct { - Id int64 `json:"id"` - Name string `json:"name"` - FollowCount int64 `json:"follow_count"` - FollowerCount int64 `json:"follower_count"` - isFollow bool `json:"is_follow"` -} diff --git a/service/userService.go b/service/userService.go index 6d43c33..7b4e1ff 100644 --- a/service/userService.go +++ b/service/userService.go @@ -1 +1,42 @@ package service + +type UserService interface { + /* + 个人使用 + */ + // GetTableUserList GetUserList 获得全部TableUser对象 + GetTableUserList() []TableUser + + // GetTableUserByUsername GetUserByUsername 根据username获得TableUser对象 + GetTableUserByUsername(name string) TableUser + + // GetTableUserById GetUserById 根据user_id获得TableUser对象 + GetTableUserById(id int64) TableUser + + /* + 他人使用 + */ + // GetUserById 未登录情况下,根据user_id获得User对象 + GetUserById(id int64) (User, error) + + // GetUserByIdWithCurId 已登录(curID)情况下,根据user_id获得User对象 + GetUserByIdWithCurId(id int64, curId int64) (User, error) + + // 根据token返回id + // 接口:auth中间件,解析完token,将userid放入context + //(调用方法:直接在context内拿参数"user_id"的值) +} + +type User struct { + Id int64 `json:"id,omitempty"` + Name string `json:"name,omitempty"` + FollowCount int64 `json:"follow_count,omitempty"` + FollowerCount int64 `json:"follower_count,omitempty"` + IsFollow bool `json:"is_follow,omitempty"` +} + +type TableUser struct { + Id int64 + Name string + Password string +} diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index 6d43c33..1affb64 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -1 +1,138 @@ package service + +import ( + "TikTok/config" + "TikTok/dao" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "github.com/dgrijalva/jwt-go" + "log" + "strconv" + "time" +) + +type UserServiceImpl struct { + FollowService +} + +func (tableUser TableUser) TableName() string { + return "users" +} + +func (usi *UserServiceImpl) GetTableUserList() []TableUser { + tableUsers := []TableUser{} + if err := dao.Db.Find(&tableUsers).Error; err != nil { + log.Panicln("err:", err.Error()) + return tableUsers + } + return tableUsers +} + +func (usi *UserServiceImpl) GetTableUserByUsername(name string) TableUser { + tableUser := TableUser{} + if err := dao.Db.Where("name = ?", name).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + } + if tableUser.Name == name { + log.Println("查询成功") + return tableUser + } else { + log.Println("未找到该用户") + return tableUser + } +} + +func (usi *UserServiceImpl) GetTableUserById(id int64) TableUser { + tableUser := TableUser{} + if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + } + if tableUser.Id == id { + log.Println("查询成功") + return tableUser + } else { + log.Println("未找到该用户") + return tableUser + } +} + +func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { + tableUser := TableUser{} + if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + } + if tableUser.Id == id { + log.Println("查询成功") + } else { + log.Println("未找到该用户") + } + impl := UserServiceImpl{} + followCount, _ := impl.FollowService.GetFollowingCnt(id) + followerCount, _ := impl.FollowService.GetFollowerCnt(id) + user := User{ + Id: id, + Name: tableUser.Name, + FollowCount: followCount, + FollowerCount: followerCount, + IsFollow: false, + } + return user, errors.New("query fail") +} + +func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, error) { + tableUser := TableUser{} + if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + } + if tableUser.Id == id { + log.Println("查询成功") + } else { + log.Println("未找到该用户") + } + impl := UserServiceImpl{} + followCount, _ := impl.FollowService.GetFollowingCnt(id) + followerCount, _ := impl.FollowService.GetFollowerCnt(id) + isfollow, _ := impl.FollowService.IsFollowing(curId, id) + user := User{ + Id: id, + Name: tableUser.Name, + FollowCount: followCount, + FollowerCount: followerCount, + IsFollow: isfollow, + } + return user, errors.New("query fail") +} + +func NewToken(u *TableUser) string { + expiresTime := time.Now().Unix() + int64(config.OneDayOfHours) + fmt.Printf("%v\n", expiresTime) + claims := jwt.StandardClaims{ + Audience: u.Name, + ExpiresAt: expiresTime, + Id: strconv.FormatInt(1, 10), + IssuedAt: time.Now().Unix(), + Issuer: "tiktok", + NotBefore: time.Now().Unix(), + Subject: "token", + } + var jwtSecret = []byte(config.Secret) + tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + if token, err := tokenClaims.SignedString(jwtSecret); err == nil { + token = "Bearer " + token + println("generate token success!\n") + return token + } else { + println("generate token fail\n") + return "fail" + } +} + +func EnCoder(password string) string { + h := hmac.New(sha256.New, []byte(password)) + sha := hex.EncodeToString(h.Sum(nil)) + fmt.Println("Result: " + sha) + return sha +} From 300b82b8f6f7945b02b13bc18615ee3366417bee Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Tue, 17 May 2022 19:12:13 +0800 Subject: [PATCH 21/70] =?UTF-8?q?dev-20220517-like=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- router.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/router.go b/router.go index 400e674..daa1a71 100644 --- a/router.go +++ b/router.go @@ -8,8 +8,25 @@ import ( func initRouter(r *gin.Engine) { apiRouter := r.Group("/douyin") + // basic apis + //apiRouter.GET("/feed/", controller.Feed) + //apiRouter.GET("/user/", middleware.Auth(), controller.UserInfo) + //apiRouter.POST("/user/register/", controller.Register) + //apiRouter.POST("/user/login/", controller.Login) + //apiRouter.POST("/publish/action/", controller.Publish) + //apiRouter.GET("/publish/list/", controller.PublishList) apiRouter.GET("/user/", middleware.Auth(), controller.UserInfo) apiRouter.POST("/user/register/", controller.Register) apiRouter.POST("/user/login/", controller.Login) + // extra apis - I + apiRouter.POST("/favorite/action/", middleware.Auth(), controller.Favorite_Action) + apiRouter.GET("/favorite/list/", middleware.Auth(), controller.GetFavouriteList) + //apiRouter.POST("/comment/action/", controller.CommentAction) + //apiRouter.GET("/comment/list/", controller.CommentList) + + // extra apis - II + //apiRouter.POST("/relation/action/", controller.RelationAction) + //apiRouter.GET("/relation/follow/list/", controller.FollowList) + //apiRouter.GET("/relation/follower/list/", controller.FollowerList) } From 8f89fbf33a534dae0825a9d8df78f1dd06e31fe1 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Tue, 17 May 2022 19:36:49 +0800 Subject: [PATCH 22/70] =?UTF-8?q?dev-20220517-user=20userServiceImpl?= =?UTF-8?q?=E7=BB=93=E6=9E=84=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/userController.go | 54 +++++++++++++++++------------------- middleware/Auth.go | 3 +- service/userService.go | 4 ++- service/userServiceImpl.go | 26 +++++++++++++++-- 4 files changed, 54 insertions(+), 33 deletions(-) diff --git a/controller/userController.go b/controller/userController.go index df5a43c..1179afd 100644 --- a/controller/userController.go +++ b/controller/userController.go @@ -3,6 +3,8 @@ package controller import ( "TikTok/service" "github.com/gin-gonic/gin" + "net/http" + "strconv" ) type Response struct { @@ -22,73 +24,69 @@ type UserResponse struct { } func Register(c *gin.Context) { - /*username := c.Query("username") + username := c.Query("username") password := c.Query("password") - u := new(service.User) + usi := service.UserServiceImpl{} - if u.GetUserByUsername(username) { + u := usi.GetTableUserByUsername(username) + if username == u.Name { c.JSON(http.StatusOK, UserLoginResponse{ - Response: pojo.Response{StatusCode: 1, StatusMsg: "User already exist"}, + Response: Response{StatusCode: 1, StatusMsg: "User already exist"}, }) } else { - newUser := &service.User{ + newUser := service.TableUser{ Name: username, Password: service.EnCoder(password), } - if newUser.InsertUser() != true { + if usi.InsertTableUser(&newUser) != true { println("insert data fail") } token := service.GenerateToken(username) c.JSON(http.StatusOK, UserLoginResponse{ - Response: pojo.Response{StatusCode: 0}, + Response: Response{StatusCode: 0}, UserId: u.Id, Token: token, }) - }*/ + } } func Login(c *gin.Context) { - /*username := c.Query("username") + username := c.Query("username") password := c.Query("password") encoderPassword := service.EnCoder(password) println(encoderPassword) - u := new(service.User) - u.GetUserByUsername(username) + + usi := service.UserServiceImpl{} + + u := usi.GetTableUserByUsername(username) if encoderPassword == u.Password { token := service.GenerateToken(username) c.JSON(http.StatusOK, UserLoginResponse{ - Response: pojo.Response{StatusCode: 0}, + Response: Response{StatusCode: 0}, UserId: u.Id, Token: token, }) } else { c.JSON(http.StatusOK, UserLoginResponse{ - Response: pojo.Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, + Response: Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, }) - }*/ + } } func UserInfo(c *gin.Context) { - /*user_id := c.Query("user_id") + user_id := c.Query("user_id") id, _ := strconv.ParseInt(user_id, 10, 64) - u := new(service.User) - if u.GetUserById(id) { - user := pojo.User{ - Id: u.Id, - Name: u.Name, - FollowCount: 1, - FollowerCount: 1, - IsFollow: true, - } + + if u, err := service.UserService.GetUserById(new(service.UserServiceImpl), id); err != nil { c.JSON(http.StatusOK, UserResponse{ - Response: pojo.Response{StatusCode: 0}, - User: user, + Response: Response{StatusCode: 0}, + User: u, }) } else { c.JSON(http.StatusOK, UserResponse{ - Response: pojo.Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, + Response: Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, }) - }*/ + } } diff --git a/middleware/Auth.go b/middleware/Auth.go index 9b84e61..086f20a 100644 --- a/middleware/Auth.go +++ b/middleware/Auth.go @@ -24,7 +24,8 @@ func Auth() gin.HandlerFunc { }) } auth = strings.Fields(auth)[1] - _, err := parseToken(auth) + token, err := parseToken(auth) + context.Set("userId", token.Id) if err != nil { context.Abort() context.JSON(http.StatusUnauthorized, Response{ diff --git a/service/userService.go b/service/userService.go index 7b4e1ff..f112371 100644 --- a/service/userService.go +++ b/service/userService.go @@ -13,6 +13,8 @@ type UserService interface { // GetTableUserById GetUserById 根据user_id获得TableUser对象 GetTableUserById(id int64) TableUser + // InsertTableUser 将tableUser插入表内 + InsertTableUser(tableUser *TableUser) bool /* 他人使用 */ @@ -24,7 +26,7 @@ type UserService interface { // 根据token返回id // 接口:auth中间件,解析完token,将userid放入context - //(调用方法:直接在context内拿参数"user_id"的值) + //(调用方法:直接在context内拿参数"userId"的值) fmt.Printf("userInfo: %v\n", c.GetString("userId")) } type User struct { diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index 1affb64..c946ac0 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -59,6 +59,14 @@ func (usi *UserServiceImpl) GetTableUserById(id int64) TableUser { } } +func (usi *UserServiceImpl) InsertTableUser(tableUser *TableUser) bool { + if err := dao.Db.Create(&tableUser).Error; err != nil { + log.Println("插入失败") + return false + } + return true +} + func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { tableUser := TableUser{} if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { @@ -69,7 +77,8 @@ func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { } else { log.Println("未找到该用户") } - impl := UserServiceImpl{} + fsi := new(FollowServiceImpl) + impl := UserServiceImpl{fsi} followCount, _ := impl.FollowService.GetFollowingCnt(id) followerCount, _ := impl.FollowService.GetFollowerCnt(id) user := User{ @@ -92,7 +101,8 @@ func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, e } else { log.Println("未找到该用户") } - impl := UserServiceImpl{} + fsi := new(FollowServiceImpl) + impl := UserServiceImpl{fsi} followCount, _ := impl.FollowService.GetFollowingCnt(id) followerCount, _ := impl.FollowService.GetFollowerCnt(id) isfollow, _ := impl.FollowService.IsFollowing(curId, id) @@ -106,13 +116,23 @@ func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, e return user, errors.New("query fail") } +func GenerateToken(username string) string { + u := UserService.GetTableUserByUsername(new(UserServiceImpl), username) + fmt.Printf("generatetoken: %v\n", u) + token := NewToken(u) + println(token) + return token +} + func NewToken(u *TableUser) string { expiresTime := time.Now().Unix() + int64(config.OneDayOfHours) fmt.Printf("%v\n", expiresTime) + id64 := u.Id + fmt.Printf("newtoken: %v\n", strconv.FormatInt(id64, 10)) claims := jwt.StandardClaims{ Audience: u.Name, ExpiresAt: expiresTime, - Id: strconv.FormatInt(1, 10), + Id: strconv.FormatInt(id64, 10), IssuedAt: time.Now().Unix(), Issuer: "tiktok", NotBefore: time.Now().Unix(), From a0c3f8ae450f1ab214ff46146bbb3bd3e8884c56 Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Tue, 17 May 2022 19:37:26 +0800 Subject: [PATCH 23/70] =?UTF-8?q?dev-20220517-like=20=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/likeSub.go | 49 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/service/likeSub.go b/service/likeSub.go index d6a2c33..27e1a26 100644 --- a/service/likeSub.go +++ b/service/likeSub.go @@ -4,19 +4,38 @@ type LikeSub struct { } func (like *LikeSub) GetVideo(videoId int64) (Video, error) { - return Video{ - Id: 1, - Author: User{ - Id: 1, - Name: "lzz", - FollowCount: 12, - FollowerCount: 13, - IsFollow: true, - }, - PlayUrl: "www.baidu.com", - CoverUrl: "www.baidu.com", - FavoriteCount: 2, - CommentCount: 3, - IsFavorite: true, - }, nil + if videoId%2 == 1 { + return Video{ + Id: 1, + Author: User{ + Id: 1, + Name: "lzz", + FollowCount: 12, + FollowerCount: 13, + IsFollow: true, + }, + PlayUrl: "www.baidu.com", + CoverUrl: "www.baidu.com", + FavoriteCount: 2, + CommentCount: 3, + IsFavorite: true, + }, nil + } else { + return Video{ + Id: 2, + Author: User{ + Id: 2, + Name: "lzz2", + FollowCount: 11, + FollowerCount: 11, + IsFollow: false, + }, + PlayUrl: "www.baidu11.com", + CoverUrl: "www.baidu11.com", + FavoriteCount: 1, + CommentCount: 3, + IsFavorite: false, + }, nil + } + } From db7a9a45790285d36056a874470238a9cda2ebda Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Tue, 17 May 2022 19:58:33 +0800 Subject: [PATCH 24/70] =?UTF-8?q?dev-20220517-user=20userServiceImpl?= =?UTF-8?q?=E7=BB=93=E6=9E=84=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/userServiceImpl.go | 2 +- service/userSub.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index c946ac0..e491471 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -124,7 +124,7 @@ func GenerateToken(username string) string { return token } -func NewToken(u *TableUser) string { +func NewToken(u TableUser) string { expiresTime := time.Now().Unix() + int64(config.OneDayOfHours) fmt.Printf("%v\n", expiresTime) id64 := u.Id diff --git a/service/userSub.go b/service/userSub.go index 6d43c33..0735d8c 100644 --- a/service/userSub.go +++ b/service/userSub.go @@ -1 +1,32 @@ package service + +type FollowServiceImpl struct { +} + +func (fsi *FollowServiceImpl) IsFollowing(userId int64, targetId int64) (bool, error) { + return true, nil +} + +func (fsi *FollowServiceImpl) GetFollowingCnt(userId int64) (int64, error) { + return int64(1), nil +} + +func (fsi *FollowServiceImpl) GetFollowerCnt(userId int64) (int64, error) { + return int64(1), nil +} + +func (fsi *FollowServiceImpl) AddFollowRelation(userId int64, targetId int64) (bool, error) { + return true, nil +} + +func (fsi *FollowServiceImpl) DeleteFollowRelation(userId int64, targetId int64) (bool, error) { + return true, nil +} + +func (fsi *FollowServiceImpl) GetFollowing(userId int64) ([]User, error) { + return nil, nil +} + +func (fsi *FollowServiceImpl) GetFollowers(userId int64) ([]User, error) { + return nil, nil +} From 7c8fc2cca4b2e720bac15468ba14a3d57ae7ab37 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Tue, 17 May 2022 20:06:05 +0800 Subject: [PATCH 25/70] =?UTF-8?q?dev-20220517-user=20userServiceImpl?= =?UTF-8?q?=E7=BB=93=E6=9E=84=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0(?= =?UTF-8?q?=E4=BF=AE=E6=94=B9Bug)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/userController.go | 6 +++--- service/userServiceImpl.go | 18 ++++++++++-------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/controller/userController.go b/controller/userController.go index 1179afd..509dda6 100644 --- a/controller/userController.go +++ b/controller/userController.go @@ -81,12 +81,12 @@ func UserInfo(c *gin.Context) { if u, err := service.UserService.GetUserById(new(service.UserServiceImpl), id); err != nil { c.JSON(http.StatusOK, UserResponse{ - Response: Response{StatusCode: 0}, - User: u, + Response: Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, }) } else { c.JSON(http.StatusOK, UserResponse{ - Response: Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, + Response: Response{StatusCode: 0}, + User: u, }) } } diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index e491471..4acd469 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -72,10 +72,11 @@ func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { log.Println(err.Error()) } - if tableUser.Id == id { - log.Println("查询成功") - } else { + if tableUser.Id != id { log.Println("未找到该用户") + return User{}, errors.New("query fail") + } else { + log.Println("查询成功") } fsi := new(FollowServiceImpl) impl := UserServiceImpl{fsi} @@ -88,7 +89,7 @@ func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { FollowerCount: followerCount, IsFollow: false, } - return user, errors.New("query fail") + return user, nil } func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, error) { @@ -96,10 +97,11 @@ func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, e if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { log.Println(err.Error()) } - if tableUser.Id == id { - log.Println("查询成功") - } else { + if tableUser.Id != id { log.Println("未找到该用户") + return User{}, errors.New("query fail") + } else { + log.Println("查询成功") } fsi := new(FollowServiceImpl) impl := UserServiceImpl{fsi} @@ -113,7 +115,7 @@ func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, e FollowerCount: followerCount, IsFollow: isfollow, } - return user, errors.New("query fail") + return user, nil } func GenerateToken(username string) string { From 4a2a6671e9c56e4e66ad4aae36a4cc640b79f71b Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Tue, 17 May 2022 21:22:10 +0800 Subject: [PATCH 26/70] =?UTF-8?q?dev-20220517-user=20=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E4=BB=A3=E7=A0=81(=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=B3=A8=E9=87=8A=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.go | 2 ++ controller/userController.go | 9 ++++++--- middleware/Auth.go | 5 ++++- service/userService.go | 8 +++++--- service/userServiceImpl.go | 10 ++++++++++ service/userSub.go | 5 +++-- 6 files changed, 30 insertions(+), 9 deletions(-) diff --git a/config/config.go b/config/config.go index 216d3db..4e214dc 100644 --- a/config/config.go +++ b/config/config.go @@ -1,7 +1,9 @@ package config +// Secret 密钥 var Secret = "tiktok" +// OneDayOfHours 时间 var OneDayOfHours = 60 * 60 * 24 var OneMinute = 60 * 1 var OneMonth = 60 * 60 * 24 * 30 diff --git a/controller/userController.go b/controller/userController.go index 509dda6..2d89d04 100644 --- a/controller/userController.go +++ b/controller/userController.go @@ -23,6 +23,7 @@ type UserResponse struct { User service.User `json:"user"` } +// Register POST douyin/user/register/ 用户注册 func Register(c *gin.Context) { username := c.Query("username") password := c.Query("password") @@ -40,7 +41,7 @@ func Register(c *gin.Context) { Password: service.EnCoder(password), } if usi.InsertTableUser(&newUser) != true { - println("insert data fail") + println("Insert Data Fail") } token := service.GenerateToken(username) c.JSON(http.StatusOK, UserLoginResponse{ @@ -51,6 +52,7 @@ func Register(c *gin.Context) { } } +// Login POST douyin/user/login/ 用户登录 func Login(c *gin.Context) { username := c.Query("username") password := c.Query("password") @@ -70,18 +72,19 @@ func Login(c *gin.Context) { }) } else { c.JSON(http.StatusOK, UserLoginResponse{ - Response: Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, + Response: Response{StatusCode: 1, StatusMsg: "Username or Password Error"}, }) } } +// UserInfo GET douyin/user/ 用户信息 func UserInfo(c *gin.Context) { user_id := c.Query("user_id") id, _ := strconv.ParseInt(user_id, 10, 64) if u, err := service.UserService.GetUserById(new(service.UserServiceImpl), id); err != nil { c.JSON(http.StatusOK, UserResponse{ - Response: Response{StatusCode: 1, StatusMsg: "User doesn't exist"}, + Response: Response{StatusCode: 1, StatusMsg: "User Doesn't Exist"}, }) } else { c.JSON(http.StatusOK, UserResponse{ diff --git a/middleware/Auth.go b/middleware/Auth.go index 086f20a..4698e47 100644 --- a/middleware/Auth.go +++ b/middleware/Auth.go @@ -13,6 +13,8 @@ type Response struct { StatusMsg string `json:"status_msg,omitempty"` } +// Auth 鉴权中间件 +// 若用户携带的token正确,解析token,将userId放入上下文context中并放行;否则,返回错误信息 func Auth() gin.HandlerFunc { return func(context *gin.Context) { auth := context.Request.Header.Get("Authorization") @@ -29,7 +31,7 @@ func Auth() gin.HandlerFunc { if err != nil { context.Abort() context.JSON(http.StatusUnauthorized, Response{ - StatusMsg: "token 无效", + StatusMsg: "Token Error", }) } else { println("token 正确") @@ -38,6 +40,7 @@ func Auth() gin.HandlerFunc { } } +// parseToken 解析token func parseToken(token string) (*jwt.StandardClaims, error) { jwtToken, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(token *jwt.Token) (i interface{}, e error) { return []byte(config.Secret), nil diff --git a/service/userService.go b/service/userService.go index f112371..b6d5c2c 100644 --- a/service/userService.go +++ b/service/userService.go @@ -4,13 +4,13 @@ type UserService interface { /* 个人使用 */ - // GetTableUserList GetUserList 获得全部TableUser对象 + // GetTableUserList 获得全部TableUser对象 GetTableUserList() []TableUser - // GetTableUserByUsername GetUserByUsername 根据username获得TableUser对象 + // GetTableUserByUsername 根据username获得TableUser对象 GetTableUserByUsername(name string) TableUser - // GetTableUserById GetUserById 根据user_id获得TableUser对象 + // GetTableUserById 根据user_id获得TableUser对象 GetTableUserById(id int64) TableUser // InsertTableUser 将tableUser插入表内 @@ -29,6 +29,7 @@ type UserService interface { //(调用方法:直接在context内拿参数"userId"的值) fmt.Printf("userInfo: %v\n", c.GetString("userId")) } +// User 最终封装后,controller返回的User结构体 type User struct { Id int64 `json:"id,omitempty"` Name string `json:"name,omitempty"` @@ -37,6 +38,7 @@ type User struct { IsFollow bool `json:"is_follow,omitempty"` } +// TableUser users表对应的结构体 type TableUser struct { Id int64 Name string diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index 4acd469..fa2d3bd 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -18,10 +18,12 @@ type UserServiceImpl struct { FollowService } +// TableName 修改表名映射 func (tableUser TableUser) TableName() string { return "users" } +// GetTableUserList 获得全部TableUser对象 func (usi *UserServiceImpl) GetTableUserList() []TableUser { tableUsers := []TableUser{} if err := dao.Db.Find(&tableUsers).Error; err != nil { @@ -31,6 +33,7 @@ func (usi *UserServiceImpl) GetTableUserList() []TableUser { return tableUsers } +// GetTableUserByUsername 根据username获得TableUser对象 func (usi *UserServiceImpl) GetTableUserByUsername(name string) TableUser { tableUser := TableUser{} if err := dao.Db.Where("name = ?", name).First(&tableUser).Error; err != nil { @@ -45,6 +48,7 @@ func (usi *UserServiceImpl) GetTableUserByUsername(name string) TableUser { } } +// GetTableUserById 根据user_id获得TableUser对象 func (usi *UserServiceImpl) GetTableUserById(id int64) TableUser { tableUser := TableUser{} if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { @@ -59,6 +63,7 @@ func (usi *UserServiceImpl) GetTableUserById(id int64) TableUser { } } +// InsertTableUser 将tableUser插入表内 func (usi *UserServiceImpl) InsertTableUser(tableUser *TableUser) bool { if err := dao.Db.Create(&tableUser).Error; err != nil { log.Println("插入失败") @@ -67,6 +72,7 @@ func (usi *UserServiceImpl) InsertTableUser(tableUser *TableUser) bool { return true } +// GetUserById 未登录情况下,根据user_id获得User对象 func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { tableUser := TableUser{} if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { @@ -92,6 +98,7 @@ func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { return user, nil } +// GetUserByIdWithCurId 已登录(curID)情况下,根据user_id获得User对象 func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, error) { tableUser := TableUser{} if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { @@ -118,6 +125,7 @@ func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, e return user, nil } +// GenerateToken 根据username生成一个token func GenerateToken(username string) string { u := UserService.GetTableUserByUsername(new(UserServiceImpl), username) fmt.Printf("generatetoken: %v\n", u) @@ -126,6 +134,7 @@ func GenerateToken(username string) string { return token } +// NewToken 根据信息创建token func NewToken(u TableUser) string { expiresTime := time.Now().Unix() + int64(config.OneDayOfHours) fmt.Printf("%v\n", expiresTime) @@ -152,6 +161,7 @@ func NewToken(u TableUser) string { } } +// EnCoder 密码加密 func EnCoder(password string) string { h := hmac.New(sha256.New, []byte(password)) sha := hex.EncodeToString(h.Sum(nil)) diff --git a/service/userSub.go b/service/userSub.go index 0735d8c..86a2e4b 100644 --- a/service/userSub.go +++ b/service/userSub.go @@ -1,6 +1,7 @@ package service -type FollowServiceImpl struct { +// 如果要实现用户登录所有功能,将下方代码恢复 +/*type FollowServiceImpl struct { } func (fsi *FollowServiceImpl) IsFollowing(userId int64, targetId int64) (bool, error) { @@ -29,4 +30,4 @@ func (fsi *FollowServiceImpl) GetFollowing(userId int64) ([]User, error) { func (fsi *FollowServiceImpl) GetFollowers(userId int64) ([]User, error) { return nil, nil -} +}*/ From 883c8392bfa9cc6563774b0cf5556f0280b197b1 Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Tue, 17 May 2022 22:36:55 +0800 Subject: [PATCH 27/70] =?UTF-8?q?dev-2022-5-17-follow=20=E5=85=B3=E6=B3=A8?= =?UTF-8?q?=E3=80=81=E5=8F=96=E6=B6=88=E5=85=B3=E6=B3=A8=E3=80=81=E5=85=B3?= =?UTF-8?q?=E6=B3=A8=E5=88=97=E8=A1=A8=E3=80=81=E7=B2=89=E4=B8=9D=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/followController.go | 134 +++++++++++++++++++++ dao/FollowDao.go | 187 ++++++++++++++++++++++++++++++ go.mod | 2 +- go.sum | 46 ++++++++ router.go | 7 ++ service/followService.go | 4 - service/followServiceImpl.go | 146 +++++++++++++++++++++++ service/followServiceImpl_test.go | 17 +++ 8 files changed, 538 insertions(+), 5 deletions(-) create mode 100644 controller/followController.go create mode 100644 dao/FollowDao.go create mode 100644 service/followServiceImpl_test.go diff --git a/controller/followController.go b/controller/followController.go new file mode 100644 index 0000000..2886bc3 --- /dev/null +++ b/controller/followController.go @@ -0,0 +1,134 @@ +package controller + +import ( + "TikTok/service" + "github.com/gin-gonic/gin" + "net/http" + "strconv" +) + +// RelationActionResp 关注和取消关注需要返回结构。 +type RelationActionResp struct { + Response +} + +// FollowingResp 获取关注列表需要返回的结构。 +type FollowingResp struct { + Response + users []service.User `json:"users"` +} + +// FollowersResp 获取粉丝列表需要返回的结构。 +type FollowersResp struct { + Response + users []service.User `json:"users"` +} + +// RelationAction 处理关注和取消关注请求。 +func RelationAction(c *gin.Context) { + userId, err1 := strconv.ParseInt(c.GetString("user_id"), 10, 64) + toUserId, err2 := strconv.ParseInt(c.GetString("to_user_id"), 10, 64) + actionType, err3 := strconv.ParseInt(c.GetString("action_type"), 10, 64) + // 传入参数格式有问题。 + if nil != err1 || nil != err2 || nil != err3 || actionType < 1 || actionType > 2 { + c.JSON(http.StatusOK, RelationActionResp{ + Response{ + StatusCode: -1, + StatusMsg: "用户id格式错误", + }, + }) + return + } + // 正常处理 + fsi := service.NewFSIInstance() + switch { + // 关注 + case 1 == actionType: + fsi.AddFollowRelation(userId, toUserId) + // 取关 + case 2 == actionType: + fsi.DeleteFollowRelation(userId, toUserId) + } + c.JSON(http.StatusOK, RelationActionResp{ + Response{ + StatusCode: 0, + StatusMsg: "OK", + }, + }) +} + +// GetFollowing 处理获取关注列表请求 +func GetFollowing(c *gin.Context) { + userId, err := strconv.ParseInt(c.GetString("user_id"), 10, 64) + // 用户id解析出错。 + if nil != err { + c.JSON(http.StatusOK, FollowingResp{ + Response: Response{ + StatusCode: -1, + StatusMsg: "用户id格式错误。", + }, + users: nil, + }) + return + } + // 正常获取关注列表 + fsi := service.NewFSIInstance() + users, err := fsi.GetFollowing(userId) + // 获取关注列表时出错。 + if err != nil { + c.JSON(http.StatusOK, FollowingResp{ + Response: Response{ + StatusCode: -1, + StatusMsg: "获取关注列表时出错。", + }, + users: nil, + }) + return + } + // 成功获取到关注列表。 + c.JSON(http.StatusOK, FollowingResp{ + Response: Response{ + StatusCode: 0, + StatusMsg: "OK", + }, + users: users, + }) +} + +// GetFollowers 处理获取关注列表请求 +func GetFollowers(c *gin.Context) { + userId, err := strconv.ParseInt(c.GetString("user_id"), 10, 64) + // 用户id解析出错。 + if nil != err { + c.JSON(http.StatusOK, FollowingResp{ + Response: Response{ + StatusCode: -1, + StatusMsg: "用户id格式错误。", + }, + users: nil, + }) + return + } + // 正常获取粉丝列表 + fsi := service.NewFSIInstance() + users, err := fsi.GetFollowers(userId) + // 获取关注列表时出错。 + if err != nil { + c.JSON(http.StatusOK, FollowingResp{ + Response: Response{ + StatusCode: -1, + StatusMsg: "获取粉丝列表时出错。", + }, + users: nil, + }) + return + } + // 成功获取到粉丝列表。 + c.JSON(http.StatusOK, FollowingResp{ + Response: Response{ + StatusCode: 0, + StatusMsg: "OK", + }, + users: users, + }) +} diff --git a/dao/FollowDao.go b/dao/FollowDao.go new file mode 100644 index 0000000..099d7d2 --- /dev/null +++ b/dao/FollowDao.go @@ -0,0 +1,187 @@ +package dao + +import ( + "github.com/jinzhu/gorm" + "log" + "sync" +) + +// Follow 用户关系结构,对应用户关系表。 +type Follow struct { + Id int64 + UserId int64 + FollowerId int64 + Cancel int8 +} + +// TableName 设置Follow结构体对应数据库表名。 +func (Follow) TableName() string { + return "follow" +} + +// FollowDao 把dao层看成整体,把dao的curd封装在一个结构体中。 +type FollowDao struct { +} + +var ( + followDao *FollowDao //操作该dao层crud的结构体变量。 + followOnce sync.Once //单例限定,去限定申请一个followDao结构体变量。 +) + +// NewFollowDaoInstance 生成并返回followDao的单例对象。 +func NewFollowDaoInstance() *FollowDao { + followOnce.Do( + func() { + followDao = &FollowDao{} + }) + return followDao +} + +/* +下面为FollowDao的成员方法,即crud逻辑。 +*/ + +// FindRelation 给定当前用户和目标用户id,查询follow表中相应的记录。 +func (*FollowDao) FindRelation(userId int64, targetId int64) (*Follow, error) { + // follow变量用于后续存储数据库查出来的用户关系。 + follow := Follow{} + //当查询出现错误时,日志打印err msg,并return err. + if err := Db. + Where("user_id = ?", userId). + Where("follower_id = ?", targetId). + Where("cancel = ?", 1). + Take(&follow).Error; nil != err { + // 当没查到数据时,gorm也会报错。 + if gorm.IsRecordNotFoundError(err) { + return nil, nil + } + log.Println(err.Error()) + return nil, err + } + //正常情况,返回取到的值和空err. + return &follow, nil +} + +// GetFollowerCnt 给定当前用户id,查询follow表中该用户的粉丝数。 +func (*FollowDao) GetFollowerCnt(userId int64) (int64, error) { + // 用于存储当前用户粉丝数的变量 + var cnt int64 + // 当查询出现错误的情况,日志打印err msg,并返回err. + if err := Db. + Model(Follow{}). + Where("user_id = ?", userId). + Where("cancel = ?", 1). + Count(&cnt).Error; nil != err { + log.Println(err.Error()) + return 0, err + } + // 正常情况,返回取到的粉丝数。 + return cnt, nil +} + +// GetFollowingCnt 给定当前用户id,查询follow表中该用户关注了多少人。 +func (*FollowDao) GetFollowingCnt(userId int64) (int64, error) { + // 用于存储当前用户关注了多少人。 + var cnt int64 + // 查询出错,日志打印err msg,并return err + if err := Db.Model(Follow{}). + Where("follower_id = ?", userId). + Where("cancel = ?", 1). + Count(&cnt).Error; nil != err { + log.Println(err.Error()) + return 0, err + } + // 查询成功,返回人数。 + return cnt, nil +} + +// InsertFollowRelation 给定用户和目标对象id,插入其关注关系。 +func (*FollowDao) InsertFollowRelation(userId int64, targetId int64) (bool, error) { + // 生成需要插入的关系结构体。 + follow := Follow{ + UserId: userId, + FollowerId: targetId, + Cancel: 1, + } + // 插入失败,返回err. + if err := Db.Create(follow).Error; nil != err { + log.Println(err.Error()) + return false, err + } + // 插入成功 + return true, nil +} + +// FindEverFollowing 给定当前用户和目标用户id,查看曾经是否有关注关系。 +func (*FollowDao) FindEverFollowing(userId int64, targetId int64) (*Follow, error) { + // 用于存储查出来的关注关系。 + follow := Follow{} + //当查询出现错误时,日志打印err msg,并return err. + if err := Db. + Where("user_id = ?", userId). + Where("follower_id = ?", targetId). + Where("cancel = ?", 0). + Take(&follow).Error; nil != err { + // 当没查到记录报错时,不当做错误处理。 + if gorm.IsRecordNotFoundError(err) { + return nil, nil + } + log.Println(err.Error()) + return nil, err + } + //正常情况,返回取到的关系和空err. + return &follow, nil +} + +// UpdateFollowRelation 给定用户和目标用户的id,更新他们的关系为取消关注或再次关注。 +func (*FollowDao) UpdateFollowRelation(userId int64, targetId int64, cancel int8) (bool, error) { + // 更新失败,返回错误。 + if err := Db.Model(Follow{}). + Where("user_id = ?", userId). + Where("follower_id = ?", targetId). + Update("cancel", 1).Error; nil != err { + // 更新失败,打印错误日志。 + log.Println(err.Error()) + return false, err + } + // 更新成功。 + return true, nil +} + +// GetFollowingIds 给定用户id,查询他关注了哪些人的id。 +func (*FollowDao) GetFollowingIds(userId int64) ([]int64, error) { + var ids []int64 + if err := Db. + Model(Follow{}). + Where("follower_id = ?", userId). + Pluck("user_id", &ids).Error; nil != err { + // 没有关注任何人,但是不能算错。 + if gorm.IsRecordNotFoundError(err) { + return nil, nil + } + // 查询出错。 + log.Println(err.Error()) + return nil, err + } + // 查询成功。 + return ids, nil +} + +// GetFollowersIds 给定用户id,查询他关注了哪些人的id。 +func (*FollowDao) GetFollowersIds(userId int64) ([]int64, error) { + var ids []int64 + if err := Db. + Model(Follow{}). + Where("user_id = ?", userId). + Pluck("follower_id", &ids).Error; nil != err { + // 没有粉丝,但是不能算错。 + if gorm.IsRecordNotFoundError(err) { + return nil, nil + } + // 查询出错。 + log.Println(err.Error()) + return nil, err + } + // 查询成功。 + return ids, nil +} diff --git a/go.mod b/go.mod index 313bbac..7fb68ca 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module TikTok -go 1.18 +go 1.17 require ( github.com/dgrijalva/jwt-go v3.2.0+incompatible diff --git a/go.sum b/go.sum index 45d36ac..9990aee 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,13 @@ +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs= +github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY= github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -13,6 +18,7 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumC github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= @@ -20,8 +26,10 @@ github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= +github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= github.com/go-openapi/spec v0.20.6 h1:ich1RQ3WDbfoeTqTAb+5EIxNmpKVJZWBNah9RAT0jIQ= github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= @@ -50,6 +58,7 @@ github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiu github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= @@ -61,6 +70,7 @@ github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFF github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= @@ -92,12 +102,21 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/otiai10/copy v1.7.0 h1:hVoPiN+t+7d2nzzwMiDHPSOogsWAStewq3TwU05+clE= +github.com/otiai10/copy v1.7.0/go.mod h1:rmRl6QPdJj6EiUqXQ/4Nn2lLXoNQjFCQbbNrxgc/t3U= +github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= +github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= +github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= +github.com/otiai10/mint v1.3.3/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -107,45 +126,71 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI= github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= +github.com/ugorji/go v1.2.7 h1:qYhyWUUd6WbiM+C6JZAUkIJt/1WrjzNHY9+KCIjVqTo= github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0= github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY= +github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= +github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f h1:OeJjE6G4dgCY4PIXvIRQbE8+RX+uXZyGhUy/ksMGJoc= golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 h1:nonptSpoQ4vQjyraW20DXPAglgQfVnM9ZC6MmNLMR60= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= @@ -157,6 +202,7 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= diff --git a/router.go b/router.go index daa1a71..86fe651 100644 --- a/router.go +++ b/router.go @@ -29,4 +29,11 @@ func initRouter(r *gin.Engine) { //apiRouter.POST("/relation/action/", controller.RelationAction) //apiRouter.GET("/relation/follow/list/", controller.FollowList) //apiRouter.GET("/relation/follower/list/", controller.FollowerList) + + /* + 关注模块 + */ + apiRouter.POST("/douyin/relation/action/", middleware.Auth(), controller.RelationAction) + apiRouter.GET("/douyin/relation/follow/list/", middleware.Auth(), controller.GetFollowing) + apiRouter.GET("douyin/relation/follower/list", middleware.Auth(), controller.GetFollowers) } diff --git a/service/followService.go b/service/followService.go index 07cff76..5c4669f 100644 --- a/service/followService.go +++ b/service/followService.go @@ -1,7 +1,3 @@ -// Package service -// @Description 定义用户关系接口及方法 -// @Author lls -// @Update 20220516 package service // FollowService 定义用户关系接口以及用户关系中的各种方法 diff --git a/service/followServiceImpl.go b/service/followServiceImpl.go index 6d43c33..481dffe 100644 --- a/service/followServiceImpl.go +++ b/service/followServiceImpl.go @@ -1 +1,147 @@ package service + +import ( + "TikTok/dao" + "sync" +) + +// FollowServiceImp 该结构体继承FollowService接口。 +type FollowServiceImp struct { + UserService + FollowService +} + +var ( + followServiceImp *FollowServiceImp //controller层通过该实例变量调用service的所有业务方法。 + followServiceOnce *sync.Once //限定该service对象为单例,节约内存。 +) + +// NewFSIInstance 生成并返回FollowServiceImp结构体单例变量。 +func NewFSIInstance() *FollowServiceImp { + followServiceOnce.Do( + func() { + followServiceImp = &FollowServiceImp{ + UserService: &UserServiceImpl{}, + } + }) + return followServiceImp +} + +// IsFollowing 给定当前用户和目标用户id,判断是否存在关注关系。 +func (*FollowServiceImp) IsFollowing(userId int64, targetId int64) (bool, error) { + relation, err := dao.NewFollowDaoInstance().FindRelation(userId, targetId) + + if nil != err { + return false, err + } + if nil == relation { + return false, nil + } + return true, nil +} + +// AddFollowRelation 给定当前用户和目标对象id,添加他们之间的关注关系。 +func (*FollowServiceImp) AddFollowRelation(userId int64, targetId int64) (bool, error) { + followDao := dao.NewFollowDaoInstance() + follow, err := followDao.FindEverFollowing(userId, targetId) + // 寻找SQL 出错。 + if nil != err { + return false, err + } + // 曾经关注过,只需要update一下cancel即可。 + if nil != follow { + _, err := followDao.UpdateFollowRelation(userId, targetId, 1) + // update 出错。 + if nil != err { + return false, err + } + // update 成功。 + return true, nil + } + // 曾经没有关注过,需要插入一条关注关系。 + _, err = followDao.InsertFollowRelation(userId, targetId) + if nil != err { + // insert 出错 + return false, err + } + // insert 成功。 + return true, nil +} + +// DeleteFollowRelation 给定当前用户和目标用户id,删除其关注关系。 +func (*FollowServiceImp) DeleteFollowRelation(userId int64, targetId int64) (bool, error) { + followDao := dao.NewFollowDaoInstance() + follow, err := followDao.FindEverFollowing(userId, targetId) + // 寻找 SQL 出错。 + if nil != err { + return false, err + } + // 曾经关注过,只需要update一下cancel即可。 + if nil != follow { + _, err := followDao.UpdateFollowRelation(userId, targetId, 0) + // update 出错。 + if nil != err { + return false, err + } + // update 成功。 + return true, nil + } + // 没有关注关系 + return false, nil +} + +// GetFollowing 根据当前用户id来查询他的关注者列表。 +func (f *FollowServiceImp) GetFollowing(userId int64) ([]User, error) { + // 获取关注对象的id数组。 + ids, err := dao.NewFollowDaoInstance().GetFollowingIds(userId) + // 查询出错 + if nil != err { + return nil, err + } + // 没得关注者 + if nil == ids { + return nil, nil + } + // 根据每个id来查询用户信息。 + length := len(ids) + users := make([]User, length) + for i := 0; i < length; i++ { + user, err := f.GetUserById(ids[i]) + // 查询失败,继续查其他的。 + if nil != err { + continue + } + // 查询成功,把user加入相应的位置。 + users[i] = user + } + // 返回关注对象列表。 + return users, nil +} + +// GetFollowers 根据当前用户id来查询他的粉丝列表。 +func (f *FollowServiceImp) GetFollowers(userId int64) ([]User, error) { + // 获取粉丝的id数组。 + ids, err := dao.NewFollowDaoInstance().GetFollowersIds(userId) + // 查询出错 + if nil != err { + return nil, err + } + // 没得粉丝 + if nil == ids { + return nil, nil + } + // 根据每个id来查询用户信息。 + length := len(ids) + users := make([]User, length) + for i := 0; i < length; i++ { + user, err := f.GetUserById(ids[i]) + // 查询失败,继续查其他的。 + if nil != err { + continue + } + // 查询成功,把user加入相应的位置。 + users[i] = user + } + // 返回粉丝列表。 + return users, nil +} diff --git a/service/followServiceImpl_test.go b/service/followServiceImpl_test.go new file mode 100644 index 0000000..09e7458 --- /dev/null +++ b/service/followServiceImpl_test.go @@ -0,0 +1,17 @@ +package service + +import ( + "fmt" + "testing" +) + +func TestIsFollow(t *testing.T) { + isFollow, err := newFSIInstance().IsFollowing(1, 2) + if nil != err { + t.Errorf("IsFollow() error = %v", err) + } + if false == isFollow { + fmt.Println("不存在该关系") + } + fmt.Println("存在该关系") +} From 89ed81772126b9c9bce4fd74e374e1592bca407c Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Wed, 18 May 2022 00:20:23 +0800 Subject: [PATCH 28/70] =?UTF-8?q?dev-20220517-video=20=E5=AE=8C=E6=88=90li?= =?UTF-8?q?st=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/Initdao.go | 6 ++-- dao/videoDao.go | 35 +++++++++++++++++++++ dao/videoDao_test.go | 32 ++++++++++++++++++++ go.mod | 1 + go.sum | 2 ++ router.go | 2 ++ service/videoService.go | 8 ++--- service/videoServiceImpl.go | 52 ++++++++++++++++++++++++++++++++ service/videoServiceImpl_test.go | 18 +++++++++++ 9 files changed, 150 insertions(+), 6 deletions(-) create mode 100644 dao/videoDao.go create mode 100644 dao/videoDao_test.go create mode 100644 service/videoServiceImpl_test.go diff --git a/dao/Initdao.go b/dao/Initdao.go index d4de926..95c52bf 100644 --- a/dao/Initdao.go +++ b/dao/Initdao.go @@ -8,9 +8,11 @@ import ( var Db *gorm.DB -func init() { +func Init() { var err error - Db, err = gorm.Open("mysql", "douyin:zjqxy@tcp(43.138.25.60:3306)/douyin/") + //想要正确的处理time.Time,需要带上 parseTime 参数, + //要支持完整的UTF-8编码,需要将 charset=utf8 更改为 charset=utf8mb4 + Db, err = gorm.Open("mysql", "douyin:zjqxy@tcp(43.138.25.60:3306)/douyin?charset=utf8mb4&parseTime=True&loc=Local") if err != nil { log.Panicln("err:", err.Error()) } diff --git a/dao/videoDao.go b/dao/videoDao.go new file mode 100644 index 0000000..1b92ec1 --- /dev/null +++ b/dao/videoDao.go @@ -0,0 +1,35 @@ +package dao + +import ( + "time" +) + +type TableVideo struct { + ID int64 + AuthorId int64 `copier:"-"` //在拷贝时忽略 + PlayUrl string + CoverUrl string + PublishTime time.Time `copier:"-"` //在拷贝时忽略 +} + +// TableName +// 将TableVideo映射到videos, +// 这样我结构体到名字就不需要是Video了,防止和我Service层到结构体名字冲突 +func (TableVideo) TableName() string { + return "videos" +} + +// GetVideosByAuthorId +// 根据作者的id来查询对应数据库数据,并TableVideo返回切片 +func GetVideosByAuthorId(authorId int64) ([]TableVideo, error) { + //建立结果集接收 + var data []TableVideo + //初始化db + Init() + result := Db.Where(&TableVideo{AuthorId: authorId}).Find(&data) + //如果出现问题,返回对应到空,并且返回error + if result.Error != nil { + return nil, result.Error + } + return data, nil +} diff --git a/dao/videoDao_test.go b/dao/videoDao_test.go new file mode 100644 index 0000000..3b95caf --- /dev/null +++ b/dao/videoDao_test.go @@ -0,0 +1,32 @@ +package dao + +import ( + "fmt" + "testing" +) + +func TestInit(t *testing.T) { + Init() +} + +func TestFind(t *testing.T) { + Init() + var tv TableVideo + result := Db.First(&tv) + fmt.Println(result.RowsAffected) + fmt.Println(tv.ID) + fmt.Println(tv.AuthorId) + fmt.Println(tv.CoverUrl) + fmt.Println(tv.PlayUrl) + fmt.Println(tv.PublishTime) +} + +func TestGetVideosByAuthorId(t *testing.T) { + data, err := GetVideosByAuthorId(2) + if err != nil { + print(err) + } + for _, video := range data { + fmt.Println(video) + } +} diff --git a/go.mod b/go.mod index 313bbac..8c45e2b 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.18 require ( github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gin-gonic/gin v1.7.7 + github.com/jinzhu/copier v0.3.5 github.com/jinzhu/gorm v1.9.16 github.com/swaggo/swag v1.8.1 ) diff --git a/go.sum b/go.sum index 45d36ac..945bb18 100644 --- a/go.sum +++ b/go.sum @@ -50,6 +50,8 @@ github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiu github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= +github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= diff --git a/router.go b/router.go index 67ea7c1..75f7422 100644 --- a/router.go +++ b/router.go @@ -1,5 +1,7 @@ package main +import "github.com/gin-gonic/gin" + func initRouter(r *gin.Engine) { } diff --git a/service/videoService.go b/service/videoService.go index 6618fc5..54155f2 100644 --- a/service/videoService.go +++ b/service/videoService.go @@ -6,8 +6,8 @@ import ( ) type Video struct { - Id int64 - Author User //todo 等user接口 + Id int64 `copier:"ID"` //指定别名 + Author User `copier:"-"` //在拷贝时忽略 PlayUrl string CoverUrl string FavoriteCount int64 @@ -17,7 +17,7 @@ type Video struct { type VideoService interface { // Feed - // 通过传入时间戳,当前用户的id,返回对应的视频数组,以及视频数组中最早的发布时间 + // 通过传入时间戳,当前用户的id,返回对应的视频切片数组,以及视频数组中最早的发布时间 Feed(lastTime time.Time, userId int64) ([]Video, time.Time, error) // GetVideo @@ -27,6 +27,6 @@ type VideoService interface { // 将传入的视频流保存在文件服务器中,并存储在mysql表中 Publish(data *multipart.FileHeader, userId int64) error // List - // 通过userId来查询对应用户发布的视频,并返回对应的视频数组 + // 通过userId来查询对应用户发布的视频,并返回对应的视频切片数组 List(userId int64) ([]Video, error) } diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go index 6d43c33..198775e 100644 --- a/service/videoServiceImpl.go +++ b/service/videoServiceImpl.go @@ -1 +1,53 @@ package service + +import ( + "TikTok/dao" + "github.com/jinzhu/copier" + "mime/multipart" +) + +type VideoServiceImpl struct { + UserService +} + +// Feed +// 通过传入时间戳,当前用户的id,返回对应的视频数组,以及视频数组中最早的发布时间 +//func (videoService VideoServiceImpl) Feed(lastTime time.Time, userId int64) ([]Video, time.Time, error) { +// +//} + +// GetVideo +// 传入视频id获得对应的视频对象 +//func (videoService VideoServiceImpl) GetVideo(videoId int64) (Video, error) { +// return nil,nil +//} + +// Publish +// 将传入的视频流保存在文件服务器中,并存储在mysql表中 +func (videoService VideoServiceImpl) Publish(data *multipart.FileHeader, userId int64) error { + return nil +} + +// List +// 通过userId来查询对应用户发布的视频,并返回对应的视频数组 +func (videoService VideoServiceImpl) List(userId int64) ([]Video, error) { + //依据用户id查询所有的视频,获取视频列表 + data, err := dao.GetVideosByAuthorId(userId) + if err != nil { + return nil, err + } + //提前定义好切片长度 + result := make([]Video, 0, len(data)) + for _, temp := range data { + var video Video + //进行拷贝操作 + copier.Copy(&video, &temp) + //获取对应的user + //video.Author,err = videoService.GetUserById(temp.AuthorId) + //if err != nil { + // return nil, err + //} + result = append(result, video) + } + return result, nil +} diff --git a/service/videoServiceImpl_test.go b/service/videoServiceImpl_test.go new file mode 100644 index 0000000..54421c7 --- /dev/null +++ b/service/videoServiceImpl_test.go @@ -0,0 +1,18 @@ +package service + +import ( + "fmt" + "testing" +) + +func TestList(t *testing.T) { + var videoService VideoServiceImpl + list, err := videoService.List(2) + if err != nil { + return + } + for _, video := range list { + fmt.Println(video) + } + +} From e572a1824143f421d2832c190dc489cba7ca003b Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Wed, 18 May 2022 00:49:36 +0800 Subject: [PATCH 29/70] =?UTF-8?q?dev-20220518-video=20=E5=AE=8C=E5=96=84li?= =?UTF-8?q?st=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/videoServiceImpl.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go index 198775e..f90929b 100644 --- a/service/videoServiceImpl.go +++ b/service/videoServiceImpl.go @@ -43,10 +43,10 @@ func (videoService VideoServiceImpl) List(userId int64) ([]Video, error) { //进行拷贝操作 copier.Copy(&video, &temp) //获取对应的user - //video.Author,err = videoService.GetUserById(temp.AuthorId) - //if err != nil { - // return nil, err - //} + video.Author, err = videoService.GetUserByIdWithCurId(temp.AuthorId, temp.AuthorId) + if err != nil { + return nil, err + } result = append(result, video) } return result, nil From b711a2687031765593cfcf836c30807aa1087d34 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Wed, 18 May 2022 00:20:23 +0800 Subject: [PATCH 30/70] =?UTF-8?q?dev-20220517-video=20=E5=AE=8C=E6=88=90li?= =?UTF-8?q?st=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/videoServiceImpl.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go index f90929b..198775e 100644 --- a/service/videoServiceImpl.go +++ b/service/videoServiceImpl.go @@ -43,10 +43,10 @@ func (videoService VideoServiceImpl) List(userId int64) ([]Video, error) { //进行拷贝操作 copier.Copy(&video, &temp) //获取对应的user - video.Author, err = videoService.GetUserByIdWithCurId(temp.AuthorId, temp.AuthorId) - if err != nil { - return nil, err - } + //video.Author,err = videoService.GetUserById(temp.AuthorId) + //if err != nil { + // return nil, err + //} result = append(result, video) } return result, nil From a886fae3855356671f4f87345519b3ec4a69576a Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Tue, 17 May 2022 22:36:55 +0800 Subject: [PATCH 31/70] =?UTF-8?q?dev-2022-5-17-follow=20=E5=85=B3=E6=B3=A8?= =?UTF-8?q?=E3=80=81=E5=8F=96=E6=B6=88=E5=85=B3=E6=B3=A8=E3=80=81=E5=85=B3?= =?UTF-8?q?=E6=B3=A8=E5=88=97=E8=A1=A8=E3=80=81=E7=B2=89=E4=B8=9D=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E5=B7=B2=E7=BB=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.sum | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.sum b/go.sum index 56cf513..0172cb8 100644 --- a/go.sum +++ b/go.sum @@ -61,6 +61,7 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= @@ -192,7 +193,6 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= From e2c2faa3d97c7dd4ce909d76aa956e1cf0d67861 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Wed, 18 May 2022 01:11:58 +0800 Subject: [PATCH 32/70] Revert "dev-2022-5-17-follow" This reverts commit a886fae3855356671f4f87345519b3ec4a69576a. --- go.sum | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.sum b/go.sum index 0172cb8..56cf513 100644 --- a/go.sum +++ b/go.sum @@ -61,7 +61,6 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= @@ -193,6 +192,7 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= From 61a66e328c69b91c08359e2d1f4e206755d698d1 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Wed, 18 May 2022 01:12:19 +0800 Subject: [PATCH 33/70] Revert "dev-20220517-video" This reverts commit b711a2687031765593cfcf836c30807aa1087d34. --- service/videoServiceImpl.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go index 198775e..f90929b 100644 --- a/service/videoServiceImpl.go +++ b/service/videoServiceImpl.go @@ -43,10 +43,10 @@ func (videoService VideoServiceImpl) List(userId int64) ([]Video, error) { //进行拷贝操作 copier.Copy(&video, &temp) //获取对应的user - //video.Author,err = videoService.GetUserById(temp.AuthorId) - //if err != nil { - // return nil, err - //} + video.Author, err = videoService.GetUserByIdWithCurId(temp.AuthorId, temp.AuthorId) + if err != nil { + return nil, err + } result = append(result, video) } return result, nil From c1f94a9cb0569ee6e4574e3a027cc84f10e116ba Mon Sep 17 00:00:00 2001 From: syx <424193726@qq.com> Date: Wed, 18 May 2022 11:26:44 +0800 Subject: [PATCH 34/70] =?UTF-8?q?dev-20220518-video=20GetVideo=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E6=8E=A5=E5=8F=A3=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/videoService.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/service/videoService.go b/service/videoService.go index 54155f2..3730fd3 100644 --- a/service/videoService.go +++ b/service/videoService.go @@ -22,10 +22,12 @@ type VideoService interface { // GetVideo // 传入视频id获得对应的视频对象 - GetVideo(videoId int64) (Video, error) + GetVideo(videoId int64, userId int64) (Video, error) + // Publish // 将传入的视频流保存在文件服务器中,并存储在mysql表中 Publish(data *multipart.FileHeader, userId int64) error + // List // 通过userId来查询对应用户发布的视频,并返回对应的视频切片数组 List(userId int64) ([]Video, error) From 747c3343b284602329e00009649d1866ef78fa8f Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Wed, 18 May 2022 12:09:53 +0800 Subject: [PATCH 35/70] =?UTF-8?q?dev-20220518-video=20=E7=BC=96=E5=86=99ge?= =?UTF-8?q?tVideo=E6=9C=8D=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/videoDao.go | 14 ++++++++++++++ dao/videoDao_test.go | 9 +++++++++ service/videoServiceImpl.go | 27 ++++++++++++++++++-------- service/videoServiceImpl_test.go | 11 +++++++++++ service/videoSub.go | 33 ++++++++++++++++++++++++++++++++ 5 files changed, 86 insertions(+), 8 deletions(-) diff --git a/dao/videoDao.go b/dao/videoDao.go index 1b92ec1..5a04b48 100644 --- a/dao/videoDao.go +++ b/dao/videoDao.go @@ -33,3 +33,17 @@ func GetVideosByAuthorId(authorId int64) ([]TableVideo, error) { } return data, nil } + +// GetVideoByVideoId +// 依据VideoId来获得视频信息 +func GetVideoByVideoId(videoId int64) (TableVideo, error) { + var tableVideo TableVideo + tableVideo.ID = videoId + Init() + result := Db.First(&tableVideo) + if result.Error != nil { + return tableVideo, result.Error + } + return tableVideo, nil + +} diff --git a/dao/videoDao_test.go b/dao/videoDao_test.go index 3b95caf..ec239cd 100644 --- a/dao/videoDao_test.go +++ b/dao/videoDao_test.go @@ -30,3 +30,12 @@ func TestGetVideosByAuthorId(t *testing.T) { fmt.Println(video) } } + +func TestGetVideoByVideoId(t *testing.T) { + data, err := GetVideoByVideoId(1) + if err != nil { + print(err) + } + fmt.Println(data) + +} diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go index f90929b..40ef0c1 100644 --- a/service/videoServiceImpl.go +++ b/service/videoServiceImpl.go @@ -4,6 +4,7 @@ import ( "TikTok/dao" "github.com/jinzhu/copier" "mime/multipart" + "time" ) type VideoServiceImpl struct { @@ -12,25 +13,35 @@ type VideoServiceImpl struct { // Feed // 通过传入时间戳,当前用户的id,返回对应的视频数组,以及视频数组中最早的发布时间 -//func (videoService VideoServiceImpl) Feed(lastTime time.Time, userId int64) ([]Video, time.Time, error) { -// -//} +func (videoService VideoServiceImpl) Feed(lastTime time.Time, userId int64) ([]Video, time.Time, error) { + return nil, time.Time{}, nil +} // GetVideo // 传入视频id获得对应的视频对象 -//func (videoService VideoServiceImpl) GetVideo(videoId int64) (Video, error) { -// return nil,nil -//} +func (videoService *VideoServiceImpl) GetVideo(videoId int64, userId int64) (Video, error) { + var video Video + data, err := dao.GetVideoByVideoId(videoId) + if err != nil { + return video, err + } + copier.Copy(&video, &data) + video.Author, err = videoService.GetUserByIdWithCurId(data.AuthorId, userId) + if err != nil { + return video, err + } + return video, nil +} // Publish // 将传入的视频流保存在文件服务器中,并存储在mysql表中 -func (videoService VideoServiceImpl) Publish(data *multipart.FileHeader, userId int64) error { +func (videoService *VideoServiceImpl) Publish(data *multipart.FileHeader, userId int64) error { return nil } // List // 通过userId来查询对应用户发布的视频,并返回对应的视频数组 -func (videoService VideoServiceImpl) List(userId int64) ([]Video, error) { +func (videoService *VideoServiceImpl) List(userId int64) ([]Video, error) { //依据用户id查询所有的视频,获取视频列表 data, err := dao.GetVideosByAuthorId(userId) if err != nil { diff --git a/service/videoServiceImpl_test.go b/service/videoServiceImpl_test.go index 54421c7..b0b755b 100644 --- a/service/videoServiceImpl_test.go +++ b/service/videoServiceImpl_test.go @@ -16,3 +16,14 @@ func TestList(t *testing.T) { } } + +func TestGetVideo(t *testing.T) { + var videoService VideoServiceImpl + videoService.UserService = VideoSub{} + video, err := videoService.GetVideo(1, 1) + if err != nil { + return + } + fmt.Println(video) + +} diff --git a/service/videoSub.go b/service/videoSub.go index 6d43c33..5c0ddfe 100644 --- a/service/videoSub.go +++ b/service/videoSub.go @@ -1 +1,34 @@ package service + +type VideoSub struct { +} + +func (vs VideoSub) GetTableUserList() []TableUser { + //TODO implement me + panic("implement me") +} + +func (vs VideoSub) GetTableUserByUsername(name string) TableUser { + //TODO implement me + panic("implement me") +} + +func (vs VideoSub) GetTableUserById(id int64) TableUser { + //TODO implement me + panic("implement me") +} + +func (vs VideoSub) InsertTableUser(tableUser *TableUser) bool { + //TODO implement me + panic("implement me") +} + +func (vs VideoSub) GetUserById(id int64) (User, error) { + //TODO implement me + panic("implement me") +} + +func (vs VideoSub) GetUserByIdWithCurId(id int64, curId int64) (User, error) { + var user User + return user, nil +} From d7e60ac1ba628cde5e7373b818f52518c93fd7cf Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Wed, 18 May 2022 13:18:10 +0800 Subject: [PATCH 36/70] =?UTF-8?q?dev-20220517-like=20=E4=BF=AE=E6=94=B9Get?= =?UTF-8?q?FavouriteList=E5=87=BD=E6=95=B0=EF=BC=8C=E5=AF=B9=E5=85=B6?= =?UTF-8?q?=E4=BB=96=E6=A8=A1=E5=9D=97=E6=97=A0=E5=BD=B1=E5=93=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/likeServiceImpl.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service/likeServiceImpl.go b/service/likeServiceImpl.go index 14d9cb3..d556e22 100644 --- a/service/likeServiceImpl.go +++ b/service/likeServiceImpl.go @@ -80,8 +80,8 @@ func (like *LikeServiceImpl) GetFavouriteList(userId int64) ([]Video, error) { //如果查询到数据,遍历video_id,将每个video对象添加到集合中去; //likesub := new(LikeSub) for video_id := range video_ids { - //video, err1 := likesub.GetVideo(int64(video_id)) - video, err1 := like.GetVideo(int64(video_id)) + //video, err1 := likesub.GetVideo(int64(video_id),userId) + video, err1 := like.GetVideo(int64(video_id), userId) if err1 != nil { //如果没有获取这个video_id的视频,视频可能被删除了,跳过 log.Panicln(errors.New("can't find this favourite video")) continue From d025d25fec433332218822bc74fd9dc465f4f09f Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Wed, 18 May 2022 16:21:33 +0800 Subject: [PATCH 37/70] =?UTF-8?q?dev-20220517-user=20=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E4=BB=A3=E7=A0=81(=E9=87=8D=E6=9E=84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/userController.go | 7 +- dao/UserDao.go | 68 +++++++++++++++++++ dao/userDao_test.go | 34 ++++++++++ service/userService.go | 20 +++--- service/userServiceImpl.go | 113 +++++++++++++++----------------- service/userServiceImpl_test.go | 48 ++++++++++++++ service/videoSub.go | 10 +-- 7 files changed, 225 insertions(+), 75 deletions(-) create mode 100644 dao/userDao_test.go create mode 100644 service/userServiceImpl_test.go diff --git a/controller/userController.go b/controller/userController.go index 2d89d04..6e3c07c 100644 --- a/controller/userController.go +++ b/controller/userController.go @@ -1,6 +1,7 @@ package controller import ( + "TikTok/dao" "TikTok/service" "github.com/gin-gonic/gin" "net/http" @@ -36,7 +37,7 @@ func Register(c *gin.Context) { Response: Response{StatusCode: 1, StatusMsg: "User already exist"}, }) } else { - newUser := service.TableUser{ + newUser := dao.TableUser{ Name: username, Password: service.EnCoder(password), } @@ -82,7 +83,9 @@ func UserInfo(c *gin.Context) { user_id := c.Query("user_id") id, _ := strconv.ParseInt(user_id, 10, 64) - if u, err := service.UserService.GetUserById(new(service.UserServiceImpl), id); err != nil { + usi := service.UserServiceImpl{} + + if u, err := usi.GetUserById(id); err != nil { c.JSON(http.StatusOK, UserResponse{ Response: Response{StatusCode: 1, StatusMsg: "User Doesn't Exist"}, }) diff --git a/dao/UserDao.go b/dao/UserDao.go index 85f5bf2..ba0ccde 100644 --- a/dao/UserDao.go +++ b/dao/UserDao.go @@ -1,8 +1,76 @@ package dao +import ( + "log" + "sync" +) + // TableUser 对应数据库User表结构的结构体 type TableUser struct { Id int64 Name string Password string } + +// TableName 修改表名映射 +func (tableUser TableUser) TableName() string { + return "users" +} + +type UserDao struct { +} + +var ( + userDao *UserDao + userOnce sync.Once +) + +func NewUserDaoInstance() *UserDao { + userOnce.Do( + func() { + userDao = &UserDao{} + }) + return userDao +} + +func (*UserDao) GetTableUserList() ([]TableUser, error) { + tableUsers := []TableUser{} + Init() + if err := Db.Find(&tableUsers).Error; err != nil { + log.Println(err.Error()) + return tableUsers, err + } + return tableUsers, nil +} + +// GetTableUserByUsername 根据username获得TableUser对象 +func (*UserDao) GetTableUserByUsername(name string) (TableUser, error) { + tableUser := TableUser{} + Init() + if err := Db.Where("name = ?", name).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + return tableUser, err + } + return tableUser, nil +} + +// GetTableUserById 根据user_id获得TableUser对象 +func (*UserDao) GetTableUserById(id int64) (TableUser, error) { + tableUser := TableUser{} + Init() + if err := Db.Where("id = ?", id).First(&tableUser).Error; err != nil { + log.Println(err.Error()) + return tableUser, err + } + return tableUser, nil +} + +// InsertTableUser 将tableUser插入表内 +func (*UserDao) InsertTableUser(tableUser *TableUser) bool { + Init() + if err := Db.Create(&tableUser).Error; err != nil { + log.Println(err.Error()) + return false + } + return true +} diff --git a/dao/userDao_test.go b/dao/userDao_test.go new file mode 100644 index 0000000..7215667 --- /dev/null +++ b/dao/userDao_test.go @@ -0,0 +1,34 @@ +package dao + +import ( + "fmt" + "testing" +) + +func TestGetTableUserList(t *testing.T) { + list, err := NewUserDaoInstance().GetTableUserList() + fmt.Printf("%v", list) + fmt.Printf("%v", err) +} + +func TestGetTableUserByUsername(t *testing.T) { + list, err := NewUserDaoInstance().GetTableUserByUsername("test") + fmt.Printf("%v", list) + fmt.Printf("%v", err) +} + +func TestGetTableUserById(t *testing.T) { + list, err := NewUserDaoInstance().GetTableUserById(int64(4)) + fmt.Printf("%v", list) + fmt.Printf("%v", err) +} + +func TestInsertTableUser(t *testing.T) { + tu := &TableUser{ + Id: 5, + Name: "a", + Password: "111111", + } + list := NewUserDaoInstance().InsertTableUser(tu) + fmt.Printf("%v", list) +} diff --git a/service/userService.go b/service/userService.go index b6d5c2c..5d66e24 100644 --- a/service/userService.go +++ b/service/userService.go @@ -1,20 +1,22 @@ package service +import "TikTok/dao" + type UserService interface { /* 个人使用 */ // GetTableUserList 获得全部TableUser对象 - GetTableUserList() []TableUser + GetTableUserList() []dao.TableUser // GetTableUserByUsername 根据username获得TableUser对象 - GetTableUserByUsername(name string) TableUser + GetTableUserByUsername(name string) dao.TableUser // GetTableUserById 根据user_id获得TableUser对象 - GetTableUserById(id int64) TableUser + GetTableUserById(id int64) dao.TableUser // InsertTableUser 将tableUser插入表内 - InsertTableUser(tableUser *TableUser) bool + InsertTableUser(tableUser *dao.TableUser) bool /* 他人使用 */ @@ -39,8 +41,8 @@ type User struct { } // TableUser users表对应的结构体 -type TableUser struct { - Id int64 - Name string - Password string -} +//type TableUser struct { +// Id int64 +// Name string +// Password string +//} diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index fa2d3bd..54cbbaf 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -6,7 +6,6 @@ import ( "crypto/hmac" "crypto/sha256" "encoding/hex" - "errors" "fmt" "github.com/dgrijalva/jwt-go" "log" @@ -18,54 +17,44 @@ type UserServiceImpl struct { FollowService } -// TableName 修改表名映射 -func (tableUser TableUser) TableName() string { - return "users" -} - // GetTableUserList 获得全部TableUser对象 -func (usi *UserServiceImpl) GetTableUserList() []TableUser { - tableUsers := []TableUser{} - if err := dao.Db.Find(&tableUsers).Error; err != nil { - log.Panicln("err:", err.Error()) +func (usi *UserServiceImpl) GetTableUserList() []dao.TableUser { + tableUsers, err := dao.NewUserDaoInstance().GetTableUserList() + if err != nil { + log.Println("Err:", err.Error()) return tableUsers } return tableUsers } // GetTableUserByUsername 根据username获得TableUser对象 -func (usi *UserServiceImpl) GetTableUserByUsername(name string) TableUser { - tableUser := TableUser{} - if err := dao.Db.Where("name = ?", name).First(&tableUser).Error; err != nil { - log.Println(err.Error()) - } - if tableUser.Name == name { - log.Println("查询成功") - return tableUser - } else { - log.Println("未找到该用户") +func (usi *UserServiceImpl) GetTableUserByUsername(name string) dao.TableUser { + tableUser, err := dao.NewUserDaoInstance().GetTableUserByUsername(name) + if err != nil { + log.Println("Err:", err.Error()) + log.Println("User Not Found") return tableUser } + log.Println("Query User Success") + return tableUser } // GetTableUserById 根据user_id获得TableUser对象 -func (usi *UserServiceImpl) GetTableUserById(id int64) TableUser { - tableUser := TableUser{} - if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { - log.Println(err.Error()) - } - if tableUser.Id == id { - log.Println("查询成功") - return tableUser - } else { - log.Println("未找到该用户") +func (usi *UserServiceImpl) GetTableUserById(id int64) dao.TableUser { + tableUser, err := dao.NewUserDaoInstance().GetTableUserById(id) + if err != nil { + log.Println("Err:", err.Error()) + log.Println("User Not Found") return tableUser } + log.Println("Query User Success") + return tableUser } // InsertTableUser 将tableUser插入表内 -func (usi *UserServiceImpl) InsertTableUser(tableUser *TableUser) bool { - if err := dao.Db.Create(&tableUser).Error; err != nil { +func (usi *UserServiceImpl) InsertTableUser(tableUser *dao.TableUser) bool { + flag := dao.NewUserDaoInstance().InsertTableUser(tableUser) + if flag == false { log.Println("插入失败") return false } @@ -74,21 +63,23 @@ func (usi *UserServiceImpl) InsertTableUser(tableUser *TableUser) bool { // GetUserById 未登录情况下,根据user_id获得User对象 func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { - tableUser := TableUser{} - if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { - log.Println(err.Error()) + user := User{ + Id: 0, + Name: "", + FollowCount: 0, + FollowerCount: 0, + IsFollow: false, } - if tableUser.Id != id { - log.Println("未找到该用户") - return User{}, errors.New("query fail") - } else { - log.Println("查询成功") + tableUser, err := dao.NewUserDaoInstance().GetTableUserById(id) + if err != nil { + log.Println("Err:", err.Error()) + log.Println("User Not Found") + return user, err } - fsi := new(FollowServiceImpl) - impl := UserServiceImpl{fsi} - followCount, _ := impl.FollowService.GetFollowingCnt(id) - followerCount, _ := impl.FollowService.GetFollowerCnt(id) - user := User{ + log.Println("Query User Success") + followCount, _ := usi.GetFollowingCnt(id) + followerCount, _ := usi.GetFollowerCnt(id) + user = User{ Id: id, Name: tableUser.Name, FollowCount: followCount, @@ -100,22 +91,24 @@ func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { // GetUserByIdWithCurId 已登录(curID)情况下,根据user_id获得User对象 func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, error) { - tableUser := TableUser{} - if err := dao.Db.Where("id = ?", id).First(&tableUser).Error; err != nil { - log.Println(err.Error()) + user := User{ + Id: 0, + Name: "", + FollowCount: 0, + FollowerCount: 0, + IsFollow: false, } - if tableUser.Id != id { - log.Println("未找到该用户") - return User{}, errors.New("query fail") - } else { - log.Println("查询成功") + tableUser, err := dao.NewUserDaoInstance().GetTableUserById(id) + if err != nil { + log.Println("Err:", err.Error()) + log.Println("User Not Found") + return user, err } - fsi := new(FollowServiceImpl) - impl := UserServiceImpl{fsi} - followCount, _ := impl.FollowService.GetFollowingCnt(id) - followerCount, _ := impl.FollowService.GetFollowerCnt(id) - isfollow, _ := impl.FollowService.IsFollowing(curId, id) - user := User{ + log.Println("Query User Success") + followCount, _ := usi.GetFollowingCnt(id) + followerCount, _ := usi.GetFollowerCnt(id) + isfollow, _ := usi.IsFollowing(curId, id) + user = User{ Id: id, Name: tableUser.Name, FollowCount: followCount, @@ -135,7 +128,7 @@ func GenerateToken(username string) string { } // NewToken 根据信息创建token -func NewToken(u TableUser) string { +func NewToken(u dao.TableUser) string { expiresTime := time.Now().Unix() + int64(config.OneDayOfHours) fmt.Printf("%v\n", expiresTime) id64 := u.Id diff --git a/service/userServiceImpl_test.go b/service/userServiceImpl_test.go new file mode 100644 index 0000000..80b6df2 --- /dev/null +++ b/service/userServiceImpl_test.go @@ -0,0 +1,48 @@ +package service + +import ( + "TikTok/dao" + "fmt" + "testing" +) + +func TestGetTableUserList(t *testing.T) { + impl := UserServiceImpl{} + list := impl.GetTableUserList() + fmt.Printf("%v", list) +} + +func TestGetTableUserByUsername(t *testing.T) { + impl := UserServiceImpl{} + list := impl.GetTableUserByUsername("test22") + fmt.Printf("%v", list) +} + +func TestGetTableUserById(t *testing.T) { + impl := UserServiceImpl{} + list := impl.GetTableUserById(int64(4)) + fmt.Printf("%v", list) +} + +func TestInsertTableUser(t *testing.T) { + impl := UserServiceImpl{} + user := &dao.TableUser{ + Id: 20000, + Name: "qaq", + Password: "111111", + } + list := impl.InsertTableUser(user) + fmt.Printf("%v", list) +} + +func TestGetUserById(t *testing.T) { + impl := UserServiceImpl{} + list, _ := impl.GetUserById(int64(4)) + fmt.Printf("%v", list) +} + +func TestGetUserByIdWithCurId(t *testing.T) { + impl := UserServiceImpl{} + list, _ := impl.GetUserByIdWithCurId(int64(4), int64(5)) + fmt.Printf("%v", list) +} diff --git a/service/videoSub.go b/service/videoSub.go index 5c0ddfe..b327c11 100644 --- a/service/videoSub.go +++ b/service/videoSub.go @@ -1,24 +1,26 @@ package service +import "TikTok/dao" + type VideoSub struct { } -func (vs VideoSub) GetTableUserList() []TableUser { +func (vs VideoSub) GetTableUserList() []dao.TableUser { //TODO implement me panic("implement me") } -func (vs VideoSub) GetTableUserByUsername(name string) TableUser { +func (vs VideoSub) GetTableUserByUsername(name string) dao.TableUser { //TODO implement me panic("implement me") } -func (vs VideoSub) GetTableUserById(id int64) TableUser { +func (vs VideoSub) GetTableUserById(id int64) dao.TableUser { //TODO implement me panic("implement me") } -func (vs VideoSub) InsertTableUser(tableUser *TableUser) bool { +func (vs VideoSub) InsertTableUser(tableUser *dao.TableUser) bool { //TODO implement me panic("implement me") } From bf46d9b25a903b3193c26c229fcd4e51532b8dcc Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Thu, 19 May 2022 01:06:49 +0800 Subject: [PATCH 38/70] =?UTF-8?q?dev-20220519-video=20video=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E9=87=8D=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.go | 3 ++ dao/videoDao.go | 13 +++++ dao/videoDao_test.go | 11 ++++ service/videoServiceImpl.go | 86 +++++++++++++++++++++++++++++--- service/videoServiceImpl_test.go | 27 ++++++++-- service/videoSub.go | 81 +++++++++++++++++++++++++++++- 6 files changed, 209 insertions(+), 12 deletions(-) diff --git a/config/config.go b/config/config.go index 4e214dc..7cfebb7 100644 --- a/config/config.go +++ b/config/config.go @@ -7,3 +7,6 @@ var Secret = "tiktok" var OneDayOfHours = 60 * 60 * 24 var OneMinute = 60 * 1 var OneMonth = 60 * 60 * 24 * 30 + +// VideoCount 每次获取视频流的数量 +const VideoCount = 10 diff --git a/dao/videoDao.go b/dao/videoDao.go index 5a04b48..04516dd 100644 --- a/dao/videoDao.go +++ b/dao/videoDao.go @@ -1,6 +1,7 @@ package dao import ( + "TikTok/config" "time" ) @@ -47,3 +48,15 @@ func GetVideoByVideoId(videoId int64) (TableVideo, error) { return tableVideo, nil } + +// GetVideosByLastTime +// 依据一个时间,来获取这个时间之前的一些视频 +func GetVideosByLastTime(lastTime time.Time) ([]TableVideo, error) { + videos := make([]TableVideo, config.VideoCount) + Init() + result := Db.Where("publish_time Date: Thu, 19 May 2022 04:47:44 +0800 Subject: [PATCH 39/70] =?UTF-8?q?dev-20220519-video=20nginx=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=99=A8=E9=85=8D=E7=BD=AE=E5=AE=8C=E6=88=90=EF=BC=8C?= =?UTF-8?q?ftp=E6=9C=8D=E5=8A=A1=E5=99=A8=E9=85=8D=E7=BD=AE=E5=AE=8C?= =?UTF-8?q?=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/nginx.conf | 89 +++++++++++++++++++++++++++++++ config/vsftpd.conf | 127 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 216 insertions(+) create mode 100644 config/nginx.conf create mode 100644 config/vsftpd.conf diff --git a/config/nginx.conf b/config/nginx.conf new file mode 100644 index 0000000..ba65162 --- /dev/null +++ b/config/nginx.conf @@ -0,0 +1,89 @@ +# 服务器nginx配置 +# 已经配置好图片服务器,视频服务器 +#user www www; +worker_processes auto; +#error_log /www/wwwlogs/nginx_error.log crit; +pid /www/server/nginx/logs/nginx.pid; +worker_rlimit_nofile 51200; + +events +{ + use epoll; + worker_connections 51200; + multi_accept on; +} + +http +{ + include mime.types; + #include luawaf.conf; + + #include proxy.conf; + + default_type application/octet-stream; + + #server_names_hash_bucket_size 512; + #client_header_buffer_size 32k; + #large_client_header_buffers 4 32k; + #client_max_body_size 50m; + + sendfile on; + tcp_nopush on; + + keepalive_timeout 60; + + tcp_nodelay on; + autoindex on; #开启nginx目录浏览功能 + autoindex_exact_size off; #文件大小从KB开始显示 + autoindex_localtime on; #显示文件修改时间为服务器本地时间 + + fastcgi_connect_timeout 300; + fastcgi_send_timeout 300; + fastcgi_read_timeout 300; + fastcgi_buffer_size 64k; + fastcgi_buffers 4 64k; + fastcgi_busy_buffers_size 128k; + fastcgi_temp_file_write_size 256k; + fastcgi_intercept_errors on; + gzip on; + gzip_min_length 1k; + gzip_buffers 4 16k; + gzip_http_version 1.1; + gzip_comp_level 2; + gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml; + gzip_vary on; + gzip_proxied expired no-cache no-store private auth; + gzip_disable "MSIE [1-6]\."; + + limit_conn_zone $binary_remote_addr zone=perip:10m; + limit_conn_zone $server_name zone=perserver:10m; + + server_tokens off; + access_log off; + +server + { + listen 80; + # server_name video; + index index.html; + root /home/ftpuser/video; + + error_page 404 /404.html; + #include enable-php.conf; + + location / { + root html; + index index.html index.htm; + } + #http://43.138.25.60/1.mp4 + location ~ .*\.mp4$ { + mp4; + } + #http://43.138.25.60/images/a.jpg + location /images{ + root /home/ftpuser; + } + access_log /www/wwwlogs/access.log; + } + # include /www/server/panel/vhost/nginx/*.conf; +} diff --git a/config/vsftpd.conf b/config/vsftpd.conf new file mode 100644 index 0000000..ae2c35c --- /dev/null +++ b/config/vsftpd.conf @@ -0,0 +1,127 @@ +# Example config file /etc/vsftpd/vsftpd.conf +# +# The default compiled in settings are fairly paranoid. This sample file +# loosens things up a bit, to make the ftp daemon more usable. +# Please see vsftpd.conf.5 for all compiled in defaults. +# +# READ THIS: This example file is NOT an exhaustive list of vsftpd options. +# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's +# capabilities. +# +# Allow anonymous FTP? (Beware - allowed by default if you comment this out). +anonymous_enable=NO +# +# Uncomment this to allow local users to log in. +# When SELinux is enforcing check for SE bool ftp_home_dir +local_enable=YES +# +# Uncomment this to enable any form of FTP write command. +write_enable=YES +# +# Default umask for local users is 077. You may wish to change this to 022, +# if your users expect that (022 is used by most other ftpd's) +local_umask=022 +# +# Uncomment this to allow the anonymous FTP user to upload files. This only +# has an effect if the above global write enable is activated. Also, you will +# obviously need to create a directory writable by the FTP user. +# When SELinux is enforcing check for SE bool allow_ftpd_anon_write, allow_ftpd_full_access +#anon_upload_enable=YES +# +# Uncomment this if you want the anonymous FTP user to be able to create +# new directories. +#anon_mkdir_write_enable=YES +# +# Activate directory messages - messages given to remote users when they +# go into a certain directory. +dirmessage_enable=YES +# +# Activate logging of uploads/downloads. +xferlog_enable=YES +# +# Make sure PORT transfer connections originate from port 20 (ftp-data). +connect_from_port_20=YES +# You may override where the log file goes if you like. The default is shown +# below. +#xferlog_file=/var/log/xferlog +# +# If you want, you can have your log file in standard ftpd xferlog format. +# Note that the default log file location is /var/log/xferlog in this case. +xferlog_std_format=YES +# +# You may change the default value for timing out an idle session. +#idle_session_timeout=600 +# +# You may change the default value for timing out a data connection. +#data_connection_timeout=120 +# +# It is recommended that you define on your system a unique user which the +# ftp server can use as a totally isolated and unprivileged user. +#nopriv_user=ftpsecure +# +# Enable this and the server will recognise asynchronous ABOR requests. Not +# recommended for security (the code is non-trivial). Not enabling it, +# however, may confuse older FTP clients. +#async_abor_enable=YES +# +# By default the server will pretend to allow ASCII mode but in fact ignore +# the request. Turn on the below options to have the server actually do ASCII +# mangling on files when in ASCII mode. The vsftpd.conf(5) man page explains +# the behaviour when these options are disabled. +# Beware that on some FTP servers, ASCII support allows a denial of service +# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd +# predicted this attack and has always been safe, reporting the size of the +# raw file. +# ASCII mangling is a horrible feature of the protocol. +#ascii_upload_enable=YES +#ascii_download_enable=YES +# +# You may fully customise the login banner string: +#ftpd_banner=Welcome to blah FTP service. +# +# You may specify a file of disallowed anonymous e-mail addresses. Apparently +# useful for combatting certain DoS attacks. +#deny_email_enable=YES +# (default follows) +#banned_email_file=/etc/vsftpd/banned_emails +# +# You may specify an explicit list of local users to chroot() to their home +# directory. If chroot_local_user is YES, then this list becomes a list of +# users to NOT chroot(). +# (Warning! chroot'ing can be very dangerous. If using chroot, make sure that +# the user does not have write access to the top level directory within the +# chroot) +#chroot_local_user=YES +#chroot_list_enable=YES +# (default follows) +#chroot_list_file=/etc/vsftpd/chroot_list +# +# You may activate the "-R" option to the builtin ls. This is disabled by +# default to avoid remote users being able to cause excessive I/O on large +# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume +# the presence of the "-R" option, so there is a strong case for enabling it. +#ls_recurse_enable=YES +# +# When "listen" directive is enabled, vsftpd runs in standalone mode and +# listens on IPv4 sockets. This directive cannot be used in conjunction +# with the listen_ipv6 directive. +listen=YES +# +# This directive enables listening on IPv6 sockets. By default, listening +# on the IPv6 "any" address (::) will accept connections from both IPv6 +# and IPv4 clients. It is not necessary to listen on *both* IPv4 and IPv6 +# sockets. If you want that (perhaps because you want to listen on specific +# addresses) then you must run two copies of vsftpd with two configuration +# files. +# Make sure, that one of the listen options is commented !! +listen_ipv6=NO + +pam_service_name=vsftpd +userlist_enable=YES +tcp_wrappers=YES +#仅允许user_list文件中的用户访问FTP服务 +userlist_deny=NO +#被动模式端口范围 +pasv_min_port=30000 +pasv_max_port=30999 + From c1276e1c464b2a74fd061b2d07a540c20f9cd10f Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Thu, 19 May 2022 05:32:14 +0800 Subject: [PATCH 40/70] =?UTF-8?q?dev-20220519-video=20=E6=9E=84=E5=BB=BA?= =?UTF-8?q?=E5=A5=BD=E4=B8=8A=E4=BC=A0FTP=E6=9C=8D=E5=8A=A1=E5=99=A8?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.go | 3 +++ dao/videoDao.go | 57 ++++++++++++++++++++++++++++++++++++++++++++ dao/videoDao_test.go | 11 +++++++++ go.mod | 1 + go.sum | 2 ++ 5 files changed, 74 insertions(+) diff --git a/config/config.go b/config/config.go index 7cfebb7..8e7cfe1 100644 --- a/config/config.go +++ b/config/config.go @@ -10,3 +10,6 @@ var OneMonth = 60 * 60 * 24 * 30 // VideoCount 每次获取视频流的数量 const VideoCount = 10 +const ConConfig = "43.138.25.60:21" +const FtpUser = "ftpuser" +const FtpPsw = "424193726" diff --git a/dao/videoDao.go b/dao/videoDao.go index 04516dd..b9d1d93 100644 --- a/dao/videoDao.go +++ b/dao/videoDao.go @@ -2,6 +2,8 @@ package dao import ( "TikTok/config" + "github.com/dutchcoders/goftp" + "os" "time" ) @@ -60,3 +62,58 @@ func GetVideosByLastTime(lastTime time.Time) ([]TableVideo, error) { } return videos, nil } + +// VideoFTP +// 通过ftp将视频传入服务器 +func VideoFTP(file *os.File, videoName string) error { + //初始化ftp + ftp, err := initFTP() + if err != nil { + return err + } + //转到video相对路线下 + err = ftp.Cwd("video") + if err != nil { + return err + } + if err := ftp.Stor(videoName+".mp4", file); err != nil { + return err + } + defer file.Close() + return nil +} + +//初始化FTP +func initFTP() (*goftp.FTP, error) { + //获取到ftp的链接 + connect, err := goftp.Connect(config.ConConfig) + if err != nil { + return nil, err + } + //登录 + err = connect.Login(config.FtpUser, config.FtpPsw) + if err != nil { + return nil, err + } + return connect, nil +} + +// ImageFTP +// 将图片传入FTP服务器中,但是这里要注意图片的格式随着名字一起给 +func ImageFTP(file *os.File, imageName string) error { + //初始化ftp + ftp, err := initFTP() + if err != nil { + return err + } + //转到video相对路线下 + err = ftp.Cwd("images") + if err != nil { + return err + } + if err := ftp.Stor(imageName, file); err != nil { + return err + } + defer file.Close() + return nil +} diff --git a/dao/videoDao_test.go b/dao/videoDao_test.go index 2a5b578..c5475a3 100644 --- a/dao/videoDao_test.go +++ b/dao/videoDao_test.go @@ -2,6 +2,7 @@ package dao import ( "fmt" + "os" "testing" "time" ) @@ -50,3 +51,13 @@ func TestGetVideosByLastTime(t *testing.T) { fmt.Println(video) } } +func TestVideoFtp(t *testing.T) { + _, err := os.Open("/Users/siyixiong/GolandProjects/tiktok/config/vsftpd.conf") + if err != nil { + panic(err) + } + //err = VideoFtp(file, "test") + if err != nil { + return + } +} diff --git a/go.mod b/go.mod index 8bc81a1..54f5b12 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.17 require ( github.com/dgrijalva/jwt-go v3.2.0+incompatible + github.com/dutchcoders/goftp v0.0.0-20170301105846-ed59a591ce14 github.com/gin-gonic/gin v1.7.7 github.com/jinzhu/copier v0.3.5 github.com/jinzhu/gorm v1.9.16 diff --git a/go.sum b/go.sum index 56cf513..4efc984 100644 --- a/go.sum +++ b/go.sum @@ -16,6 +16,8 @@ github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6RO github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dutchcoders/goftp v0.0.0-20170301105846-ed59a591ce14 h1:EqNCch0Y7FT4tawhoWu1vcaAvfPGm2hRCPHmtKdyZWI= +github.com/dutchcoders/goftp v0.0.0-20170301105846-ed59a591ce14/go.mod h1:0PBGc2Br4QviPu4/IVVcXmCaLcSHcXgzpVqm5JndaB8= github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= From 1bebef7498c96321d5b1b72d1882f3bd67e3d775 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Thu, 19 May 2022 21:31:34 +0800 Subject: [PATCH 41/70] =?UTF-8?q?dev-20220519-video=20=E6=9E=84=E5=BB=BA?= =?UTF-8?q?=E5=A5=BDpublish=E6=9C=8D=E5=8A=A1=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.go | 6 ++++++ dao/videoDao.go | 25 +++++++++++++++++++------ dao/videoDao_test.go | 33 ++++++++++++++++++++++++--------- go.mod | 2 ++ go.sum | 6 ++++++ service/videoServiceImpl.go | 36 +++++++++++++++++++++++++++++++++--- 6 files changed, 90 insertions(+), 18 deletions(-) diff --git a/config/config.go b/config/config.go index 8e7cfe1..c3ada54 100644 --- a/config/config.go +++ b/config/config.go @@ -10,6 +10,12 @@ var OneMonth = 60 * 60 * 24 * 30 // VideoCount 每次获取视频流的数量 const VideoCount = 10 + +// ConConfig ftp服务器地址 const ConConfig = "43.138.25.60:21" const FtpUser = "ftpuser" const FtpPsw = "424193726" + +// PlayUrlPrefix 存储的图片和视频的链接 +const PlayUrlPrefix = "http://43.138.25.60/" +const CoverUrlPrefix = "http://43.138.25.60/images/" diff --git a/dao/videoDao.go b/dao/videoDao.go index b9d1d93..1b64fed 100644 --- a/dao/videoDao.go +++ b/dao/videoDao.go @@ -3,7 +3,7 @@ package dao import ( "TikTok/config" "github.com/dutchcoders/goftp" - "os" + "io" "time" ) @@ -65,7 +65,7 @@ func GetVideosByLastTime(lastTime time.Time) ([]TableVideo, error) { // VideoFTP // 通过ftp将视频传入服务器 -func VideoFTP(file *os.File, videoName string) error { +func VideoFTP(file io.Reader, videoName string) error { //初始化ftp ftp, err := initFTP() if err != nil { @@ -79,7 +79,6 @@ func VideoFTP(file *os.File, videoName string) error { if err := ftp.Stor(videoName+".mp4", file); err != nil { return err } - defer file.Close() return nil } @@ -99,8 +98,8 @@ func initFTP() (*goftp.FTP, error) { } // ImageFTP -// 将图片传入FTP服务器中,但是这里要注意图片的格式随着名字一起给 -func ImageFTP(file *os.File, imageName string) error { +// 将图片传入FTP服务器中,但是这里要注意图片的格式随着名字一起给,同时调用时需要自己结束流 +func ImageFTP(file io.Reader, imageName string) error { //初始化ftp ftp, err := initFTP() if err != nil { @@ -114,6 +113,20 @@ func ImageFTP(file *os.File, imageName string) error { if err := ftp.Stor(imageName, file); err != nil { return err } - defer file.Close() + return nil +} + +// Save 保存视频记录 +func Save(videoName string, imageName string, authorId int64) error { + Init() + var video TableVideo + video.PublishTime = time.Now() + video.PlayUrl = config.PlayUrlPrefix + videoName + ".mp4" + video.CoverUrl = config.CoverUrlPrefix + imageName + video.AuthorId = authorId + result := Db.Save(&video) + if result.Error != nil { + return result.Error + } return nil } diff --git a/dao/videoDao_test.go b/dao/videoDao_test.go index c5475a3..a3be925 100644 --- a/dao/videoDao_test.go +++ b/dao/videoDao_test.go @@ -2,7 +2,6 @@ package dao import ( "fmt" - "os" "testing" "time" ) @@ -52,12 +51,28 @@ func TestGetVideosByLastTime(t *testing.T) { } } func TestVideoFtp(t *testing.T) { - _, err := os.Open("/Users/siyixiong/GolandProjects/tiktok/config/vsftpd.conf") - if err != nil { - panic(err) - } - //err = VideoFtp(file, "test") - if err != nil { - return - } + //file, err := os.Open("/Users/siyixiong/Movies/bilibil/bilibil20211219/樱花少女.mp4") + //if err != nil { + // panic(err) + //} + //err = VideoFTP(file, "k1") + //if err != nil { + // return + //} + //defer file.Close() + //ffmpeg.exe -ss 00:00:01 -i spring.mp4 -vframes 1 bb.jpg + //imageName := uuid.NewV4().String() + ".jpg" + //cmdArguments := []string{"-ss", "00:00:01", "-i", "/home/ftpuser/video/" + "1" + ".mp4", "-vframes", "1", "/home/ftpuser/images/" + imageName} + //cmd := exec.Command("ffmpeg", cmdArguments...) + //var out bytes.Buffer + //cmd.Stdout = &out + //err := cmd.Run() + //if err != nil { + // log.Fatal(err) + //} + //fmt.Printf("command output: %q", out.String()) +} + +func TestSave(t *testing.T) { + Save("test", "test", 10024) } diff --git a/go.mod b/go.mod index 54f5b12..fd5ac5b 100644 --- a/go.mod +++ b/go.mod @@ -8,12 +8,14 @@ require ( github.com/gin-gonic/gin v1.7.7 github.com/jinzhu/copier v0.3.5 github.com/jinzhu/gorm v1.9.16 + github.com/satori/go.uuid v1.2.0 github.com/swaggo/swag v1.8.1 ) require ( github.com/KyleBanks/depth v1.2.1 // indirect github.com/gin-contrib/sse v0.1.0 // indirect + github.com/giorgisio/goav v0.1.0 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect github.com/go-openapi/jsonreference v0.20.0 // indirect github.com/go-openapi/spec v0.20.6 // indirect diff --git a/go.sum b/go.sum index 4efc984..7e7a1e8 100644 --- a/go.sum +++ b/go.sum @@ -25,6 +25,8 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= +github.com/giorgisio/goav v0.1.0 h1:ZyfG3NfX7PMSimv4ulhmnQJf/XeHpMdGCn+afRmY5Oc= +github.com/giorgisio/goav v0.1.0/go.mod h1:RtH8HyxLRLU1iY0pjfhWBKRhnbsnmfoI+FxMwb5bfEo= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= @@ -61,6 +63,8 @@ github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gosuri/uilive v0.0.0-20170323041506-ac356e6e42cd/go.mod h1:qkLSc0A5EXSP6B04TrN4oQoxqFI7A8XvoXSlJi8cwk8= +github.com/gosuri/uiprogress v0.0.0-20170224063937-d0567a9d84a1/go.mod h1:C1RTYn4Sc7iEyf6j8ft5dyoZ4212h8G1ol9QQluh5+0= github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= @@ -118,6 +122,8 @@ github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTE github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go index 1c09c5a..b895eed 100644 --- a/service/videoServiceImpl.go +++ b/service/videoServiceImpl.go @@ -3,8 +3,13 @@ package service import ( "TikTok/config" "TikTok/dao" + "bytes" + "fmt" "github.com/jinzhu/copier" + "github.com/satori/go.uuid" + "log" "mime/multipart" + "os/exec" "time" ) @@ -74,9 +79,34 @@ func (videoService *VideoServiceImpl) GetVideo(videoId int64, userId int64) (Vid // Publish // 将传入的视频流保存在文件服务器中,并存储在mysql表中 func (videoService *VideoServiceImpl) Publish(data *multipart.FileHeader, userId int64) error { - //todo 从视频流中获取第一帧截图,并上传图片服务器,保存图片链接 - //todo 将视频流上传到视频服务器,保存视频链接 - //todo 组装并持久化 + //将视频流上传到视频服务器,保存视频链接 + file, err := data.Open() + if err != nil { + return err + } + //生成一个uuid作为视频的名字 + videoName := uuid.NewV4().String() + err = dao.VideoFTP(file, videoName) + if err != nil { + return err + } + defer file.Close() + //在服务器上执行ffmpeg 从视频流中获取第一帧截图,并上传图片服务器,保存图片链接 + imageName := uuid.NewV4().String() + ".jpg" + cmdArguments := []string{"-ss", "00:00:01", "-i", "/home/ftpuser/video/" + videoName + ".mp4", "-vframes", "1", "/home/ftpuser/images/" + imageName} + cmd := exec.Command("ffmpeg", cmdArguments...) + var out bytes.Buffer + cmd.Stdout = &out + err = cmd.Run() + if err != nil { + log.Fatal(err) + } + fmt.Printf("command output: %q", out.String()) + //组装并持久化 + err = dao.Save(videoName, imageName, userId) + if err != nil { + return err + } return nil } From 3d32d3e925037a198f2bd480fad479f6038a25ee Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Thu, 19 May 2022 23:40:20 +0800 Subject: [PATCH 42/70] =?UTF-8?q?dev-2022-5-19-follow=201-=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=90=AF=E5=8A=A8=E6=97=B6=EF=BC=8C=E5=86=85=E5=AD=98?= =?UTF-8?q?=E4=B8=AD=E5=88=9D=E5=A7=8B=E5=8C=96gorm.DB=E6=8C=87=E9=92=88?= =?UTF-8?q?=E5=8F=98=E9=87=8F=EF=BC=9B=202-=E8=A7=A3=E5=86=B3bug-routerGro?= =?UTF-8?q?upPath=E3=80=81bug-=E5=BE=AA=E7=8E=AF=E8=B0=83=E7=94=A8?= =?UTF-8?q?=E3=80=81bug-Users=E6=95=B0=E7=BB=84json=E5=8C=96=E3=80=81bug-?= =?UTF-8?q?=E6=8F=92=E5=85=A5=E5=85=B3=E7=B3=BB=E5=89=8Dcancel-01=E9=83=BD?= =?UTF-8?q?=E8=A6=81=E6=A3=80=E6=9F=A5=E3=80=81bug-create(&follow)?= =?UTF-8?q?=EF=BC=9B=203-=E5=AE=8C=E6=88=90=E5=85=B3=E6=B3=A8=E3=80=81?= =?UTF-8?q?=E5=8F=96=E6=B6=88=E5=85=B3=E6=B3=A8=E3=80=81=E7=B2=89=E4=B8=9D?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E3=80=81=E5=85=B3=E6=B3=A8=E5=88=97=E8=A1=A8?= =?UTF-8?q?=E7=9A=84=E5=85=A8=E9=83=A8=E6=B5=8B=E8=AF=95=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/followController.go | 36 +++++++++++++++++++--------------- dao/FollowDao.go | 8 ++++---- main.go | 4 ++++ router.go | 6 +++--- service/followServiceImpl.go | 29 +++++++++++++++++++++++++-- 5 files changed, 58 insertions(+), 25 deletions(-) diff --git a/controller/followController.go b/controller/followController.go index 2886bc3..7902fb5 100644 --- a/controller/followController.go +++ b/controller/followController.go @@ -2,6 +2,7 @@ package controller import ( "TikTok/service" + "fmt" "github.com/gin-gonic/gin" "net/http" "strconv" @@ -15,20 +16,22 @@ type RelationActionResp struct { // FollowingResp 获取关注列表需要返回的结构。 type FollowingResp struct { Response - users []service.User `json:"users"` + Users []service.User `json:"users,omitempty"` } // FollowersResp 获取粉丝列表需要返回的结构。 type FollowersResp struct { Response - users []service.User `json:"users"` + // 必须大写,才能序列化 + Users []service.User `json:"users,omitempty"` } // RelationAction 处理关注和取消关注请求。 func RelationAction(c *gin.Context) { - userId, err1 := strconv.ParseInt(c.GetString("user_id"), 10, 64) - toUserId, err2 := strconv.ParseInt(c.GetString("to_user_id"), 10, 64) - actionType, err3 := strconv.ParseInt(c.GetString("action_type"), 10, 64) + userId, err1 := strconv.ParseInt(c.Query("user_id"), 10, 64) + toUserId, err2 := strconv.ParseInt(c.Query("to_user_id"), 10, 64) + actionType, err3 := strconv.ParseInt(c.Query("action_type"), 10, 64) + fmt.Println(userId, toUserId, actionType) // 传入参数格式有问题。 if nil != err1 || nil != err2 || nil != err3 || actionType < 1 || actionType > 2 { c.JSON(http.StatusOK, RelationActionResp{ @@ -59,7 +62,7 @@ func RelationAction(c *gin.Context) { // GetFollowing 处理获取关注列表请求 func GetFollowing(c *gin.Context) { - userId, err := strconv.ParseInt(c.GetString("user_id"), 10, 64) + userId, err := strconv.ParseInt(c.Query("user_id"), 10, 64) // 用户id解析出错。 if nil != err { c.JSON(http.StatusOK, FollowingResp{ @@ -67,7 +70,7 @@ func GetFollowing(c *gin.Context) { StatusCode: -1, StatusMsg: "用户id格式错误。", }, - users: nil, + Users: nil, }) return } @@ -81,54 +84,55 @@ func GetFollowing(c *gin.Context) { StatusCode: -1, StatusMsg: "获取关注列表时出错。", }, - users: nil, + Users: nil, }) return } // 成功获取到关注列表。 c.JSON(http.StatusOK, FollowingResp{ + Users: users, Response: Response{ StatusCode: 0, StatusMsg: "OK", }, - users: users, }) } // GetFollowers 处理获取关注列表请求 func GetFollowers(c *gin.Context) { - userId, err := strconv.ParseInt(c.GetString("user_id"), 10, 64) + userId, err := strconv.ParseInt(c.Query("user_id"), 10, 64) // 用户id解析出错。 if nil != err { - c.JSON(http.StatusOK, FollowingResp{ + c.JSON(http.StatusOK, FollowersResp{ Response: Response{ StatusCode: -1, StatusMsg: "用户id格式错误。", }, - users: nil, + Users: nil, }) return } // 正常获取粉丝列表 fsi := service.NewFSIInstance() users, err := fsi.GetFollowers(userId) + fmt.Printf("%#v", users) // 获取关注列表时出错。 if err != nil { - c.JSON(http.StatusOK, FollowingResp{ + c.JSON(http.StatusOK, FollowersResp{ Response: Response{ StatusCode: -1, StatusMsg: "获取粉丝列表时出错。", }, - users: nil, + Users: nil, }) return } // 成功获取到粉丝列表。 - c.JSON(http.StatusOK, FollowingResp{ + c.JSON(http.StatusOK, FollowersResp{ Response: Response{ StatusCode: 0, StatusMsg: "OK", }, - users: users, + Users: users, }) } diff --git a/dao/FollowDao.go b/dao/FollowDao.go index 099d7d2..a9b7460 100644 --- a/dao/FollowDao.go +++ b/dao/FollowDao.go @@ -16,7 +16,7 @@ type Follow struct { // TableName 设置Follow结构体对应数据库表名。 func (Follow) TableName() string { - return "follow" + return "follows" } // FollowDao 把dao层看成整体,把dao的curd封装在一个结构体中。 @@ -104,7 +104,7 @@ func (*FollowDao) InsertFollowRelation(userId int64, targetId int64) (bool, erro Cancel: 1, } // 插入失败,返回err. - if err := Db.Create(follow).Error; nil != err { + if err := Db.Select("UserId", "FollowerId", "Cancel").Create(&follow).Error; nil != err { log.Println(err.Error()) return false, err } @@ -120,7 +120,7 @@ func (*FollowDao) FindEverFollowing(userId int64, targetId int64) (*Follow, erro if err := Db. Where("user_id = ?", userId). Where("follower_id = ?", targetId). - Where("cancel = ?", 0). + Where("cancel = ? or cancel = ?", 0, 1). Take(&follow).Error; nil != err { // 当没查到记录报错时,不当做错误处理。 if gorm.IsRecordNotFoundError(err) { @@ -139,7 +139,7 @@ func (*FollowDao) UpdateFollowRelation(userId int64, targetId int64, cancel int8 if err := Db.Model(Follow{}). Where("user_id = ?", userId). Where("follower_id = ?", targetId). - Update("cancel", 1).Error; nil != err { + Update("cancel", cancel).Error; nil != err { // 更新失败,打印错误日志。 log.Println(err.Error()) return false, err diff --git a/main.go b/main.go index 842ec0b..40acbe0 100644 --- a/main.go +++ b/main.go @@ -1,10 +1,14 @@ package main import ( + "TikTok/dao" "github.com/gin-gonic/gin" ) func main() { + // 初始化数据库 + dao.Init() + r := gin.Default() initRouter(r) diff --git a/router.go b/router.go index 86fe651..88f14a7 100644 --- a/router.go +++ b/router.go @@ -33,7 +33,7 @@ func initRouter(r *gin.Engine) { /* 关注模块 */ - apiRouter.POST("/douyin/relation/action/", middleware.Auth(), controller.RelationAction) - apiRouter.GET("/douyin/relation/follow/list/", middleware.Auth(), controller.GetFollowing) - apiRouter.GET("douyin/relation/follower/list", middleware.Auth(), controller.GetFollowers) + apiRouter.POST("/relation/action/", middleware.Auth(), controller.RelationAction) + apiRouter.GET("/relation/follow/list/", middleware.Auth(), controller.GetFollowing) + apiRouter.GET("/relation/follower/list", middleware.Auth(), controller.GetFollowers) } diff --git a/service/followServiceImpl.go b/service/followServiceImpl.go index 481dffe..6393e27 100644 --- a/service/followServiceImpl.go +++ b/service/followServiceImpl.go @@ -13,7 +13,7 @@ type FollowServiceImp struct { var ( followServiceImp *FollowServiceImp //controller层通过该实例变量调用service的所有业务方法。 - followServiceOnce *sync.Once //限定该service对象为单例,节约内存。 + followServiceOnce sync.Once //限定该service对象为单例,节约内存。 ) // NewFSIInstance 生成并返回FollowServiceImp结构体单例变量。 @@ -21,7 +21,10 @@ func NewFSIInstance() *FollowServiceImp { followServiceOnce.Do( func() { followServiceImp = &FollowServiceImp{ - UserService: &UserServiceImpl{}, + UserService: &UserServiceImpl{ + // 存在我调userService中,userService又要调我。 + FollowService: &FollowServiceImp{}, + }, } }) return followServiceImp @@ -40,6 +43,28 @@ func (*FollowServiceImp) IsFollowing(userId int64, targetId int64) (bool, error) return true, nil } +// GetFollowerCnt 给定当前用户id,查询其粉丝数量。 +func (*FollowServiceImp) GetFollowerCnt(userId int64) (int64, error) { + cnt, err := dao.NewFollowDaoInstance().GetFollowerCnt(userId) + + if nil != err { + return 0, err + } + + return cnt, err +} + +// GetFollowingCnt 给定当前用户id,查询其关注者数量。 +func (*FollowServiceImp) GetFollowingCnt(userId int64) (int64, error) { + cnt, err := dao.NewFollowDaoInstance().GetFollowingCnt(userId) + + if nil != err { + return 0, err + } + + return cnt, err +} + // AddFollowRelation 给定当前用户和目标对象id,添加他们之间的关注关系。 func (*FollowServiceImp) AddFollowRelation(userId int64, targetId int64) (bool, error) { followDao := dao.NewFollowDaoInstance() From b335ca3cd5ae71c3698b0af04d1b0d24e6fe3b9a Mon Sep 17 00:00:00 2001 From: siyuanli Date: Fri, 20 May 2022 08:51:00 +0800 Subject: [PATCH 43/70] =?UTF-8?q?dev-20220520-comment=20=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=B8=AD=E5=8F=91=E8=A1=A8=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E3=80=81=E5=88=A0=E9=99=A4=E8=AF=84=E8=AE=BA=E3=80=81=E6=9F=A5?= =?UTF-8?q?=E7=9C=8B=E8=AF=84=E8=AE=BA=E3=80=81=E8=AF=84=E8=AE=BA=E6=95=B0?= =?UTF-8?q?=E9=87=8F=E5=87=BD=E6=95=B0=E5=B7=B2=E5=AE=9E=E7=8E=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/commentConfit.go | 5 + controller/CommentController.go | 165 ++++++++++++++++++++++++++++++++ dao/CommentDao.go | 94 ++++++++++++++++-- router.go | 8 ++ service/commentService.go | 24 ++--- service/commentServiceImpl.go | 63 ++++++++---- service/videoSub.go | 2 +- 7 files changed, 319 insertions(+), 42 deletions(-) create mode 100644 config/commentConfit.go create mode 100644 controller/CommentController.go diff --git a/config/commentConfit.go b/config/commentConfit.go new file mode 100644 index 0000000..ea94f8f --- /dev/null +++ b/config/commentConfit.go @@ -0,0 +1,5 @@ +package config + +const ValidComment = 0 //评论状态:有效 +const InvalidComment = 1 //用户状态:取消 +const DateTime = "2006-01-02 15:04:05" diff --git a/controller/CommentController.go b/controller/CommentController.go new file mode 100644 index 0000000..afa7514 --- /dev/null +++ b/controller/CommentController.go @@ -0,0 +1,165 @@ +package controller + +import ( + "TikTok/dao" + "TikTok/service" + "github.com/gin-gonic/gin" + "log" + "net/http" + "strconv" +) + +type CommentListResponse struct { + StatusCode int32 `json:"status_code"` + StatusMsg string `json:"status_msg,omitempty"` + Comment_list []service.CommentInfo `json:"comment_list,omitempty"` +} + +//-发表 or 删除评论 comment/action/ +func Comment_Action(c *gin.Context) { + //获取userId + userId, err := strconv.ParseInt(c.Query("user_id"), 10, 64) + //错误处理 + if err != nil { + c.JSON(http.StatusOK, Response{ + StatusCode: -1, + StatusMsg: "comment userId json invalid", + }) + return + } + //获取videoId + videoId, err := strconv.ParseInt(c.Query("video_id"), 10, 64) + //错误处理 + if err != nil { + c.JSON(http.StatusOK, Response{ + StatusCode: -1, + StatusMsg: "comment videoId json invalid", + }) + return + } + //获取操作类型 + actionType, err := strconv.ParseInt(c.Query("action_type"), 10, 32) + //错误处理 + if err != nil || actionType < 1 || actionType > 2 { + c.JSON(http.StatusOK, Response{ + StatusCode: -1, + StatusMsg: "comment actionType json invalid", + }) + return + } + //调用service层评论函数 + commentService := new(service.CommentServiceImpl) + if actionType == 1 { //actionType为1,则进行发表评论操作 + content := c.Query("comment_text") + var sendComment dao.Comment + sendComment.User_id = userId + sendComment.Video_id = videoId + sendComment.Comment_text = content + //发表评论 + if commentService.Send(sendComment) != nil { //发表评论失败 + c.JSON(http.StatusOK, Response{ + StatusCode: -1, + StatusMsg: "send comment failed", + }) + return + } + + /*//测试count函数+++++++++++++++++++++: + count0, err := commentService.CountFromVideoId(videoId) + if err != nil { + c.JSON(http.StatusOK, Response{ + StatusCode: -1, + StatusMsg: "count comment failed", + }) + return + } + var str string + str = "send comment " + strconv.Itoa(int(count0)) + " success" + //+++++++++++++++++++++++++++++++++++++*/ + + //发表评论成功 + c.JSON(http.StatusOK, Response{ + StatusCode: 0, + StatusMsg: "send comment success", + }) + return + } else { //actionType为2,则进行删除评论操作 + //获取要删除的评论的id + commentId, err := strconv.ParseInt(c.Query("comment_id"), 10, 64) + if err != nil { + c.JSON(http.StatusOK, Response{ + StatusCode: -1, + StatusMsg: "delete commentId invalid", + }) + return + } + //删除评论操作 + err = commentService.DelComment(commentId) + if err != nil { //删除评论失败 + str := err.Error() + c.JSON(http.StatusOK, Response{ + StatusCode: -1, + StatusMsg: str, + }) + return + } + //删除评论成功 + c.JSON(http.StatusOK, Response{ + StatusCode: 0, + StatusMsg: "delete comment success", + }) + return + } +} + +//-查看评论列表 comment/list/ +func Comment_List(c *gin.Context) { + //获取userId + userId, err := strconv.ParseInt(c.Query("user_id"), 10, 64) + //错误处理 + if err != nil { + c.JSON(http.StatusOK, Response{ + StatusCode: -1, + StatusMsg: "comment userId json invalid", + }) + return + } + //获取videoId + videoId, err := strconv.ParseInt(c.Query("video_id"), 10, 64) + //错误处理 + if err != nil { + c.JSON(http.StatusOK, Response{ + StatusCode: -1, + StatusMsg: "comment videoId json invalid", + }) + return + } + log.Println(videoId) + log.Println(userId) + //调用service层评论函数 + commentService := new(service.CommentServiceImpl) + commentList, err := commentService.GetList(videoId, userId) + if err != nil { //获取评论列表失败 + log.Println(err.Error()) + c.JSON(http.StatusOK, CommentListResponse{ + StatusCode: -1, + StatusMsg: "get comment list failed", + }) + return + } + + //测试获取了几条数据: + //count := len(commentList) + //var str string + //str = "get comment list" + strconv.Itoa(count) + " success" + //log.Println(str) + + //获取评论列表成功 + c.JSON(http.StatusOK, CommentListResponse{ + StatusCode: 0, + StatusMsg: "get comment list success", + Comment_list: commentList, + }) + //log.Println(str) + return +} diff --git a/dao/CommentDao.go b/dao/CommentDao.go index e92e4d9..a8f8971 100644 --- a/dao/CommentDao.go +++ b/dao/CommentDao.go @@ -1,11 +1,93 @@ package dao +import ( + "TikTok/config" + "errors" + "github.com/jinzhu/gorm" + "log" + "sync" +) + //评论信息-数据库中的结构体-dao层使用 type Comment struct { - Id int64 //评论id - User_id int64 //评论用户id - Video_id int64 //视频id - Content string //评论内容 - Create_date string //评论发布的日期mm-dd - Cancel int32 //取消评论为1,发布评论为0 + Id int64 //评论id + User_id int64 //评论用户id + Video_id int64 //视频id + Comment_text string //评论内容 + Create_date string //评论发布的日期mm-dd + Cancel int32 //取消评论为1,发布评论为0 +} + +// TableName 修改表名映射 +func (Comment) TableName() string { + return "comments" +} + +type CommentDao struct { +} + +var ( + commentDao *CommentDao + commentOnce sync.Once +) + +func NewCommentDaoInstance() *CommentDao { + commentOnce.Do( + func() { + commentDao = &CommentDao{} + }) + return commentDao +} + +//1、使用video id 查询Comment数量 +func (*CommentDao) Count(video_id int64) (int64, error) { + Init() + var count int64 + err := Db.Model(Comment{}).Where(map[string]interface{}{"video_id": video_id, "cancel": config.ValidComment}).Count(&count).Error + if err != nil { + return -1, errors.New("find commentsCount failed") + } + return count, nil +} + +//2、发表评论 +func (*CommentDao) InsertComment(comment Comment) error { + Init() + err := Db.Model(Comment{}).Create(&comment).Error + if err != nil { + return errors.New("create comment failed") + } + return nil +} + +//3、删除评论,传入评论id +func (*CommentDao) DeleteComment(id int64) error { + Init() + var commentInfo Comment + //先查询是否有此评论(正常肯定是有的吧) + result := Db.Model(Comment{}).Where(map[string]interface{}{"id": id, "cancel": config.ValidComment}).First(&commentInfo) + if errors.Is(result.Error, gorm.ErrRecordNotFound) { + return errors.New("del comment is not exist") + } + err := Db.Model(Comment{}).Where("id = ?", id).Update("cancel", config.InvalidComment).Error + if err != nil { + return errors.New("del Comment failed") + } + return nil +} + +//4.根据视频id查询所属评论全部列表信息 +func (*CommentDao) GetCommentList(videoId int64) ([]Comment, error) { + Init() + var commentList []Comment + result := Db.Model(Comment{}).Where(map[string]interface{}{"video_id": videoId, "cancel": config.ValidComment}).Find(&commentList) + if errors.Is(result.Error, gorm.ErrRecordNotFound) { + log.Println(result.Error.Error()) + return commentList, errors.New("there are no comments") + } + if result.Error != nil { + log.Println(result.Error.Error()) + return commentList, errors.New("get commentList failed") + } + return commentList, nil } diff --git a/router.go b/router.go index 88f14a7..29f042b 100644 --- a/router.go +++ b/router.go @@ -36,4 +36,12 @@ func initRouter(r *gin.Engine) { apiRouter.POST("/relation/action/", middleware.Auth(), controller.RelationAction) apiRouter.GET("/relation/follow/list/", middleware.Auth(), controller.GetFollowing) apiRouter.GET("/relation/follower/list", middleware.Auth(), controller.GetFollowers) + + /* + 评论模块 + */ + //发表评论 + apiRouter.POST("/douyin/comment/action/", middleware.Auth(), controller.Comment_Action) + //查看评论列表 + apiRouter.GET("/douyin/comment/list/", middleware.Auth(), controller.Comment_List) } diff --git a/service/commentService.go b/service/commentService.go index f44c88f..f4cf2c9 100644 --- a/service/commentService.go +++ b/service/commentService.go @@ -1,5 +1,9 @@ package service +import ( + "TikTok/dao" +) + //发表评论-使用的结构体-service层引用dao层↑的Comment。 //接口定义(CommentService.go) type CommentService interface { @@ -13,7 +17,7 @@ type CommentService interface { 二、评论模块自己request实现的方法: */ //2、发表评论,传进来评论的基本信息,返回保存是否成功的状态描述 - Send(comment *Comment) error + Send(comment dao.Comment) error //3、删除评论,传入评论id即可,返回错误状态信息 DelComment(id int64) error //4、查看评论列表-返回评论list-在controller层再封装外层的状态信息 @@ -22,18 +26,8 @@ type CommentService interface { //查看评论-传出的结构体-service type CommentInfo struct { - Id int64 //评论id - UserInfo User //评论用户的信息-由用户模块赞助 - Content string //评论内容 - Create_date string //评论发布的日期mm-dd -} - -//评论信息-数据库中的结构体-dao层使用-先放这,import不了 -type Comment struct { - Id int64 //评论id - User_id int64 //评论用户id - Video_id int64 //视频id - Content string //评论内容 - Create_date string //评论发布的日期mm-dd - Cancel int32 //取消评论为1,发布评论为0 + Id int64 `json:"id,omitempty"` + UserInfo User + Content string `json:"content,omitempty"` + Create_date string `json:"create_date,omitempty"` } diff --git a/service/commentServiceImpl.go b/service/commentServiceImpl.go index f0b157a..facd66a 100644 --- a/service/commentServiceImpl.go +++ b/service/commentServiceImpl.go @@ -1,43 +1,66 @@ package service import ( + "TikTok/config" "TikTok/dao" - "errors" + "log" + "time" ) type CommentServiceImpl struct { + UserService } //1、使用video id 查询Comment数量 func (c CommentServiceImpl) CountFromVideoId(id int64) (int64, error) { - var count int64 - if err := dao.Db.Table("comments").Where("id = ?", id).First(&count); err != nil { - return -1, errors.New("can't find commentsCount") - } - return count, nil + return dao.NewCommentDaoInstance().Count(id) } //2、发表评论 -func (c CommentServiceImpl) Send(comment *Comment) error { - if comment.Id == 0 { - return errors.New("Comment id = 0") - } - return nil +func (c CommentServiceImpl) Send(comment dao.Comment) error { + //数据准备 + var commentInfo dao.Comment + commentInfo.Video_id = comment.Video_id //评论视频id传入 + commentInfo.User_id = comment.User_id //评论用户id传入 + commentInfo.Comment_text = comment.Comment_text //评论内容传入 + commentInfo.Cancel = config.ValidComment //评论状态,0,有效 + nowTime := time.Now().Format(config.DateTime) + commentInfo.Create_date = nowTime //评论时间记录 + + return dao.NewCommentDaoInstance().InsertComment(commentInfo) } //3、删除评论,传入评论id func (c CommentServiceImpl) DelComment(id int64) error { - if id == 0 { - return errors.New("Comment id = 0") - } - return nil + return dao.NewCommentDaoInstance().DeleteComment(id) } //4、查看评论列表-返回评论list -func (c CommentServiceImpl) GetList(vedioId int64, userId int64) ([]CommentInfo, error) { - //comment := new(dao.Comment) - if vedioId == 0 || userId == 0 { - return nil, errors.New("id = 0") +func (c CommentServiceImpl) GetList(videoId int64, userId int64) ([]CommentInfo, error) { + //1.先查询评论列表信息 + commentList, err := dao.NewCommentDaoInstance().GetCommentList(videoId) + if err != nil { + log.Println(err.Error()) + return nil, err + } + //提前定义好切片长度 + commentInfoList := make([]CommentInfo, 0, len(commentList)) + for _, comment := range commentList { + var commentInfo CommentInfo + commentInfo.Id = comment.Id + commentInfo.Content = comment.Comment_text + commentInfo.Create_date = comment.Create_date + //TODO:返回的评论中添加用户信息 + //2.根据查询到的评论用户id和当前用户id,查询评论用户信息 + /*commentInfo.UserInfo, err = c.GetUserByIdWithCurId(comment.User_id, userId) + log.Println(len(commentList)) + log.Println(comment.User_id) + if err != nil { + return nil, err + }*/ + //3.组装list + log.Println(userId) + commentInfoList = append(commentInfoList, commentInfo) } - return nil, nil + return commentInfoList, nil } diff --git a/service/videoSub.go b/service/videoSub.go index 248609e..7d57166 100644 --- a/service/videoSub.go +++ b/service/videoSub.go @@ -11,7 +11,7 @@ func (vs VideoSub) CountFromVideoId(id int64) (int64, error) { return 4, nil } -func (vs VideoSub) Send(comment *Comment) error { +func (vs VideoSub) Send(comment *dao.Comment) error { //TODO implement me panic("implement me") } From 4ae96d086f040b2e6a0380874448cc9c1de7a1d6 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Fri, 20 May 2022 10:34:15 +0800 Subject: [PATCH 44/70] =?UTF-8?q?dev-20220520-user=20=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E4=BB=A3=E7=A0=81(=E4=BF=AE=E6=94=B9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/userController.go | 4 +++- dao/UserDao.go | 7 +++++-- service/userService.go | 11 ++--------- service/userServiceImpl.go | 21 ++++++++++++++++++--- service/userServiceImpl_test.go | 10 +++++++--- 5 files changed, 35 insertions(+), 18 deletions(-) diff --git a/controller/userController.go b/controller/userController.go index 6e3c07c..616c90c 100644 --- a/controller/userController.go +++ b/controller/userController.go @@ -83,7 +83,9 @@ func UserInfo(c *gin.Context) { user_id := c.Query("user_id") id, _ := strconv.ParseInt(user_id, 10, 64) - usi := service.UserServiceImpl{} + usi := service.UserServiceImpl{ + FollowService: &service.FollowServiceImp{}, + } if u, err := usi.GetUserById(id); err != nil { c.JSON(http.StatusOK, UserResponse{ diff --git a/dao/UserDao.go b/dao/UserDao.go index ba0ccde..4b53237 100644 --- a/dao/UserDao.go +++ b/dao/UserDao.go @@ -17,14 +17,16 @@ func (tableUser TableUser) TableName() string { return "users" } +// UserDao 把user的dao封装在内 type UserDao struct { } var ( - userDao *UserDao - userOnce sync.Once + userDao *UserDao //操作userDao来进行crud + userOnce sync.Once //单例模式 ) +// NewUserDaoInstance 生成并返回userDao的单例对象 func NewUserDaoInstance() *UserDao { userOnce.Do( func() { @@ -33,6 +35,7 @@ func NewUserDaoInstance() *UserDao { return userDao } +// GetTableUserList 获取全部TableUser对象 func (*UserDao) GetTableUserList() ([]TableUser, error) { tableUsers := []TableUser{} Init() diff --git a/service/userService.go b/service/userService.go index 5d66e24..0cf2b7f 100644 --- a/service/userService.go +++ b/service/userService.go @@ -35,14 +35,7 @@ type UserService interface { type User struct { Id int64 `json:"id,omitempty"` Name string `json:"name,omitempty"` - FollowCount int64 `json:"follow_count,omitempty"` - FollowerCount int64 `json:"follower_count,omitempty"` + FollowCount int64 `json:"follow_count"` + FollowerCount int64 `json:"follower_count"` IsFollow bool `json:"is_follow,omitempty"` } - -// TableUser users表对应的结构体 -//type TableUser struct { -// Id int64 -// Name string -// Password string -//} diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index 54cbbaf..f0bf796 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -78,7 +78,13 @@ func (usi *UserServiceImpl) GetUserById(id int64) (User, error) { } log.Println("Query User Success") followCount, _ := usi.GetFollowingCnt(id) + if err != nil { + log.Println("Err:", err.Error()) + } followerCount, _ := usi.GetFollowerCnt(id) + if err != nil { + log.Println("Err:", err.Error()) + } user = User{ Id: id, Name: tableUser.Name, @@ -105,9 +111,18 @@ func (usi *UserServiceImpl) GetUserByIdWithCurId(id int64, curId int64) (User, e return user, err } log.Println("Query User Success") - followCount, _ := usi.GetFollowingCnt(id) - followerCount, _ := usi.GetFollowerCnt(id) - isfollow, _ := usi.IsFollowing(curId, id) + followCount, err := usi.GetFollowingCnt(id) + if err != nil { + log.Println("Err:", err.Error()) + } + followerCount, err := usi.GetFollowerCnt(id) + if err != nil { + log.Println("Err:", err.Error()) + } + isfollow, err := usi.IsFollowing(curId, id) + if err != nil { + log.Println("Err:", err.Error()) + } user = User{ Id: id, Name: tableUser.Name, diff --git a/service/userServiceImpl_test.go b/service/userServiceImpl_test.go index 80b6df2..2536da8 100644 --- a/service/userServiceImpl_test.go +++ b/service/userServiceImpl_test.go @@ -36,13 +36,17 @@ func TestInsertTableUser(t *testing.T) { } func TestGetUserById(t *testing.T) { - impl := UserServiceImpl{} + impl := UserServiceImpl{ + FollowService: &FollowServiceImp{}, + } list, _ := impl.GetUserById(int64(4)) fmt.Printf("%v", list) } func TestGetUserByIdWithCurId(t *testing.T) { - impl := UserServiceImpl{} - list, _ := impl.GetUserByIdWithCurId(int64(4), int64(5)) + impl := UserServiceImpl{ + FollowService: &FollowServiceImp{}, + } + list, _ := impl.GetUserByIdWithCurId(int64(482), int64(130)) fmt.Printf("%v", list) } From 17b1fe22533d521f59be4ec96e9cdfcb6d1bee7e Mon Sep 17 00:00:00 2001 From: siyuanli Date: Fri, 20 May 2022 11:58:03 +0800 Subject: [PATCH 45/70] =?UTF-8?q?dev-20220520-comment=20=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=B8=AD=E6=9F=A5=E7=9C=8B=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E6=9B=B4=E6=96=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/commentServiceImpl.go | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/service/commentServiceImpl.go b/service/commentServiceImpl.go index facd66a..e8abee6 100644 --- a/service/commentServiceImpl.go +++ b/service/commentServiceImpl.go @@ -50,16 +50,15 @@ func (c CommentServiceImpl) GetList(videoId int64, userId int64) ([]CommentInfo, commentInfo.Id = comment.Id commentInfo.Content = comment.Comment_text commentInfo.Create_date = comment.Create_date - //TODO:返回的评论中添加用户信息 //2.根据查询到的评论用户id和当前用户id,查询评论用户信息 - /*commentInfo.UserInfo, err = c.GetUserByIdWithCurId(comment.User_id, userId) - log.Println(len(commentList)) - log.Println(comment.User_id) + impl := UserServiceImpl{ + FollowService: &FollowServiceImp{}, + } + commentInfo.UserInfo, err = impl.GetUserByIdWithCurId(comment.User_id, userId) if err != nil { return nil, err - }*/ + } //3.组装list - log.Println(userId) commentInfoList = append(commentInfoList, commentInfo) } return commentInfoList, nil From 25cafad9bc02dc570e0e826365edea79c5a74718 Mon Sep 17 00:00:00 2001 From: siyuanli Date: Fri, 20 May 2022 12:41:01 +0800 Subject: [PATCH 46/70] =?UTF-8?q?dev-20220520-comment=20=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E4=B8=AD=E6=9F=A5=E7=9C=8B=E8=AF=84=E8=AE=BA?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E6=9B=B4=E6=96=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/commentService.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/service/commentService.go b/service/commentService.go index f4cf2c9..f5d744d 100644 --- a/service/commentService.go +++ b/service/commentService.go @@ -26,8 +26,8 @@ type CommentService interface { //查看评论-传出的结构体-service type CommentInfo struct { - Id int64 `json:"id,omitempty"` - UserInfo User + Id int64 `json:"id,omitempty"` + UserInfo User `json:"user,omitempty"` Content string `json:"content,omitempty"` Create_date string `json:"create_date,omitempty"` } From 5e3d401c2050843a5ec374ff466e90f9ad8384b6 Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Fri, 20 May 2022 12:45:28 +0800 Subject: [PATCH 47/70] =?UTF-8?q?dev-2022-5-20-follow=201-=E5=85=B3?= =?UTF-8?q?=E7=B3=BB=E6=98=AF=E5=90=A6=E5=AD=98=E5=9C=A8cancel=E5=8F=98?= =?UTF-8?q?=E5=8C=96=EF=BC=9B=202-=E4=B8=80=E6=9D=A1SQL=E6=9B=BF=E4=BB=A3f?= =?UTF-8?q?or=E5=BE=AA=E7=8E=AF=E8=8E=B7=E5=8F=96=E5=85=B3=E6=B3=A8?= =?UTF-8?q?=E3=80=81=E7=B2=89=E4=B8=9D=E5=88=97=E8=A1=A8=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/followController.go | 1 - dao/FollowDao.go | 9 +++--- service/followServiceImpl.go | 50 ++++++++++++++++++++++++++++++---- 3 files changed, 50 insertions(+), 10 deletions(-) diff --git a/controller/followController.go b/controller/followController.go index 7902fb5..d960e89 100644 --- a/controller/followController.go +++ b/controller/followController.go @@ -115,7 +115,6 @@ func GetFollowers(c *gin.Context) { // 正常获取粉丝列表 fsi := service.NewFSIInstance() users, err := fsi.GetFollowers(userId) - fmt.Printf("%#v", users) // 获取关注列表时出错。 if err != nil { c.JSON(http.StatusOK, FollowersResp{ diff --git a/dao/FollowDao.go b/dao/FollowDao.go index a9b7460..4ce2424 100644 --- a/dao/FollowDao.go +++ b/dao/FollowDao.go @@ -49,7 +49,7 @@ func (*FollowDao) FindRelation(userId int64, targetId int64) (*Follow, error) { if err := Db. Where("user_id = ?", userId). Where("follower_id = ?", targetId). - Where("cancel = ?", 1). + Where("cancel = ?", 0). Take(&follow).Error; nil != err { // 当没查到数据时,gorm也会报错。 if gorm.IsRecordNotFoundError(err) { @@ -70,7 +70,7 @@ func (*FollowDao) GetFollowerCnt(userId int64) (int64, error) { if err := Db. Model(Follow{}). Where("user_id = ?", userId). - Where("cancel = ?", 1). + Where("cancel = ?", 0). Count(&cnt).Error; nil != err { log.Println(err.Error()) return 0, err @@ -86,7 +86,7 @@ func (*FollowDao) GetFollowingCnt(userId int64) (int64, error) { // 查询出错,日志打印err msg,并return err if err := Db.Model(Follow{}). Where("follower_id = ?", userId). - Where("cancel = ?", 1). + Where("cancel = ?", 0). Count(&cnt).Error; nil != err { log.Println(err.Error()) return 0, err @@ -101,7 +101,7 @@ func (*FollowDao) InsertFollowRelation(userId int64, targetId int64) (bool, erro follow := Follow{ UserId: userId, FollowerId: targetId, - Cancel: 1, + Cancel: 0, } // 插入失败,返回err. if err := Db.Select("UserId", "FollowerId", "Cancel").Create(&follow).Error; nil != err { @@ -173,6 +173,7 @@ func (*FollowDao) GetFollowersIds(userId int64) ([]int64, error) { if err := Db. Model(Follow{}). Where("user_id = ?", userId). + Where("cancel = ?", 0). Pluck("follower_id", &ids).Error; nil != err { // 没有粉丝,但是不能算错。 if gorm.IsRecordNotFoundError(err) { diff --git a/service/followServiceImpl.go b/service/followServiceImpl.go index 6393e27..3665b6c 100644 --- a/service/followServiceImpl.go +++ b/service/followServiceImpl.go @@ -50,7 +50,6 @@ func (*FollowServiceImp) GetFollowerCnt(userId int64) (int64, error) { if nil != err { return 0, err } - return cnt, err } @@ -75,7 +74,7 @@ func (*FollowServiceImp) AddFollowRelation(userId int64, targetId int64) (bool, } // 曾经关注过,只需要update一下cancel即可。 if nil != follow { - _, err := followDao.UpdateFollowRelation(userId, targetId, 1) + _, err := followDao.UpdateFollowRelation(userId, targetId, 0) // update 出错。 if nil != err { return false, err @@ -103,7 +102,7 @@ func (*FollowServiceImp) DeleteFollowRelation(userId int64, targetId int64) (boo } // 曾经关注过,只需要update一下cancel即可。 if nil != follow { - _, err := followDao.UpdateFollowRelation(userId, targetId, 0) + _, err := followDao.UpdateFollowRelation(userId, targetId, 1) // update 出错。 if nil != err { return false, err @@ -116,7 +115,7 @@ func (*FollowServiceImp) DeleteFollowRelation(userId int64, targetId int64) (boo } // GetFollowing 根据当前用户id来查询他的关注者列表。 -func (f *FollowServiceImp) GetFollowing(userId int64) ([]User, error) { +/*func (f *FollowServiceImp) GetFollowing(userId int64) ([]User, error) { // 获取关注对象的id数组。 ids, err := dao.NewFollowDaoInstance().GetFollowingIds(userId) // 查询出错 @@ -141,10 +140,28 @@ func (f *FollowServiceImp) GetFollowing(userId int64) ([]User, error) { } // 返回关注对象列表。 return users, nil +}*/ +// GetFollowing 根据当前用户id来查询他的关注者列表。 +func (f *FollowServiceImp) GetFollowing(userId int64) ([]User, error) { + users := make([]User, 1) + dao.Db.Raw("select id,`name`,"+ + "\ncount(if(tag = 'follower' and cancel is not null,1,null)) follower_count,"+ + "\ncount(if(tag = 'follow' and cancel is not null,1,null)) follow_count,"+ + "\n'true' isFollow\nfrom\n("+ + "\n\tselect f1.follower_id fid,u.id,`name`,f2.cancel,'follower' tag"+ + "\n\tfrom follows f1 join users u on f1.user_id = u.id and f1.cancel = 0"+ + "\n\tleft join follows f2 on u.id = f2.user_id and f2.cancel = 0\n\tunion all"+ + "\n\tselect f1.follower_id fid,u.id,`name`,f2.cancel,'follow' tag"+ + "\n\tfrom follows f1 join users u on f1.user_id = u.id and f1.cancel = 0"+ + "\n\tleft join follows f2 on u.id = f2.follower_id and f2.cancel = 0\n) T"+ + "\nwhere fid = ? group by fid,id,`name`", userId).Scan(&users) + // 返回关注对象列表。 + return users, nil } // GetFollowers 根据当前用户id来查询他的粉丝列表。 -func (f *FollowServiceImp) GetFollowers(userId int64) ([]User, error) { + +/*func (f *FollowServiceImp) GetFollowers(userId int64) ([]User, error) { // 获取粉丝的id数组。 ids, err := dao.NewFollowDaoInstance().GetFollowersIds(userId) // 查询出错 @@ -169,4 +186,27 @@ func (f *FollowServiceImp) GetFollowers(userId int64) ([]User, error) { } // 返回粉丝列表。 return users, nil +}*/ + +// GetFollowers 根据当前用户id来查询他的粉丝列表。 +func (f *FollowServiceImp) GetFollowers(userId int64) ([]User, error) { + users := make([]User, 1) + dao.Db.Raw("select T.id,T.name,T.follow_cnt follow_count,T.follower_cnt follower_count,if(f.cancel is null,'false','true') is_follow"+ + "\nfrom follows f right join"+ + "\n(\n\tselect fid,id,`name`,"+ + "\n\tcount(if(tag = 'follower' and cancel is not null,1,null)) follower_cnt,"+ + "\n\tcount(if(tag = 'follow' and cancel is not null,1,null)) follow_cnt"+ + "\n\tfrom\n\t\t("+ + "\n\t\tselect f1.user_id fid,u.id,`name`,f2.cancel,'follower' tag"+ + "\n\t\tfrom follows f1 join users u on f1.follower_id = u.id and f1.cancel = 0"+ + "\n\t\tleft join follows f2 on u.id = f2.user_id and f2.cancel = 0"+ + "\n\t\tunion all"+ + "\n\t\tselect f1.user_id fid,u.id,`name`,f2.cancel,'follow' tag"+ + "\n\t\tfrom follows f1 join users u on f1.follower_id = u.id and f1.cancel = 0"+ + "\n\t\tleft join follows f2 on u.id = f2.follower_id and f2.cancel = 0"+ + "\n\t\t) T\n\t\tgroup by fid,id,`name`"+ + "\n) T on f.user_id = T.fid and f.follower_id = T.id and f.cancel = 0 where fid = ?", userId). + Scan(&users) + + return users, nil } From b0ed7d0fce1b5d04e3dea2e39026823ad13b797e Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Fri, 20 May 2022 22:33:42 +0800 Subject: [PATCH 48/70] =?UTF-8?q?dev-2022-5-20-follow=201-=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=9B=9E=E4=BC=A0=E7=9A=84json=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E5=90=8D=E5=AF=B9=E5=BA=94=E5=89=8D=E7=AB=AF=E9=9C=80=E8=A6=81?= =?UTF-8?q?=E7=9A=84=E5=91=BD=E5=90=8D=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/followController.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/controller/followController.go b/controller/followController.go index d960e89..ea959ab 100644 --- a/controller/followController.go +++ b/controller/followController.go @@ -16,14 +16,14 @@ type RelationActionResp struct { // FollowingResp 获取关注列表需要返回的结构。 type FollowingResp struct { Response - Users []service.User `json:"users,omitempty"` + UserList []service.User `json:"user_list,omitempty"` } // FollowersResp 获取粉丝列表需要返回的结构。 type FollowersResp struct { Response // 必须大写,才能序列化 - Users []service.User `json:"users,omitempty"` + UserList []service.User `json:"user_list,omitempty"` } // RelationAction 处理关注和取消关注请求。 @@ -70,7 +70,7 @@ func GetFollowing(c *gin.Context) { StatusCode: -1, StatusMsg: "用户id格式错误。", }, - Users: nil, + UserList: nil, }) return } @@ -84,13 +84,13 @@ func GetFollowing(c *gin.Context) { StatusCode: -1, StatusMsg: "获取关注列表时出错。", }, - Users: nil, + UserList: nil, }) return } // 成功获取到关注列表。 c.JSON(http.StatusOK, FollowingResp{ - Users: users, + UserList: users, Response: Response{ StatusCode: 0, StatusMsg: "OK", @@ -108,7 +108,7 @@ func GetFollowers(c *gin.Context) { StatusCode: -1, StatusMsg: "用户id格式错误。", }, - Users: nil, + UserList: nil, }) return } @@ -122,7 +122,7 @@ func GetFollowers(c *gin.Context) { StatusCode: -1, StatusMsg: "获取粉丝列表时出错。", }, - Users: nil, + UserList: nil, }) return } @@ -132,6 +132,6 @@ func GetFollowers(c *gin.Context) { StatusCode: 0, StatusMsg: "OK", }, - Users: users, + UserList: users, }) } From 132d2e523c0f011fa2fa6eaf10af2363693c498c Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Fri, 20 May 2022 23:05:20 +0800 Subject: [PATCH 49/70] =?UTF-8?q?dev-2022-5-20-follow=201-=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=9B=9E=E4=BC=A0=E7=9A=84json=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E5=90=8D=E5=AF=B9=E5=BA=94=E5=89=8D=E7=AB=AF=E9=9C=80=E8=A6=81?= =?UTF-8?q?=E7=9A=84=E5=91=BD=E5=90=8D=E3=80=82=202-test=E7=9A=84=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E8=B0=83=E7=94=A8bug=5Ffree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/followServiceImpl.go | 17 ++++++++++++----- service/followServiceImpl_test.go | 2 +- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/service/followServiceImpl.go b/service/followServiceImpl.go index 3665b6c..4f0f307 100644 --- a/service/followServiceImpl.go +++ b/service/followServiceImpl.go @@ -144,7 +144,8 @@ func (*FollowServiceImp) DeleteFollowRelation(userId int64, targetId int64) (boo // GetFollowing 根据当前用户id来查询他的关注者列表。 func (f *FollowServiceImp) GetFollowing(userId int64) ([]User, error) { users := make([]User, 1) - dao.Db.Raw("select id,`name`,"+ + // 查询出错。 + if err := dao.Db.Raw("select id,`name`,"+ "\ncount(if(tag = 'follower' and cancel is not null,1,null)) follower_count,"+ "\ncount(if(tag = 'follow' and cancel is not null,1,null)) follow_count,"+ "\n'true' isFollow\nfrom\n("+ @@ -154,7 +155,9 @@ func (f *FollowServiceImp) GetFollowing(userId int64) ([]User, error) { "\n\tselect f1.follower_id fid,u.id,`name`,f2.cancel,'follow' tag"+ "\n\tfrom follows f1 join users u on f1.user_id = u.id and f1.cancel = 0"+ "\n\tleft join follows f2 on u.id = f2.follower_id and f2.cancel = 0\n) T"+ - "\nwhere fid = ? group by fid,id,`name`", userId).Scan(&users) + "\nwhere fid = ? group by fid,id,`name`", userId).Scan(&users).Error; nil != err { + return nil, err + } // 返回关注对象列表。 return users, nil } @@ -191,7 +194,8 @@ func (f *FollowServiceImp) GetFollowing(userId int64) ([]User, error) { // GetFollowers 根据当前用户id来查询他的粉丝列表。 func (f *FollowServiceImp) GetFollowers(userId int64) ([]User, error) { users := make([]User, 1) - dao.Db.Raw("select T.id,T.name,T.follow_cnt follow_count,T.follower_cnt follower_count,if(f.cancel is null,'false','true') is_follow"+ + + if err := dao.Db.Raw("select T.id,T.name,T.follow_cnt follow_count,T.follower_cnt follower_count,if(f.cancel is null,'false','true') is_follow"+ "\nfrom follows f right join"+ "\n(\n\tselect fid,id,`name`,"+ "\n\tcount(if(tag = 'follower' and cancel is not null,1,null)) follower_cnt,"+ @@ -206,7 +210,10 @@ func (f *FollowServiceImp) GetFollowers(userId int64) ([]User, error) { "\n\t\tleft join follows f2 on u.id = f2.follower_id and f2.cancel = 0"+ "\n\t\t) T\n\t\tgroup by fid,id,`name`"+ "\n) T on f.user_id = T.fid and f.follower_id = T.id and f.cancel = 0 where fid = ?", userId). - Scan(&users) - + Scan(&users).Error; nil != err { + // 查询出错。 + return nil, err + } + // 查询成功。 return users, nil } diff --git a/service/followServiceImpl_test.go b/service/followServiceImpl_test.go index 09e7458..d930763 100644 --- a/service/followServiceImpl_test.go +++ b/service/followServiceImpl_test.go @@ -6,7 +6,7 @@ import ( ) func TestIsFollow(t *testing.T) { - isFollow, err := newFSIInstance().IsFollowing(1, 2) + isFollow, err := NewFSIInstance().IsFollowing(1, 2) if nil != err { t.Errorf("IsFollow() error = %v", err) } From d14289e64c1d52325333fb939c08014221e6492a Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Sat, 21 May 2022 01:54:42 +0800 Subject: [PATCH 50/70] =?UTF-8?q?dev-20220519-video=20=E5=AE=8C=E6=88=90co?= =?UTF-8?q?ntroller?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/videoController.go | 110 +++++++++++++++++++++++++++++++ router.go | 9 +-- service/videoService.go | 14 ++-- service/videoServiceImpl.go | 56 ++++++++++++++-- service/videoServiceImpl_test.go | 34 ++++++++-- service/videoSub.go | 10 +-- 6 files changed, 205 insertions(+), 28 deletions(-) create mode 100644 controller/videoController.go diff --git a/controller/videoController.go b/controller/videoController.go new file mode 100644 index 0000000..6a8a63d --- /dev/null +++ b/controller/videoController.go @@ -0,0 +1,110 @@ +package controller + +import ( + "TikTok/service" + "github.com/gin-gonic/gin" + "log" + "net/http" + "strconv" + "time" +) + +type FeedResponse struct { + Response + VideoList []service.Video `json:"video_list,omitempty"` + NextTime int64 `json:"next_time,omitempty"` +} + +type VideoListResponse struct { + Response + VideoList []service.Video `json:"video_list"` +} + +func GetVideo() service.VideoServiceImpl { + var userService service.UserServiceImpl + var followService service.FollowServiceImp + var videoService service.VideoServiceImpl + var likeService service.LikeServiceImpl + var commentService service.CommentServiceImpl + userService.FollowService = &followService + followService.UserService = &userService + likeService.VideoService = &videoService + commentService.UserService = &userService + videoService.CommentService = &commentService + videoService.LikeService = &likeService + videoService.UserService = &userService + return videoService +} + +func Feed(c *gin.Context) { + last_time, _ := strconv.ParseInt(c.Query("latest_time"), 10, 64) + lastTime := time.Unix(last_time, 0) + log.Printf("获取到时间戳%v", lastTime) + userId, _ := strconv.ParseInt(c.Query("user_id"), 10, 64) + log.Printf("获取到用户id:%v\n", userId) + videoService := GetVideo() + feed, nextTime, err := videoService.Feed(lastTime, userId) + if err != nil { + log.Printf("方法videoService.Feed(lastTime, userId) 失败:%v", err) + c.JSON(http.StatusOK, FeedResponse{ + Response: Response{StatusCode: 1, StatusMsg: "获取视频流失败"}, + }) + return + } + log.Printf("方法videoService.Feed(lastTime, userId) 成功") + c.JSON(http.StatusOK, FeedResponse{ + Response: Response{StatusCode: 0}, + VideoList: feed, + NextTime: nextTime.Unix(), + }) +} + +// Publish apiRouter.POST("/publish/action/", controller.Publish) +func Publish(c *gin.Context) { + data, err := c.FormFile("data") + userId, _ := strconv.ParseInt(c.Query("user_id"), 10, 64) + log.Printf("获取到用户id:%v\n", userId) + if err != nil { + log.Printf("获取视频流失败:%v", err) + c.JSON(http.StatusOK, Response{ + StatusCode: 1, + StatusMsg: err.Error(), + }) + return + } + videoService := GetVideo() + err = videoService.Publish(data, userId) + if err != nil { + log.Printf("方法videoService.Publish(data, userId) 失败:%v", err) + c.JSON(http.StatusOK, Response{ + StatusCode: 1, + StatusMsg: err.Error(), + }) + return + } + log.Printf("方法videoService.Publish(data, userId) 成功") + c.JSON(http.StatusOK, Response{ + StatusCode: 0, + StatusMsg: " uploaded successfully", + }) +} + +// PublishList apiRouter.GET("/publish/list/", controller.PublishList) +func PublishList(c *gin.Context) { + userId, _ := strconv.ParseInt(c.Query("user_id"), 10, 64) + log.Printf("获取到用户id:%v\n", userId) + videoService := GetVideo() + list, err := videoService.List(userId) + if err != nil { + log.Printf("调用videoService.List(%v)出现错误:%v\n", userId, err) + c.JSON(http.StatusOK, VideoListResponse{ + Response: Response{StatusCode: 1, StatusMsg: "获取视频列表失败"}, + }) + return + } + log.Printf("调用videoService.List(%v)成功", userId) + c.JSON(http.StatusOK, VideoListResponse{ + Response: Response{StatusCode: 0}, + VideoList: list, + }) +} diff --git a/router.go b/router.go index 29f042b..a7087b6 100644 --- a/router.go +++ b/router.go @@ -9,12 +9,9 @@ import ( func initRouter(r *gin.Engine) { apiRouter := r.Group("/douyin") // basic apis - //apiRouter.GET("/feed/", controller.Feed) - //apiRouter.GET("/user/", middleware.Auth(), controller.UserInfo) - //apiRouter.POST("/user/register/", controller.Register) - //apiRouter.POST("/user/login/", controller.Login) - //apiRouter.POST("/publish/action/", controller.Publish) - //apiRouter.GET("/publish/list/", controller.PublishList) + apiRouter.GET("/feed/", controller.Feed) + apiRouter.POST("/publish/action/", controller.Publish) + apiRouter.GET("/publish/list/", controller.PublishList) apiRouter.GET("/user/", middleware.Auth(), controller.UserInfo) apiRouter.POST("/user/register/", controller.Register) diff --git a/service/videoService.go b/service/videoService.go index 3730fd3..6dd4389 100644 --- a/service/videoService.go +++ b/service/videoService.go @@ -6,13 +6,13 @@ import ( ) type Video struct { - Id int64 `copier:"ID"` //指定别名 - Author User `copier:"-"` //在拷贝时忽略 - PlayUrl string - CoverUrl string - FavoriteCount int64 - CommentCount int64 - IsFavorite bool + Id int64 `copier:"ID" json:"id,omitempty"` //指定别名 + Author User `copier:"-" json:"author"` //在拷贝时忽略 + PlayUrl string `json:"play_url,omitempty"` + CoverUrl string `json:"cover_url,omitempty"` + FavoriteCount int64 `json:"favorite_count,omitempty"` + CommentCount int64 `json:"comment_count,omitempty"` + IsFavorite bool `json:"is_favorite,omitempty"` } type VideoService interface { diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go index b895eed..75dbf05 100644 --- a/service/videoServiceImpl.go +++ b/service/videoServiceImpl.go @@ -27,13 +27,17 @@ func (videoService VideoServiceImpl) Feed(lastTime time.Time, userId int64) ([]V //根据传入的时间,获得传入时间前n个视频,可以通过config.videoCount来控制 tableVideos, err := dao.GetVideosByLastTime(lastTime) if err != nil { + log.Printf("方法dao.GetVideosByLastTime(lastTime) 失败:%v", err) return nil, time.Time{}, err } + log.Printf("方法dao.GetVideosByLastTime(lastTime) 成功:%v", tableVideos) //将数据通过copyVideos进行处理 err = videoService.copyVideos(&videos, &tableVideos, userId) if err != nil { + log.Printf("方法videoService.copyVideos(&videos, &tableVideos, userId) 失败:%v", err) return nil, time.Time{}, err } + log.Printf("方法videoService.copyVideos(&videos, &tableVideos, userId) 成功") //返回数据,同时获得视频中最早的时间返回 return videos, tableVideos[config.VideoCount-1].PublishTime, nil } @@ -46,31 +50,51 @@ func (videoService *VideoServiceImpl) GetVideo(videoId int64, userId int64) (Vid //从数据库中查询数据 data, err := dao.GetVideoByVideoId(videoId) if err != nil { + log.Printf("方法dao.GetVideoByVideoId(videoId) 失败:%v", err) return video, err } + log.Printf("方法dao.GetVideoByVideoId(videoId) 成功") + //将同名字段进行拷贝 - copier.Copy(&video, &data) + err = copier.Copy(&video, &data) + if err != nil { + log.Printf("方法copier.Copy(&video, &data) 失败:%v", err) + return Video{}, err + } + log.Printf("方法copier.Copy(&video, &data) 成功") + //插入Author video.Author, err = videoService.GetUserByIdWithCurId(data.AuthorId, userId) if err != nil { + log.Printf("方法videoService.GetUserByIdWithCurId(data.AuthorId, userId) 失败:%v", err) return video, err } + log.Printf("方法videoService.GetUserByIdWithCurId(data.AuthorId, userId) 成功") + //插入点赞数量 likeCount, err := videoService.FavouriteCount(data.ID) if err != nil { + log.Printf("方法videoService.FavouriteCount(data.ID) 失败:%v", err) return video, err } + log.Printf("方法videoService.FavouriteCount(data.ID) 成功") + video.FavoriteCount = likeCount //获取该视屏的评论数字 commentCount, err := videoService.CountFromVideoId(data.ID) if err != nil { + log.Printf("方法videoService.CountFromVideoId(data.ID) 失败:%v", err) return video, err } + log.Printf("方法videoService.CountFromVideoId(data.ID) 成功") + video.CommentCount = commentCount //获取当前用户是否点赞了该视频 isFavourit, err := videoService.IsFavourit(video.Id, userId) if err != nil { - return video, err + log.Printf("方法videoService.IsFavourit(video.Id, userId) 失败:%v", err) + } else { + log.Printf("方法videoService.IsFavourit(video.Id, userId) 成功") } video.IsFavorite = isFavourit return video, nil @@ -82,14 +106,19 @@ func (videoService *VideoServiceImpl) Publish(data *multipart.FileHeader, userId //将视频流上传到视频服务器,保存视频链接 file, err := data.Open() if err != nil { + log.Printf("方法data.Open() 失败%v", err) return err } + log.Printf("方法data.Open() 成功") //生成一个uuid作为视频的名字 videoName := uuid.NewV4().String() + log.Printf("生成视频名称%v", videoName) err = dao.VideoFTP(file, videoName) if err != nil { + log.Printf("方法dao.VideoFTP(file, videoName) 失败%v", err) return err } + log.Printf("方法dao.VideoFTP(file, videoName) 成功") defer file.Close() //在服务器上执行ffmpeg 从视频流中获取第一帧截图,并上传图片服务器,保存图片链接 imageName := uuid.NewV4().String() + ".jpg" @@ -99,14 +128,17 @@ func (videoService *VideoServiceImpl) Publish(data *multipart.FileHeader, userId cmd.Stdout = &out err = cmd.Run() if err != nil { + log.Printf("ffmpeg 出错!!!!") log.Fatal(err) } fmt.Printf("command output: %q", out.String()) //组装并持久化 err = dao.Save(videoName, imageName, userId) if err != nil { + log.Printf("方法dao.Save(videoName, imageName, userId) 失败%v", err) return err } + log.Printf("方法dao.Save(videoName, imageName, userId) 成功") return nil } @@ -116,13 +148,16 @@ func (videoService *VideoServiceImpl) List(userId int64) ([]Video, error) { //依据用户id查询所有的视频,获取视频列表 data, err := dao.GetVideosByAuthorId(userId) if err != nil { + log.Printf("方法dao.GetVideosByAuthorId(%v)失败:%v", userId, err) return nil, err } + log.Printf("方法dao.GetVideosByAuthorId(%v)成功:%v", userId, data) //提前定义好切片长度 result := make([]Video, 0, len(data)) //调用拷贝方法,将数据进行转换 err = videoService.copyVideos(&result, &data, userId) if err != nil { + log.Printf("方法videoService.copyVideos(&result, &data, %v)失败:%v", userId, err) return nil, err } //如果数据没有问题,则直接返回 @@ -134,29 +169,42 @@ func (videoService *VideoServiceImpl) copyVideos(result *[]Video, data *[]dao.Ta for _, temp := range *data { var video Video //进行拷贝操作 - copier.Copy(&video, &temp) + err := copier.Copy(&video, &temp) + if err != nil { + log.Printf("copier.Copy(&video, &temp) 失败:%v", err) + return err + } + log.Println("copier.Copy(&video, &temp) 成功") //获取对应的user author, err := videoService.GetUserByIdWithCurId(temp.AuthorId, userId) if err != nil { + log.Printf("videoService.GetUserByIdWithCurId(temp.AuthorId, userId) 失败:%v", err) return err } + log.Println("videoService.GetUserByIdWithCurId(temp.AuthorId, userId) 成功") video.Author = author //获取该视屏的点赞数字 likeCount, err := videoService.FavouriteCount(temp.ID) if err != nil { + log.Printf("videoService.FavouriteCount(temp.ID) 失败:%v", err) return err } + log.Printf("videoService.FavouriteCount(temp.ID) 成功") video.FavoriteCount = likeCount //获取该视屏的评论数字 commentCount, err := videoService.CountFromVideoId(temp.ID) if err != nil { + log.Printf("videoService.CountFromVideoId(temp.ID) 失败:%v", err) return err } + log.Printf("videoService.CountFromVideoId(temp.ID) 成功") video.CommentCount = commentCount //获取当前用户是否点赞了该视频 isFavourit, err := videoService.IsFavourit(video.Id, userId) if err != nil { - return err + log.Printf("videoService.IsFavourit(video.Id, userId) 失败:%v", err) + } else { + log.Printf("videoService.IsFavourit(video.Id, userId) 成功") } video.IsFavorite = isFavourit *result = append(*result, video) diff --git a/service/videoServiceImpl_test.go b/service/videoServiceImpl_test.go index 8e354e1..97223ac 100644 --- a/service/videoServiceImpl_test.go +++ b/service/videoServiceImpl_test.go @@ -14,9 +14,31 @@ func getVideoService() VideoService { return &videoService } +func getVideoService2() VideoService { + var userService UserServiceImpl + var followService FollowServiceImp + var videoService VideoServiceImpl + var likeService LikeServiceImpl + var commentService CommentServiceImpl + + userService.FollowService = &followService + + followService.UserService = &userService + + likeService.VideoService = &videoService + + commentService.UserService = &userService + + videoService.CommentService = &commentService + videoService.LikeService = &likeService + videoService.UserService = &userService + + return &videoService +} + func TestList(t *testing.T) { - videoService := getVideoService() - list, err := videoService.List(1) + videoService := getVideoService2() + list, err := videoService.List(999) if err != nil { return } @@ -27,8 +49,8 @@ func TestList(t *testing.T) { } func TestGetVideo(t *testing.T) { - videoService := getVideoService() - video, err := videoService.GetVideo(1, 1) + videoService := getVideoService2() + video, err := videoService.GetVideo(1, 2) if err != nil { return } @@ -36,8 +58,8 @@ func TestGetVideo(t *testing.T) { } func TestFeed(t *testing.T) { - videoService := getVideoService() - feed, t2, err := videoService.Feed(time.Now(), 1) + videoService := getVideoService2() + feed, t2, err := videoService.Feed(time.Now(), 2) if err != nil { return } diff --git a/service/videoSub.go b/service/videoSub.go index 7d57166..efa90dc 100644 --- a/service/videoSub.go +++ b/service/videoSub.go @@ -7,15 +7,15 @@ import ( type VideoSub struct { } -func (vs VideoSub) CountFromVideoId(id int64) (int64, error) { - return 4, nil -} - -func (vs VideoSub) Send(comment *dao.Comment) error { +func (vs VideoSub) Send(comment dao.Comment) error { //TODO implement me panic("implement me") } +func (vs VideoSub) CountFromVideoId(id int64) (int64, error) { + return 4, nil +} + func (vs VideoSub) DelComment(id int64) error { //TODO implement me panic("implement me") From 24e4db5070a194284900408fa579339faf213629 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Sat, 21 May 2022 02:06:50 +0800 Subject: [PATCH 51/70] =?UTF-8?q?dev-20220519-video=20bug=20=E6=97=B6?= =?UTF-8?q?=E9=97=B4=E6=88=B3=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/videoController.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/controller/videoController.go b/controller/videoController.go index 6a8a63d..3ace5db 100644 --- a/controller/videoController.go +++ b/controller/videoController.go @@ -37,10 +37,10 @@ func GetVideo() service.VideoServiceImpl { } func Feed(c *gin.Context) { - last_time, _ := strconv.ParseInt(c.Query("latest_time"), 10, 64) - lastTime := time.Unix(last_time, 0) + me, _ := strconv.ParseInt(c.Query("latest_time"), 10, 64) + lastTime := time.Unix(me, 0) log.Printf("获取到时间戳%v", lastTime) - userId, _ := strconv.ParseInt(c.Query("user_id"), 10, 64) + userId, _ := strconv.ParseInt(c.Query("userId"), 10, 64) log.Printf("获取到用户id:%v\n", userId) videoService := GetVideo() feed, nextTime, err := videoService.Feed(lastTime, userId) @@ -91,7 +91,7 @@ func Publish(c *gin.Context) { // PublishList apiRouter.GET("/publish/list/", controller.PublishList) func PublishList(c *gin.Context) { - userId, _ := strconv.ParseInt(c.Query("user_id"), 10, 64) + userId, _ := strconv.ParseInt(c.Query("userId"), 10, 64) log.Printf("获取到用户id:%v\n", userId) videoService := GetVideo() list, err := videoService.List(userId) From 7ca9ffdc822e41c7f463d94390776b0b2d659d44 Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Sat, 21 May 2022 15:07:11 +0800 Subject: [PATCH 52/70] =?UTF-8?q?dev-20220521-like=20=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E5=8A=A0=E4=BA=86dao=E5=B1=82,=E5=AF=B9=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E8=AF=BB=E5=86=99=E6=93=8D=E4=BD=9C=E9=83=BD=E5=9C=A8?= =?UTF-8?q?dao=E5=B1=82=E5=AE=8C=E6=88=90=EF=BC=8C=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E5=87=BD=E6=95=B0Isfavourite,favouriteCount?= =?UTF-8?q?=EF=BC=8C=E4=BF=AE=E6=94=B9=E4=BA=86user=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E4=BD=93isfollow=20json=E9=9D=9E=E5=8F=AF=E9=80=89=EF=BC=8C?= =?UTF-8?q?=E8=A7=A3=E5=86=B3getvideo()=E7=A9=BA=E6=8C=87=E9=92=88?= =?UTF-8?q?=E9=97=AE=E9=A2=98=EF=BC=8C=E8=A7=A3=E5=86=B3=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E4=B8=8D=E5=88=B0error=EF=BC=8C=E8=BF=94=E5=9B=9E=E4=B8=8D?= =?UTF-8?q?=E4=BA=86statuscode=E4=B8=BA1=E7=9A=84=E6=83=85=E5=86=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/likeController.go | 2 +- dao/LikeDao.go | 99 +++++++++++++++++++++++++++++++++ service/likeServiceImpl.go | 72 ++++++++++-------------- service/likeServiceImpl_test.go | 18 ++++++ service/likeSub.go | 2 +- service/userService.go | 2 +- 6 files changed, 150 insertions(+), 45 deletions(-) create mode 100644 service/likeServiceImpl_test.go diff --git a/controller/likeController.go b/controller/likeController.go index d7bb70b..31ece77 100644 --- a/controller/likeController.go +++ b/controller/likeController.go @@ -44,7 +44,7 @@ func Favorite_Action(c *gin.Context) { func GetFavouriteList(c *gin.Context) { user_id := c.Query("user_id") userid, _ := strconv.ParseInt(user_id, 10, 64) - like := new(service.LikeServiceImpl) + like := GetVideo() videos, err := like.GetFavouriteList(userid) if err == nil { c.JSON(http.StatusOK, GetFavouriteListResponse{ diff --git a/dao/LikeDao.go b/dao/LikeDao.go index 3fff45f..096d021 100644 --- a/dao/LikeDao.go +++ b/dao/LikeDao.go @@ -1,5 +1,12 @@ package dao +import ( + "TikTok/config" + "errors" + "log" + "sync" +) + //like表的结构。 type Like struct { Id int64 //自增主键 @@ -7,3 +14,95 @@ type Like struct { Video_id int64 //视频id Cancel int8 //是否点赞,0为点赞,1为取消赞 } + +// TableName 修改表名映射 +func (Like) TableName() string { + return "likes" +} + +type LikeDao struct { +} + +var ( + likeDao *LikeDao + likeOnce sync.Once +) + +func NewLikeDaoInstance() *LikeDao { + likeOnce.Do( + func() { + likeDao = &LikeDao{} + }) + return likeDao +} + +//1.根据videoid获取点赞数量 +func (*LikeDao) GetLikeCount(videoId int64) (int64, error) { + Init() + var count int64 + err := Db.Model(Like{}).Where(map[string]interface{}{"video_id": videoId, "cancel": config.Islike}). + Count(&count).Error + if err != nil { + return 0, errors.New("An unknown exception occurred in the query") + } else { + return count, nil + } +} + +//2.根据userid,videoid,action_type点赞或者取消赞 +func (*LikeDao) UpdateLike(userId int64, videoId int64, action_type int32) error { + Init() + err := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "video_id": videoId}). + Update("cancel", action_type).Error + if err != nil { + return errors.New("update data fail") + } + return nil +} + +//3、插入点赞数据 +func (*LikeDao) InsertLike(likedata Like) error { + Init() + err := Db.Model(Like{}).Create(&likedata).Error + if err != nil { + return errors.New("insert data fail") + } + return nil +} + +//4.根据userid,videoid查询点赞信息 +func (*LikeDao) GetLikeInfo(userId int64, videoId int64) (Like, error) { + Init() + var likeInfo Like + result := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "video_id": videoId}). + First(&likeInfo) + //如果获取likeInfo失败 + if result.Error != nil { + log.Println(result.Error.Error()) + return likeInfo, errors.New("get likeInfo failed") + } + //查询数据为0 + if result.RowsAffected == 0 { + log.Println(result.Error.Error()) + return likeInfo, errors.New("can't find this data") + } + return likeInfo, nil +} + +//5.根据userid查询所属点赞全部列表信息 +func (*LikeDao) GetLikeList(userId int64) ([]Like, error) { + Init() + var likeList []Like + result := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "cancel": config.Islike}). + Find(&likeList) + //如果获取likelist失败 + if result.Error != nil { + log.Println(result.Error.Error()) + return likeList, errors.New("get likeList failed") + } + //查询数据为0 + if result.RowsAffected == 0 { + return likeList, errors.New("there are no likes") + } + return likeList, nil +} diff --git a/service/likeServiceImpl.go b/service/likeServiceImpl.go index d556e22..bd20ab7 100644 --- a/service/likeServiceImpl.go +++ b/service/likeServiceImpl.go @@ -12,80 +12,68 @@ type LikeServiceImpl struct { } func (like *LikeServiceImpl) IsFavourit(videoId int64, userId int64) (bool, error) { - likedata := new(dao.Like) //未查询到数据,返回未点赞; - if result := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId).First(&likedata); result.RowsAffected == 0 { - return false, errors.New("can't find this data") - } //查询到数据,根据Cancel值判断是否点赞; - if likedata.Cancel == config.Islike { - return true, nil - } else { - return false, nil + likedata, err := dao.NewLikeDaoInstance().GetLikeInfo(userId, videoId) + if err != nil { + return false, err + } else { //查询到数据,根据Cancel值判断是否点赞; + if likedata.Cancel == config.Islike { + return true, nil + } else { + return false, nil + } } } func (like *LikeServiceImpl) FavouriteCount(videoId int64) (int64, error) { - var count int64 - err := dao.Db.Table("likes").Where("video_id = ? AND cancel = ?", videoId, config.Islike). - Count(&count).Error - //当查询出现异常时 - if err != nil { - return 0, errors.New("An unknown exception occurred in the query") - } else { - return count, nil - } + return dao.NewLikeDaoInstance().GetLikeCount(videoId) } func (like *LikeServiceImpl) FavouriteAction(userId int64, videoId int64, action_type int32) error { - likedata := new(dao.Like) + var likedata dao.Like //先查询是否有这条数据。 - result := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId).First(&likedata) + _, err := dao.NewLikeDaoInstance().GetLikeInfo(userId, videoId) //点赞行为,否则取消赞 if action_type == config.Likeaction { //没查到这条数据,则新建这条数据,否则更新即可; - if result.RowsAffected == 0 { + if err != nil { likedata.User_id = userId likedata.Video_id = videoId likedata.Cancel = config.Islike - if result1 := dao.Db.Table("likes").Create(&likedata); result1.RowsAffected == 0 { - return errors.New("insert data fail") - } + return dao.NewLikeDaoInstance().InsertLike(likedata) } else { - if result2 := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId). - Update("cancel", config.Islike); result2.RowsAffected == 0 { - return errors.New("update data fail") - } + return dao.NewLikeDaoInstance().UpdateLike(userId, videoId, config.Islike) } } else { //只有当前是点赞状态才能取消点赞这个行为,如果查询不到数据则返回错误; - if result.RowsAffected == 0 { + if err != nil { + log.Println(err.Error()) return errors.New("can't find this data") } else { - if result3 := dao.Db.Table("likes").Where("user_id = ? AND video_id = ?", userId, videoId). - Update("cancel", config.Unlike); result3.RowsAffected == 0 { - return errors.New("update data fail") - } + return dao.NewLikeDaoInstance().UpdateLike(userId, videoId, config.Unlike) } } return nil } func (like *LikeServiceImpl) GetFavouriteList(userId int64) ([]Video, error) { - var favorite_videolist []Video - var video_ids []int64 - if result := dao.Db.Table("likes").Select("video_id").Where("user_id = ? AND cancel = ?", userId, config.Islike). - Find(&video_ids); result.RowsAffected == 0 { //如果查询不到数据,说明这个用户没有点赞视频,返回空; - return favorite_videolist, errors.New("can't find favourite video") + //1.先查询点赞列表信息 + likeList, err := dao.NewLikeDaoInstance().GetLikeList(userId) + if err != nil { + log.Println(err.Error()) + return nil, err } - //如果查询到数据,遍历video_id,将每个video对象添加到集合中去; + //提前定义好切片长度 + favorite_videolist := make([]Video, 0, len(likeList)) + //如果查询到数据,遍历video_id; //likesub := new(LikeSub) - for video_id := range video_ids { - //video, err1 := likesub.GetVideo(int64(video_id),userId) - video, err1 := like.GetVideo(int64(video_id), userId) + for _, likedata := range likeList { + //video, err1 := likesub.GetVideo(likedata.Video_id,userId) + video, err1 := like.GetVideo(likedata.Video_id, userId) if err1 != nil { //如果没有获取这个video_id的视频,视频可能被删除了,跳过 log.Panicln(errors.New("can't find this favourite video")) continue - } + } //将每个video对象添加到集合中去 favorite_videolist = append(favorite_videolist, video) } return favorite_videolist, nil diff --git a/service/likeServiceImpl_test.go b/service/likeServiceImpl_test.go new file mode 100644 index 0000000..702aae0 --- /dev/null +++ b/service/likeServiceImpl_test.go @@ -0,0 +1,18 @@ +package service + +import ( + "fmt" + "testing" +) + +func TestIsFavourit(t *testing.T) { + impl := LikeServiceImpl{} + bool, _ := impl.IsFavourit(666, 3) + fmt.Printf("%v", bool) +} + +func TestFavouriteCount(t *testing.T) { + impl := LikeServiceImpl{} + count, _ := impl.FavouriteCount(666) + fmt.Printf("%v", count) +} diff --git a/service/likeSub.go b/service/likeSub.go index 27e1a26..a7f67b0 100644 --- a/service/likeSub.go +++ b/service/likeSub.go @@ -3,7 +3,7 @@ package service type LikeSub struct { } -func (like *LikeSub) GetVideo(videoId int64) (Video, error) { +func (like *LikeSub) GetVideo(videoId int64, userId int64) (Video, error) { if videoId%2 == 1 { return Video{ Id: 1, diff --git a/service/userService.go b/service/userService.go index 0cf2b7f..9a853ed 100644 --- a/service/userService.go +++ b/service/userService.go @@ -37,5 +37,5 @@ type User struct { Name string `json:"name,omitempty"` FollowCount int64 `json:"follow_count"` FollowerCount int64 `json:"follower_count"` - IsFollow bool `json:"is_follow,omitempty"` + IsFollow bool `json:"is_follow"` } From 12973dbefe4b4dae88b9bff9bb3763cf449a405c Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Sat, 21 May 2022 17:14:36 +0800 Subject: [PATCH 53/70] =?UTF-8?q?dev-20220519-video=20userid=E8=8E=B7?= =?UTF-8?q?=E5=8F=96fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/videoController.go | 4 ++-- router.go | 6 +++--- service/videoServiceImpl.go | 8 +------- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/controller/videoController.go b/controller/videoController.go index 3ace5db..fc51e08 100644 --- a/controller/videoController.go +++ b/controller/videoController.go @@ -40,7 +40,7 @@ func Feed(c *gin.Context) { me, _ := strconv.ParseInt(c.Query("latest_time"), 10, 64) lastTime := time.Unix(me, 0) log.Printf("获取到时间戳%v", lastTime) - userId, _ := strconv.ParseInt(c.Query("userId"), 10, 64) + userId, _ := strconv.ParseInt(c.GetString("userId"), 10, 64) log.Printf("获取到用户id:%v\n", userId) videoService := GetVideo() feed, nextTime, err := videoService.Feed(lastTime, userId) @@ -91,7 +91,7 @@ func Publish(c *gin.Context) { // PublishList apiRouter.GET("/publish/list/", controller.PublishList) func PublishList(c *gin.Context) { - userId, _ := strconv.ParseInt(c.Query("userId"), 10, 64) + userId, _ := strconv.ParseInt(c.GetString("userId"), 10, 64) log.Printf("获取到用户id:%v\n", userId) videoService := GetVideo() list, err := videoService.List(userId) diff --git a/router.go b/router.go index a7087b6..752b2b9 100644 --- a/router.go +++ b/router.go @@ -9,9 +9,9 @@ import ( func initRouter(r *gin.Engine) { apiRouter := r.Group("/douyin") // basic apis - apiRouter.GET("/feed/", controller.Feed) - apiRouter.POST("/publish/action/", controller.Publish) - apiRouter.GET("/publish/list/", controller.PublishList) + apiRouter.GET("/feed/", middleware.Auth(), controller.Feed) + apiRouter.POST("/publish/action/", middleware.Auth(), controller.Publish) + apiRouter.GET("/publish/list/", middleware.Auth(), controller.PublishList) apiRouter.GET("/user/", middleware.Auth(), controller.UserInfo) apiRouter.POST("/user/register/", controller.Register) diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go index 75dbf05..fc56e94 100644 --- a/service/videoServiceImpl.go +++ b/service/videoServiceImpl.go @@ -67,7 +67,6 @@ func (videoService *VideoServiceImpl) GetVideo(videoId int64, userId int64) (Vid video.Author, err = videoService.GetUserByIdWithCurId(data.AuthorId, userId) if err != nil { log.Printf("方法videoService.GetUserByIdWithCurId(data.AuthorId, userId) 失败:%v", err) - return video, err } log.Printf("方法videoService.GetUserByIdWithCurId(data.AuthorId, userId) 成功") @@ -75,7 +74,6 @@ func (videoService *VideoServiceImpl) GetVideo(videoId int64, userId int64) (Vid likeCount, err := videoService.FavouriteCount(data.ID) if err != nil { log.Printf("方法videoService.FavouriteCount(data.ID) 失败:%v", err) - return video, err } log.Printf("方法videoService.FavouriteCount(data.ID) 成功") @@ -84,7 +82,6 @@ func (videoService *VideoServiceImpl) GetVideo(videoId int64, userId int64) (Vid commentCount, err := videoService.CountFromVideoId(data.ID) if err != nil { log.Printf("方法videoService.CountFromVideoId(data.ID) 失败:%v", err) - return video, err } log.Printf("方法videoService.CountFromVideoId(data.ID) 成功") @@ -178,8 +175,7 @@ func (videoService *VideoServiceImpl) copyVideos(result *[]Video, data *[]dao.Ta //获取对应的user author, err := videoService.GetUserByIdWithCurId(temp.AuthorId, userId) if err != nil { - log.Printf("videoService.GetUserByIdWithCurId(temp.AuthorId, userId) 失败:%v", err) - return err + log.Printf("videoService.GetUserByIdWithCurId(%v, %v) 失败:%v", temp.AuthorId, userId, err) } log.Println("videoService.GetUserByIdWithCurId(temp.AuthorId, userId) 成功") video.Author = author @@ -187,7 +183,6 @@ func (videoService *VideoServiceImpl) copyVideos(result *[]Video, data *[]dao.Ta likeCount, err := videoService.FavouriteCount(temp.ID) if err != nil { log.Printf("videoService.FavouriteCount(temp.ID) 失败:%v", err) - return err } log.Printf("videoService.FavouriteCount(temp.ID) 成功") video.FavoriteCount = likeCount @@ -195,7 +190,6 @@ func (videoService *VideoServiceImpl) copyVideos(result *[]Video, data *[]dao.Ta commentCount, err := videoService.CountFromVideoId(temp.ID) if err != nil { log.Printf("videoService.CountFromVideoId(temp.ID) 失败:%v", err) - return err } log.Printf("videoService.CountFromVideoId(temp.ID) 成功") video.CommentCount = commentCount From df3ac5572f2295de8ad5742794f3b0e99e611679 Mon Sep 17 00:00:00 2001 From: siyuanli Date: Sat, 21 May 2022 18:20:45 +0800 Subject: [PATCH 54/70] =?UTF-8?q?dev-20220520-comment=20=E8=AF=84=E8=AE=BA?= =?UTF-8?q?Dao=E5=B1=82=E5=87=BD=E6=95=B0=E6=9B=B4=E6=96=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/CommentDao.go | 7 +++---- router.go | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/dao/CommentDao.go b/dao/CommentDao.go index a8f8971..8cc9b11 100644 --- a/dao/CommentDao.go +++ b/dao/CommentDao.go @@ -45,7 +45,7 @@ func (*CommentDao) Count(video_id int64) (int64, error) { var count int64 err := Db.Model(Comment{}).Where(map[string]interface{}{"video_id": video_id, "cancel": config.ValidComment}).Count(&count).Error if err != nil { - return -1, errors.New("find commentsCount failed") + return -1, errors.New("find comments count failed") } return count, nil } @@ -71,7 +71,7 @@ func (*CommentDao) DeleteComment(id int64) error { } err := Db.Model(Comment{}).Where("id = ?", id).Update("cancel", config.InvalidComment).Error if err != nil { - return errors.New("del Comment failed") + return errors.New("del comment failed") } return nil } @@ -81,8 +81,7 @@ func (*CommentDao) GetCommentList(videoId int64) ([]Comment, error) { Init() var commentList []Comment result := Db.Model(Comment{}).Where(map[string]interface{}{"video_id": videoId, "cancel": config.ValidComment}).Find(&commentList) - if errors.Is(result.Error, gorm.ErrRecordNotFound) { - log.Println(result.Error.Error()) + if result.RowsAffected == 0 { return commentList, errors.New("there are no comments") } if result.Error != nil { diff --git a/router.go b/router.go index a7087b6..83eccbe 100644 --- a/router.go +++ b/router.go @@ -38,7 +38,7 @@ func initRouter(r *gin.Engine) { 评论模块 */ //发表评论 - apiRouter.POST("/douyin/comment/action/", middleware.Auth(), controller.Comment_Action) + apiRouter.POST("/comment/action/", middleware.Auth(), controller.Comment_Action) //查看评论列表 - apiRouter.GET("/douyin/comment/list/", middleware.Auth(), controller.Comment_List) + apiRouter.GET("/comment/list/", middleware.Auth(), controller.Comment_List) } From 58debdea05b37395d740a9b0ac9dc407b2d03876 Mon Sep 17 00:00:00 2001 From: siyuanli Date: Sat, 21 May 2022 20:02:37 +0800 Subject: [PATCH 55/70] =?UTF-8?q?dev-20220520-comment=20=E8=AF=84=E8=AE=BA?= =?UTF-8?q?Dao=E5=B1=82=E5=87=BD=E6=95=B0=E6=9B=B4=E6=96=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/Auth.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/middleware/Auth.go b/middleware/Auth.go index 4698e47..b5be123 100644 --- a/middleware/Auth.go +++ b/middleware/Auth.go @@ -27,7 +27,6 @@ func Auth() gin.HandlerFunc { } auth = strings.Fields(auth)[1] token, err := parseToken(auth) - context.Set("userId", token.Id) if err != nil { context.Abort() context.JSON(http.StatusUnauthorized, Response{ @@ -36,6 +35,7 @@ func Auth() gin.HandlerFunc { } else { println("token 正确") } + context.Set("userId", token.Id) context.Next() } } From ed21d51bcabaa62eea17662fbf13e8f703f6f59f Mon Sep 17 00:00:00 2001 From: siyuanli Date: Sat, 21 May 2022 20:08:19 +0800 Subject: [PATCH 56/70] =?UTF-8?q?dev-20220520-Auth=20token=E5=88=A4?= =?UTF-8?q?=E6=96=AD=E9=80=BB=E8=BE=91=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/Auth.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/middleware/Auth.go b/middleware/Auth.go index b5be123..730de5e 100644 --- a/middleware/Auth.go +++ b/middleware/Auth.go @@ -30,7 +30,8 @@ func Auth() gin.HandlerFunc { if err != nil { context.Abort() context.JSON(http.StatusUnauthorized, Response{ - StatusMsg: "Token Error", + StatusCode: -1, + StatusMsg: "Token Error", }) } else { println("token 正确") From b0b8e628843b48bff7c4dfa8dcc9aec246b83f65 Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Sat, 21 May 2022 21:00:16 +0800 Subject: [PATCH 57/70] =?UTF-8?q?dev-2022-5-21-follow=201-=E4=BF=AE?= =?UTF-8?q?=E6=94=B9followServiceImp=E7=BB=93=E6=9E=84=E4=BD=93=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E6=8E=A5=E5=8F=A3=E5=86=97=E4=BD=99=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/followServiceImpl.go | 1 - 1 file changed, 1 deletion(-) diff --git a/service/followServiceImpl.go b/service/followServiceImpl.go index 4f0f307..d35105e 100644 --- a/service/followServiceImpl.go +++ b/service/followServiceImpl.go @@ -8,7 +8,6 @@ import ( // FollowServiceImp 该结构体继承FollowService接口。 type FollowServiceImp struct { UserService - FollowService } var ( From 6c46a43d5233432788aafe4ca863393c8eca6e92 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Sat, 21 May 2022 22:32:58 +0800 Subject: [PATCH 58/70] =?UTF-8?q?dev-20220521-user=20=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E4=BB=A3=E7=A0=81(=E4=BF=AE=E5=A4=8DAuth?= =?UTF-8?q?=E7=9A=84Bug)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/Auth.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/middleware/Auth.go b/middleware/Auth.go index 730de5e..979bb39 100644 --- a/middleware/Auth.go +++ b/middleware/Auth.go @@ -21,7 +21,7 @@ func Auth() gin.HandlerFunc { if len(auth) == 0 { context.Abort() context.JSON(http.StatusUnauthorized, Response{ - StatusCode: 0, + StatusCode: -1, StatusMsg: "Unauthorized", }) } From be938dc7b114d38c307d0aee279a81011ff1b81e Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Sat, 21 May 2022 22:42:30 +0800 Subject: [PATCH 59/70] =?UTF-8?q?dev-20220519-video=20=E6=9B=B4=E6=8D=A2go?= =?UTF-8?q?rm=E5=8C=85=EF=BC=8C=E5=B9=B6=E6=B7=BB=E5=8A=A0dao=E5=B1=82?= =?UTF-8?q?=E6=97=A5=E5=BF=97=EF=BC=8C=E4=BB=A3=E7=A0=81=E6=9B=B4=E5=8A=A0?= =?UTF-8?q?=E4=BC=98=E9=9B=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.go | 2 +- controller/videoController.go | 7 +++--- dao/Initdao.go | 20 +++++++++++++--- go.mod | 6 +++-- go.sum | 15 +++++++----- service/videoService.go | 14 ++++++------ service/videoServiceImpl.go | 43 ++++++++++++++++++++--------------- 7 files changed, 67 insertions(+), 40 deletions(-) diff --git a/config/config.go b/config/config.go index c3ada54..863927b 100644 --- a/config/config.go +++ b/config/config.go @@ -9,7 +9,7 @@ var OneMinute = 60 * 1 var OneMonth = 60 * 60 * 24 * 30 // VideoCount 每次获取视频流的数量 -const VideoCount = 10 +const VideoCount = 5 // ConConfig ftp服务器地址 const ConConfig = "43.138.25.60:21" diff --git a/controller/videoController.go b/controller/videoController.go index fc51e08..24cc1a3 100644 --- a/controller/videoController.go +++ b/controller/videoController.go @@ -11,8 +11,8 @@ import ( type FeedResponse struct { Response - VideoList []service.Video `json:"video_list,omitempty"` - NextTime int64 `json:"next_time,omitempty"` + VideoList []service.Video `json:"video_list"` + NextTime int64 `json:"next_time"` } type VideoListResponse struct { @@ -91,7 +91,8 @@ func Publish(c *gin.Context) { // PublishList apiRouter.GET("/publish/list/", controller.PublishList) func PublishList(c *gin.Context) { - userId, _ := strconv.ParseInt(c.GetString("userId"), 10, 64) + user_Id, _ := c.GetQuery("user_id") + userId, _ := strconv.ParseInt(user_Id, 10, 64) log.Printf("获取到用户id:%v\n", userId) videoService := GetVideo() list, err := videoService.List(userId) diff --git a/dao/Initdao.go b/dao/Initdao.go index 95c52bf..eb8c909 100644 --- a/dao/Initdao.go +++ b/dao/Initdao.go @@ -1,18 +1,32 @@ package dao import ( - "github.com/jinzhu/gorm" - _ "github.com/jinzhu/gorm/dialects/mysql" + "gorm.io/driver/mysql" + "gorm.io/gorm" + "gorm.io/gorm/logger" "log" + "os" + "time" ) var Db *gorm.DB func Init() { + newLogger := logger.New( + log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer + logger.Config{ + SlowThreshold: time.Second, // 慢 SQL 阈值 + LogLevel: logger.Error, // Log level + Colorful: true, // 彩色打印 + }, + ) var err error + dsn := "douyin:zjqxy@tcp(43.138.25.60:3306)/douyin?charset=utf8mb4&parseTime=True&loc=Local" //想要正确的处理time.Time,需要带上 parseTime 参数, //要支持完整的UTF-8编码,需要将 charset=utf8 更改为 charset=utf8mb4 - Db, err = gorm.Open("mysql", "douyin:zjqxy@tcp(43.138.25.60:3306)/douyin?charset=utf8mb4&parseTime=True&loc=Local") + Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{ + Logger: newLogger, + }) if err != nil { log.Panicln("err:", err.Error()) } diff --git a/go.mod b/go.mod index fd5ac5b..70b5a46 100644 --- a/go.mod +++ b/go.mod @@ -10,12 +10,13 @@ require ( github.com/jinzhu/gorm v1.9.16 github.com/satori/go.uuid v1.2.0 github.com/swaggo/swag v1.8.1 + gorm.io/driver/mysql v1.3.3 + gorm.io/gorm v1.23.5 ) require ( github.com/KyleBanks/depth v1.2.1 // indirect github.com/gin-contrib/sse v0.1.0 // indirect - github.com/giorgisio/goav v0.1.0 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect github.com/go-openapi/jsonreference v0.20.0 // indirect github.com/go-openapi/spec v0.20.6 // indirect @@ -23,9 +24,10 @@ require ( github.com/go-playground/locales v0.14.0 // indirect github.com/go-playground/universal-translator v0.18.0 // indirect github.com/go-playground/validator/v10 v10.11.0 // indirect - github.com/go-sql-driver/mysql v1.5.0 // indirect + github.com/go-sql-driver/mysql v1.6.0 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.4 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/leodido/go-urn v1.2.1 // indirect diff --git a/go.sum b/go.sum index 7e7a1e8..d0065b1 100644 --- a/go.sum +++ b/go.sum @@ -25,8 +25,6 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= -github.com/giorgisio/goav v0.1.0 h1:ZyfG3NfX7PMSimv4ulhmnQJf/XeHpMdGCn+afRmY5Oc= -github.com/giorgisio/goav v0.1.0/go.mod h1:RtH8HyxLRLU1iY0pjfhWBKRhnbsnmfoI+FxMwb5bfEo= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= @@ -51,8 +49,9 @@ github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= github.com/go-playground/validator/v10 v10.11.0 h1:0W+xRM511GY47Yy3bZUbJVitCNg2BOGlCyvTqsp/xIw= github.com/go-playground/validator/v10 v10.11.0/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU= -github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= @@ -63,16 +62,15 @@ github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gosuri/uilive v0.0.0-20170323041506-ac356e6e42cd/go.mod h1:qkLSc0A5EXSP6B04TrN4oQoxqFI7A8XvoXSlJi8cwk8= -github.com/gosuri/uiprogress v0.0.0-20170224063937-d0567a9d84a1/go.mod h1:C1RTYn4Sc7iEyf6j8ft5dyoZ4212h8G1ol9QQluh5+0= github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= -github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M= github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jinzhu/now v1.1.4 h1:tHnRBy1i5F2Dh8BAFxqFzxKqqvezXrL2OW1TnX+Mlas= +github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -220,3 +218,8 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/mysql v1.3.3 h1:jXG9ANrwBc4+bMvBcSl8zCfPBaVoPyBEBshA8dA93X8= +gorm.io/driver/mysql v1.3.3/go.mod h1:ChK6AHbHgDCFZyJp0F+BmVGb06PSIoh9uVYKAlRbb2U= +gorm.io/gorm v1.23.1/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= +gorm.io/gorm v1.23.5 h1:TnlF26wScKSvknUC/Rn8t0NLLM22fypYBlvj1+aH6dM= +gorm.io/gorm v1.23.5/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= diff --git a/service/videoService.go b/service/videoService.go index 6dd4389..31d545f 100644 --- a/service/videoService.go +++ b/service/videoService.go @@ -6,13 +6,13 @@ import ( ) type Video struct { - Id int64 `copier:"ID" json:"id,omitempty"` //指定别名 - Author User `copier:"-" json:"author"` //在拷贝时忽略 - PlayUrl string `json:"play_url,omitempty"` - CoverUrl string `json:"cover_url,omitempty"` - FavoriteCount int64 `json:"favorite_count,omitempty"` - CommentCount int64 `json:"comment_count,omitempty"` - IsFavorite bool `json:"is_favorite,omitempty"` + Id int64 `copier:"ID" json:"id"` //指定别名 + Author User `copier:"-" json:"author"` //在拷贝时忽略 + PlayUrl string `json:"play_url"` + CoverUrl string `json:"cover_url"` + FavoriteCount int64 `json:"favorite_count"` + CommentCount int64 `json:"comment_count"` + IsFavorite bool `json:"is_favorite"` } type VideoService interface { diff --git a/service/videoServiceImpl.go b/service/videoServiceImpl.go index fc56e94..baea5d3 100644 --- a/service/videoServiceImpl.go +++ b/service/videoServiceImpl.go @@ -21,8 +21,9 @@ type VideoServiceImpl struct { // Feed // 通过传入时间戳,当前用户的id,返回对应的视频数组,以及视频数组中最早的发布时间 +// 获取视频数组大小是可以控制的,在config中的videoCount变量 func (videoService VideoServiceImpl) Feed(lastTime time.Time, userId int64) ([]Video, time.Time, error) { - //创建对应返回视频的切片数组 + //创建对应返回视频的切片数组,提前将切片的容量设置好,可以减少切片扩容的性能 videos := make([]Video, 0, config.VideoCount) //根据传入的时间,获得传入时间前n个视频,可以通过config.videoCount来控制 tableVideos, err := dao.GetVideosByLastTime(lastTime) @@ -31,7 +32,7 @@ func (videoService VideoServiceImpl) Feed(lastTime time.Time, userId int64) ([]V return nil, time.Time{}, err } log.Printf("方法dao.GetVideosByLastTime(lastTime) 成功:%v", tableVideos) - //将数据通过copyVideos进行处理 + //将数据通过copyVideos进行处理,在拷贝的过程中对数据进行组装 err = videoService.copyVideos(&videos, &tableVideos, userId) if err != nil { log.Printf("方法videoService.copyVideos(&videos, &tableVideos, userId) 失败:%v", err) @@ -43,57 +44,63 @@ func (videoService VideoServiceImpl) Feed(lastTime time.Time, userId int64) ([]V } // GetVideo -// 传入视频id获得对应的视频对象,注意还需要传入当前的用户id +// 传入视频id获得对应的视频对象,注意还需要传入当前登录用户id func (videoService *VideoServiceImpl) GetVideo(videoId int64, userId int64) (Video, error) { + //初始化video对象 var video Video - //从数据库中查询数据 + + //从数据库中查询数据,如果查询不到数据,就直接失败返回,后续流程就不需要执行了 data, err := dao.GetVideoByVideoId(videoId) if err != nil { log.Printf("方法dao.GetVideoByVideoId(videoId) 失败:%v", err) return video, err + } else { + log.Printf("方法dao.GetVideoByVideoId(videoId) 成功") } - log.Printf("方法dao.GetVideoByVideoId(videoId) 成功") - //将同名字段进行拷贝 + //将同名字段进行拷贝,如果拷贝失败,说明内部逻辑出现问题,导致的拷贝失败,直接返回一个空的数组,同时返回错误 err = copier.Copy(&video, &data) if err != nil { log.Printf("方法copier.Copy(&video, &data) 失败:%v", err) return Video{}, err + } else { + log.Printf("方法copier.Copy(&video, &data) 成功") } - log.Printf("方法copier.Copy(&video, &data) 成功") - //插入Author + //插入Author,这里需要将视频的发布者和当前登录的用户传入,才能正确获得isFollow, + //如果出现错误,不能直接返回失败,将默认值返回,保证稳定 video.Author, err = videoService.GetUserByIdWithCurId(data.AuthorId, userId) if err != nil { log.Printf("方法videoService.GetUserByIdWithCurId(data.AuthorId, userId) 失败:%v", err) + } else { + log.Printf("方法videoService.GetUserByIdWithCurId(data.AuthorId, userId) 成功") } - log.Printf("方法videoService.GetUserByIdWithCurId(data.AuthorId, userId) 成功") - //插入点赞数量 - likeCount, err := videoService.FavouriteCount(data.ID) + //插入点赞数量,同上所示,不将nil直接向上返回,数据没有就算了,给一个默认就行了 + video.FavoriteCount, err = videoService.FavouriteCount(data.ID) if err != nil { log.Printf("方法videoService.FavouriteCount(data.ID) 失败:%v", err) + } else { + log.Printf("方法videoService.FavouriteCount(data.ID) 成功") } - log.Printf("方法videoService.FavouriteCount(data.ID) 成功") - video.FavoriteCount = likeCount //获取该视屏的评论数字 - commentCount, err := videoService.CountFromVideoId(data.ID) + video.CommentCount, err = videoService.CountFromVideoId(data.ID) if err != nil { log.Printf("方法videoService.CountFromVideoId(data.ID) 失败:%v", err) + } else { + log.Printf("方法videoService.CountFromVideoId(data.ID) 成功") } - log.Printf("方法videoService.CountFromVideoId(data.ID) 成功") - video.CommentCount = commentCount //获取当前用户是否点赞了该视频 - isFavourit, err := videoService.IsFavourit(video.Id, userId) + video.IsFavorite, err = videoService.IsFavourit(video.Id, userId) if err != nil { log.Printf("方法videoService.IsFavourit(video.Id, userId) 失败:%v", err) } else { log.Printf("方法videoService.IsFavourit(video.Id, userId) 成功") } - video.IsFavorite = isFavourit + return video, nil } From 59c8179854b6d7a61e125837616d416c6abd738e Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Sun, 22 May 2022 09:35:20 +0800 Subject: [PATCH 60/70] =?UTF-8?q?dev-20220522-user=20=E6=89=93=E5=BC=80gor?= =?UTF-8?q?m=E8=AF=A6=E7=BB=86log?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/Initdao.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dao/Initdao.go b/dao/Initdao.go index 95c52bf..a9f498f 100644 --- a/dao/Initdao.go +++ b/dao/Initdao.go @@ -13,6 +13,8 @@ func Init() { //想要正确的处理time.Time,需要带上 parseTime 参数, //要支持完整的UTF-8编码,需要将 charset=utf8 更改为 charset=utf8mb4 Db, err = gorm.Open("mysql", "douyin:zjqxy@tcp(43.138.25.60:3306)/douyin?charset=utf8mb4&parseTime=True&loc=Local") + //打开gorm详细日志 + Db.LogMode(true) if err != nil { log.Panicln("err:", err.Error()) } From bfad3ce869be6287859de53fe7c5e723da961431 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Sun, 22 May 2022 12:55:39 +0800 Subject: [PATCH 61/70] =?UTF-8?q?dev-20220519-video=20=E7=8B=97=E4=B8=9C?= =?UTF-8?q?=E8=A5=BF=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=97=B6=E9=97=B4=E6=88=B3?= =?UTF-8?q?bug=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/videoController.go | 2 +- service/videoServiceImpl_test.go | 16 +--------------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/controller/videoController.go b/controller/videoController.go index 24cc1a3..ddf2862 100644 --- a/controller/videoController.go +++ b/controller/videoController.go @@ -38,7 +38,7 @@ func GetVideo() service.VideoServiceImpl { func Feed(c *gin.Context) { me, _ := strconv.ParseInt(c.Query("latest_time"), 10, 64) - lastTime := time.Unix(me, 0) + lastTime := time.UnixMilli(me) log.Printf("获取到时间戳%v", lastTime) userId, _ := strconv.ParseInt(c.GetString("userId"), 10, 64) log.Printf("获取到用户id:%v\n", userId) diff --git a/service/videoServiceImpl_test.go b/service/videoServiceImpl_test.go index 97223ac..a1f7e6d 100644 --- a/service/videoServiceImpl_test.go +++ b/service/videoServiceImpl_test.go @@ -6,39 +6,25 @@ import ( "time" ) -func getVideoService() VideoService { - var videoService VideoServiceImpl - videoService.UserService = VideoSub{} - videoService.LikeService = VideoSub{} - videoService.CommentService = VideoSub{} - return &videoService -} - func getVideoService2() VideoService { var userService UserServiceImpl var followService FollowServiceImp var videoService VideoServiceImpl var likeService LikeServiceImpl var commentService CommentServiceImpl - userService.FollowService = &followService - followService.UserService = &userService - likeService.VideoService = &videoService - commentService.UserService = &userService - videoService.CommentService = &commentService videoService.LikeService = &likeService videoService.UserService = &userService - return &videoService } func TestList(t *testing.T) { videoService := getVideoService2() - list, err := videoService.List(999) + list, err := videoService.List(3) if err != nil { return } From deb5f57d1cc41b6b118bbf1e742cbc5bc3955376 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Sun, 22 May 2022 14:29:13 +0800 Subject: [PATCH 62/70] =?UTF-8?q?dev-20220522-user=20=E4=BF=AE=E6=94=B9aut?= =?UTF-8?q?h?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/Auth.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/middleware/Auth.go b/middleware/Auth.go index 979bb39..f1ab724 100644 --- a/middleware/Auth.go +++ b/middleware/Auth.go @@ -17,7 +17,8 @@ type Response struct { // 若用户携带的token正确,解析token,将userId放入上下文context中并放行;否则,返回错误信息 func Auth() gin.HandlerFunc { return func(context *gin.Context) { - auth := context.Request.Header.Get("Authorization") + //auth := context.Request.Header.Get("Authorization") + auth := context.Query("token") if len(auth) == 0 { context.Abort() context.JSON(http.StatusUnauthorized, Response{ From 0eb0a6fe4988e5d6eaec67e9aa32bb3a6320cdc4 Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Sun, 22 May 2022 15:38:27 +0800 Subject: [PATCH 63/70] =?UTF-8?q?dev-20220519-video=20=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E5=91=BD=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c322238..eb0a76c 100644 --- a/README.md +++ b/README.md @@ -1 +1,6 @@ -# tiktok-dev \ No newline at end of file +# tiktok-dev + +## 项目编译部署 +```shell +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build ./ +``` \ No newline at end of file From d4ca066ad2c210539f4813b6e28b89d3d697b320 Mon Sep 17 00:00:00 2001 From: jyd1124 Date: Sun, 22 May 2022 15:40:36 +0800 Subject: [PATCH 64/70] =?UTF-8?q?dev-20220522-user=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=B3=A8=E5=86=8Cbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/userController.go | 3 +++ service/userServiceImpl.go | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/controller/userController.go b/controller/userController.go index 616c90c..ec3aa69 100644 --- a/controller/userController.go +++ b/controller/userController.go @@ -4,6 +4,7 @@ import ( "TikTok/dao" "TikTok/service" "github.com/gin-gonic/gin" + "log" "net/http" "strconv" ) @@ -44,7 +45,9 @@ func Register(c *gin.Context) { if usi.InsertTableUser(&newUser) != true { println("Insert Data Fail") } + u := usi.GetTableUserByUsername(username) token := service.GenerateToken(username) + log.Println("注册返回的id: ", u.Id) c.JSON(http.StatusOK, UserLoginResponse{ Response: Response{StatusCode: 0}, UserId: u.Id, diff --git a/service/userServiceImpl.go b/service/userServiceImpl.go index f0bf796..cd87f55 100644 --- a/service/userServiceImpl.go +++ b/service/userServiceImpl.go @@ -145,9 +145,9 @@ func GenerateToken(username string) string { // NewToken 根据信息创建token func NewToken(u dao.TableUser) string { expiresTime := time.Now().Unix() + int64(config.OneDayOfHours) - fmt.Printf("%v\n", expiresTime) + fmt.Printf("expiresTime: %v\n", expiresTime) id64 := u.Id - fmt.Printf("newtoken: %v\n", strconv.FormatInt(id64, 10)) + fmt.Printf("id: %v\n", strconv.FormatInt(id64, 10)) claims := jwt.StandardClaims{ Audience: u.Name, ExpiresAt: expiresTime, From a070cde443a63472999b1010e6b9f1d948def0f7 Mon Sep 17 00:00:00 2001 From: siyuanli Date: Sun, 22 May 2022 21:16:41 +0800 Subject: [PATCH 65/70] =?UTF-8?q?dev-20220520-Comment=20test=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E6=B7=BB=E5=8A=A0=EF=BC=8CDao=E4=B8=ADinit=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=BA=93=E9=80=BB=E8=BE=91=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/CommentDao.go | 11 +++++----- dao/CommentDao_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) create mode 100644 dao/CommentDao_test.go diff --git a/dao/CommentDao.go b/dao/CommentDao.go index 8cc9b11..70dd9fb 100644 --- a/dao/CommentDao.go +++ b/dao/CommentDao.go @@ -3,7 +3,6 @@ package dao import ( "TikTok/config" "errors" - "github.com/jinzhu/gorm" "log" "sync" ) @@ -41,7 +40,7 @@ func NewCommentDaoInstance() *CommentDao { //1、使用video id 查询Comment数量 func (*CommentDao) Count(video_id int64) (int64, error) { - Init() + //Init() var count int64 err := Db.Model(Comment{}).Where(map[string]interface{}{"video_id": video_id, "cancel": config.ValidComment}).Count(&count).Error if err != nil { @@ -52,7 +51,7 @@ func (*CommentDao) Count(video_id int64) (int64, error) { //2、发表评论 func (*CommentDao) InsertComment(comment Comment) error { - Init() + //Init() err := Db.Model(Comment{}).Create(&comment).Error if err != nil { return errors.New("create comment failed") @@ -62,11 +61,11 @@ func (*CommentDao) InsertComment(comment Comment) error { //3、删除评论,传入评论id func (*CommentDao) DeleteComment(id int64) error { - Init() + //Init() var commentInfo Comment //先查询是否有此评论(正常肯定是有的吧) result := Db.Model(Comment{}).Where(map[string]interface{}{"id": id, "cancel": config.ValidComment}).First(&commentInfo) - if errors.Is(result.Error, gorm.ErrRecordNotFound) { + if result.RowsAffected == 0 { return errors.New("del comment is not exist") } err := Db.Model(Comment{}).Where("id = ?", id).Update("cancel", config.InvalidComment).Error @@ -78,7 +77,7 @@ func (*CommentDao) DeleteComment(id int64) error { //4.根据视频id查询所属评论全部列表信息 func (*CommentDao) GetCommentList(videoId int64) ([]Comment, error) { - Init() + //Init() var commentList []Comment result := Db.Model(Comment{}).Where(map[string]interface{}{"video_id": videoId, "cancel": config.ValidComment}).Find(&commentList) if result.RowsAffected == 0 { diff --git a/dao/CommentDao_test.go b/dao/CommentDao_test.go new file mode 100644 index 0000000..6e3d843 --- /dev/null +++ b/dao/CommentDao_test.go @@ -0,0 +1,46 @@ +package dao + +import ( + "TikTok/config" + "fmt" + "testing" + "time" +) + +//1、使用video id 查询Comment数量 的测试函数 +func TestCountComment(t *testing.T) { + Init() + count, err := NewCommentDaoInstance().Count(14) + fmt.Printf("%v\n", count) + fmt.Printf("[%v]", err) +} + +//2、发表评论 的测试函数 +func TestInsertComment(t *testing.T) { + Init() + nowTime := time.Now().Format(config.DateTime) //评论时间记录 + comment := Comment{ + User_id: 20008, + Video_id: 1, + Comment_text: "user20008commentVideo1-2", + Create_date: nowTime, + Cancel: 0, + } + err := NewCommentDaoInstance().InsertComment(comment) + fmt.Printf("[%v]", err) +} + +//3、删除评论 的测试函数 +func TestDelComment(t *testing.T) { + Init() + err := NewCommentDaoInstance().DeleteComment(int64(8)) + fmt.Printf("[%v]", err) +} + +//4.根据视频id查询所属评论全部列表信息 的测试函数 +func TestCommentList(t *testing.T) { + Init() + list, err := NewCommentDaoInstance().GetCommentList(int64(1)) + fmt.Printf("%v\n", list) + fmt.Printf("[%v]", err) +} From 248d548c84108a981f72ce230c1b36214e29f7fc Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Sun, 22 May 2022 21:41:53 +0800 Subject: [PATCH 66/70] =?UTF-8?q?dev-20220519-video=20=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E9=93=BE=E6=8E=A5=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/videoDao.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dao/videoDao.go b/dao/videoDao.go index 1b64fed..eeaf487 100644 --- a/dao/videoDao.go +++ b/dao/videoDao.go @@ -28,7 +28,7 @@ func GetVideosByAuthorId(authorId int64) ([]TableVideo, error) { //建立结果集接收 var data []TableVideo //初始化db - Init() + //Init() result := Db.Where(&TableVideo{AuthorId: authorId}).Find(&data) //如果出现问题,返回对应到空,并且返回error if result.Error != nil { @@ -42,7 +42,7 @@ func GetVideosByAuthorId(authorId int64) ([]TableVideo, error) { func GetVideoByVideoId(videoId int64) (TableVideo, error) { var tableVideo TableVideo tableVideo.ID = videoId - Init() + //Init() result := Db.First(&tableVideo) if result.Error != nil { return tableVideo, result.Error @@ -55,7 +55,7 @@ func GetVideoByVideoId(videoId int64) (TableVideo, error) { // 依据一个时间,来获取这个时间之前的一些视频 func GetVideosByLastTime(lastTime time.Time) ([]TableVideo, error) { videos := make([]TableVideo, config.VideoCount) - Init() + //Init() result := Db.Where("publish_time Date: Mon, 23 May 2022 15:34:11 +0800 Subject: [PATCH 67/70] =?UTF-8?q?dev-20220523-like=20=E6=B3=A8=E9=87=8A?= =?UTF-8?q?=E4=BA=86likedao=E7=9A=84Init(),=E4=BB=A3=E7=A0=81=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E4=BA=86=E5=A4=A7=E9=87=8F=E6=B3=A8=E9=87=8A=EF=BC=8C?= =?UTF-8?q?=E9=87=8D=E6=96=B0=E4=BF=AE=E6=94=B9=E4=BA=86=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=E7=9A=84=E8=BE=93=E5=87=BA=E9=80=BB=E8=BE=91?= =?UTF-8?q?=EF=BC=8C=E5=90=8C=E6=97=B6service=E5=86=85=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E4=BA=86=E5=85=B6=E4=BB=96=E6=A8=A1=E5=9D=97=E9=9C=80=E8=A6=81?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E7=9A=84=E5=87=BD=E6=95=B0=E7=9A=84log.print?= =?UTF-8?q?f,control=E5=B1=82=E6=B7=BB=E5=8A=A0=E4=BA=86=E8=B5=9E=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E5=92=8C=E8=8E=B7=E5=8F=96=E7=82=B9=E8=B5=9E=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E7=9A=84log.printf?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/likeController.go | 11 +++++-- dao/LikeDao.go | 41 +++++++++++++++--------- service/likeServiceImpl.go | 61 +++++++++++++++++++++++++----------- 3 files changed, 78 insertions(+), 35 deletions(-) diff --git a/controller/likeController.go b/controller/likeController.go index 31ece77..4fbaa72 100644 --- a/controller/likeController.go +++ b/controller/likeController.go @@ -3,6 +3,7 @@ package controller import ( "TikTok/service" "github.com/gin-gonic/gin" + "log" "net/http" "strconv" ) @@ -27,12 +28,16 @@ func Favorite_Action(c *gin.Context) { action_type := c.Query("action_type") actiontype, _ := strconv.ParseInt(action_type, 10, 64) like := new(service.LikeServiceImpl) - if like.FavouriteAction(userid, videoid, int32(actiontype)) == nil { + //获取点赞或者取消赞操作的错误信息 + err := like.FavouriteAction(userid, videoid, int32(actiontype)) + if err == nil { + log.Printf("方法like.FavouriteAction(userid, videoid, int32(actiontype) 成功") c.JSON(http.StatusOK, likeResponse{ StatusCode: 0, StatusMsg: "favourite action success", }) } else { + log.Printf("方法like.FavouriteAction(userid, videoid, int32(actiontype) 失败:%v", err) c.JSON(http.StatusOK, likeResponse{ StatusCode: 1, StatusMsg: "favourite action fail", @@ -47,15 +52,17 @@ func GetFavouriteList(c *gin.Context) { like := GetVideo() videos, err := like.GetFavouriteList(userid) if err == nil { + log.Printf("方法like.GetFavouriteList(userid) 成功") c.JSON(http.StatusOK, GetFavouriteListResponse{ StatusCode: 0, StatusMsg: "get favouritelist success", Videolist: videos, }) } else { + log.Printf("方法like.GetFavouriteList(userid) 失败:%v", err) c.JSON(http.StatusOK, GetFavouriteListResponse{ StatusCode: 1, - StatusMsg: "can't find favouritelist ", + StatusMsg: "get favouritelist fail ", }) } } diff --git a/dao/LikeDao.go b/dao/LikeDao.go index 096d021..3320751 100644 --- a/dao/LikeDao.go +++ b/dao/LikeDao.go @@ -25,10 +25,12 @@ type LikeDao struct { var ( likeDao *LikeDao - likeOnce sync.Once + likeOnce sync.Once //用来保证某种行为只会被执行一次。 ) +//生成likedao单例实例; func NewLikeDaoInstance() *LikeDao { + //只执行一次,一个线程访问只返回同一个对象实例 likeOnce.Do( func() { likeDao = &LikeDao{} @@ -38,33 +40,41 @@ func NewLikeDaoInstance() *LikeDao { //1.根据videoid获取点赞数量 func (*LikeDao) GetLikeCount(videoId int64) (int64, error) { - Init() - var count int64 + var count int64 //点赞数量; + //查询likes表对应视频id点赞数量,返回查询结果 err := Db.Model(Like{}).Where(map[string]interface{}{"video_id": videoId, "cancel": config.Islike}). Count(&count).Error + //查询过程出现错误,返回默认值0,并输出错误信息 if err != nil { + log.Println(err.Error()) return 0, errors.New("An unknown exception occurred in the query") } else { + //没查询到或者查询到结果,返回数量以及无报错 return count, nil } } //2.根据userid,videoid,action_type点赞或者取消赞 func (*LikeDao) UpdateLike(userId int64, videoId int64, action_type int32) error { - Init() + //更新当前用户观看视频的点赞状态“cancel”,返回错误结果 err := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "video_id": videoId}). Update("cancel", action_type).Error + //如果出现错误,返回更新数据库失败 if err != nil { + log.Println(err.Error()) return errors.New("update data fail") } + //更新操作成功 return nil } //3、插入点赞数据 func (*LikeDao) InsertLike(likedata Like) error { - Init() + //创建点赞数据,默认为点赞,cancel为0,返回错误结果 err := Db.Model(Like{}).Create(&likedata).Error + //如果有错误结果,返回插入失败 if err != nil { + log.Println(err.Error()) return errors.New("insert data fail") } return nil @@ -72,37 +82,40 @@ func (*LikeDao) InsertLike(likedata Like) error { //4.根据userid,videoid查询点赞信息 func (*LikeDao) GetLikeInfo(userId int64, videoId int64) (Like, error) { - Init() + //创建一条空like结构体,用来存储查询到的信息 var likeInfo Like + //根据userid,videoid查询是否有该条信息,如果有,存储在likeInfo,返回查询结果 result := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "video_id": videoId}). First(&likeInfo) - //如果获取likeInfo失败 + //如果查询数据失败,返回获取likeInfo信息失败 if result.Error != nil { log.Println(result.Error.Error()) return likeInfo, errors.New("get likeInfo failed") } - //查询数据为0 + //查询数据为0,打印"can't find data",返回空结构体,这时候就应该要考虑是否插入这条数据了 if result.RowsAffected == 0 { - log.Println(result.Error.Error()) - return likeInfo, errors.New("can't find this data") + log.Println("can't find data") + return Like{}, nil } return likeInfo, nil } //5.根据userid查询所属点赞全部列表信息 func (*LikeDao) GetLikeList(userId int64) ([]Like, error) { - Init() + //创建likeList切片,用来存储查询到的当前用户点赞列表信息 var likeList []Like + //根据userid查询所有点赞视频信息,如果有,存储在likeList切片中,返回查询结果 result := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "cancel": config.Islike}). Find(&likeList) - //如果获取likelist失败 + //如果操作数据库失败,返回获取likelist失败 if result.Error != nil { log.Println(result.Error.Error()) return likeList, errors.New("get likeList failed") } - //查询数据为0 + //查询数据为0,返回空likeList切片,以及返回无错误 if result.RowsAffected == 0 { - return likeList, errors.New("there are no likes") + log.Println(errors.New("there are no likes")) + return likeList, nil } return likeList, nil } diff --git a/service/likeServiceImpl.go b/service/likeServiceImpl.go index bd20ab7..9cd1e51 100644 --- a/service/likeServiceImpl.go +++ b/service/likeServiceImpl.go @@ -11,45 +11,64 @@ type LikeServiceImpl struct { VideoService } +//根据userid,videoid查询点赞信息 func (like *LikeServiceImpl) IsFavourit(videoId int64, userId int64) (bool, error) { - //未查询到数据,返回未点赞; + //查询该点赞信息在数据库中是否存在 likedata, err := dao.NewLikeDaoInstance().GetLikeInfo(userId, videoId) + //如果有问题,说明操作数据库失败,返回默认未点赞,输出错误信息err:"get likeInfo failed" if err != nil { + log.Printf("方法GetLikeInfo(userId, videoId) 失败:%v", err) return false, err - } else { //查询到数据,根据Cancel值判断是否点赞; + } else { //查询数据为0或者查询到数据,根据Cancel值判断是否点赞; + log.Printf("方法GetLikeInfo(userId, videoId) 成功") if likedata.Cancel == config.Islike { return true, nil - } else { + } else { //查询数据为0或者cancel为Unlike return false, nil } } } +//根据videoid获取点赞数量 func (like *LikeServiceImpl) FavouriteCount(videoId int64) (int64, error) { - return dao.NewLikeDaoInstance().GetLikeCount(videoId) + //查询videoid对应点赞数量 + count, err := dao.NewLikeDaoInstance().GetLikeCount(videoId) + //如果有问题,说明操作数据库失败,返回默认0,返回错误信息err:"An unknown exception occurred in the query" + if err != nil { + log.Printf("方法GetLikeCount(videoId) 失败:%v", err) + return count, err + } + log.Printf("方法GetLikeCount(videoId) 成功") + return count, err } func (like *LikeServiceImpl) FavouriteAction(userId int64, videoId int64, action_type int32) error { + //如果查询没有数据,用来生成该条点赞信息,存储在likedata中 var likedata dao.Like - //先查询是否有这条数据。 - _, err := dao.NewLikeDaoInstance().GetLikeInfo(userId, videoId) - //点赞行为,否则取消赞 + //先查询是否有这条数据 + likeInfo, err := dao.NewLikeDaoInstance().GetLikeInfo(userId, videoId) + //点赞行为 if action_type == config.Likeaction { - //没查到这条数据,则新建这条数据,否则更新即可; + //如果有问题,说明查询数据库失败,返回错误信息err:"get likeInfo failed" if err != nil { - likedata.User_id = userId - likedata.Video_id = videoId - likedata.Cancel = config.Islike + return err + } else if likeInfo == (dao.Like{}) { //没查到这条数据,则新建这条数据; + likedata.User_id = userId //插入userid + likedata.Video_id = videoId //插入videoid + likedata.Cancel = config.Islike //插入点赞cancel=0 return dao.NewLikeDaoInstance().InsertLike(likedata) - } else { + } else { //查到这条数据,更新即可; return dao.NewLikeDaoInstance().UpdateLike(userId, videoId, config.Islike) } - } else { - //只有当前是点赞状态才能取消点赞这个行为,如果查询不到数据则返回错误; + } else { //取消赞行为,只有当前状态是点赞状态才会发起取消赞行为,所以如果查询到,必然是cancel==0(点赞) + //如果有问题,说明查询数据库失败,返回错误信息err:"get likeInfo failed" if err != nil { - log.Println(err.Error()) - return errors.New("can't find this data") + return err + } else if likeInfo == (dao.Like{}) { //只有当前是点赞状态才能取消点赞这个行为 + // 所以如果查询不到数据则返回错误,err:"can't find data,this action invalid",就不该有取消赞这个行为 + return errors.New("can't find data,this action invalid") } else { + //如果查询到数据,则更新为取消赞状态 return dao.NewLikeDaoInstance().UpdateLike(userId, videoId, config.Unlike) } } @@ -59,18 +78,22 @@ func (like *LikeServiceImpl) FavouriteAction(userId int64, videoId int64, action func (like *LikeServiceImpl) GetFavouriteList(userId int64) ([]Video, error) { //1.先查询点赞列表信息 likeList, err := dao.NewLikeDaoInstance().GetLikeList(userId) + //如果有问题,说明查询数据库失败,返回空和错误err:"get likeList failed" if err != nil { log.Println(err.Error()) return nil, err } - //提前定义好切片长度 + //提前定义好切片长度,生成集合 favorite_videolist := make([]Video, 0, len(likeList)) - //如果查询到数据,遍历video_id; + //如果查询成功,无论是否有数据,遍历likelist,获得其中的video_id; + //测试结构体,协同开发 //likesub := new(LikeSub) for _, likedata := range likeList { + //测试函数,协同开发 //video, err1 := likesub.GetVideo(likedata.Video_id,userId) + //调用video接口,Getvideo:根据videoid,当前用户id,返回video对象 video, err1 := like.GetVideo(likedata.Video_id, userId) - if err1 != nil { //如果没有获取这个video_id的视频,视频可能被删除了,跳过 + if err1 != nil { //如果没有获取这个video_id的视频,视频可能被删除了,抛出异常,并且跳过 log.Panicln(errors.New("can't find this favourite video")) continue } //将每个video对象添加到集合中去 From c30a4870a301d8a4f4179763ceb686d96f29ee55 Mon Sep 17 00:00:00 2001 From: lls <1412837463@qq.com> Date: Mon, 23 May 2022 17:07:16 +0800 Subject: [PATCH 68/70] =?UTF-8?q?dev-2022-5-23-follow=201-controller?= =?UTF-8?q?=E6=89=93=E6=88=90=E5=8A=9F=E6=97=A5=E5=BF=97=E3=80=82=202-?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93ErrNotFound=E5=88=A4=E6=96=AD?= =?UTF-8?q?=E8=B0=83=E6=95=B4=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/followController.go | 4 ++++ dao/FollowDao.go | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/controller/followController.go b/controller/followController.go index ea959ab..22d0bd5 100644 --- a/controller/followController.go +++ b/controller/followController.go @@ -4,6 +4,7 @@ import ( "TikTok/service" "fmt" "github.com/gin-gonic/gin" + "log" "net/http" "strconv" ) @@ -52,6 +53,7 @@ func RelationAction(c *gin.Context) { case 2 == actionType: fsi.DeleteFollowRelation(userId, toUserId) } + log.Println("关注、取关成功。") c.JSON(http.StatusOK, RelationActionResp{ Response{ StatusCode: 0, @@ -89,6 +91,7 @@ func GetFollowing(c *gin.Context) { return } // 成功获取到关注列表。 + log.Println("获取关注列表成功。") c.JSON(http.StatusOK, FollowingResp{ UserList: users, Response: Response{ @@ -127,6 +130,7 @@ func GetFollowers(c *gin.Context) { return } // 成功获取到粉丝列表。 + log.Println("获取粉丝列表成功。") c.JSON(http.StatusOK, FollowersResp{ Response: Response{ StatusCode: 0, diff --git a/dao/FollowDao.go b/dao/FollowDao.go index 4ce2424..b0fea10 100644 --- a/dao/FollowDao.go +++ b/dao/FollowDao.go @@ -123,7 +123,7 @@ func (*FollowDao) FindEverFollowing(userId int64, targetId int64) (*Follow, erro Where("cancel = ? or cancel = ?", 0, 1). Take(&follow).Error; nil != err { // 当没查到记录报错时,不当做错误处理。 - if gorm.IsRecordNotFoundError(err) { + if "record not found" == err.Error() { return nil, nil } log.Println(err.Error()) @@ -156,7 +156,7 @@ func (*FollowDao) GetFollowingIds(userId int64) ([]int64, error) { Where("follower_id = ?", userId). Pluck("user_id", &ids).Error; nil != err { // 没有关注任何人,但是不能算错。 - if gorm.IsRecordNotFoundError(err) { + if "record not found" == err.Error() { return nil, nil } // 查询出错。 @@ -176,7 +176,7 @@ func (*FollowDao) GetFollowersIds(userId int64) ([]int64, error) { Where("cancel = ?", 0). Pluck("follower_id", &ids).Error; nil != err { // 没有粉丝,但是不能算错。 - if gorm.IsRecordNotFoundError(err) { + if "record not found" == err.Error() { return nil, nil } // 查询出错。 From e92681c59b81676c7df5fb08f9429016bb206ed5 Mon Sep 17 00:00:00 2001 From: lzz <1245314855@qq.com> Date: Mon, 23 May 2022 20:02:27 +0800 Subject: [PATCH 69/70] =?UTF-8?q?dev-20220523-like=20=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E6=9F=A5=E8=AF=A2=E8=AE=B0=E5=BD=95=E4=B8=BA0?= =?UTF-8?q?=EF=BC=8C=E8=BF=94=E5=9B=9E=E8=B0=83=E6=95=B4=EF=BC=9Blike.getv?= =?UTF-8?q?ideo()=E6=9C=AA=E8=8E=B7=E5=BE=97=E8=BF=94=E5=9B=9E=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E5=A4=84=E7=90=86=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/LikeDao.go | 46 ++++++++++++++++++++------------------ service/likeServiceImpl.go | 32 ++++++++++++++------------ 2 files changed, 42 insertions(+), 36 deletions(-) diff --git a/dao/LikeDao.go b/dao/LikeDao.go index 3320751..9658ccf 100644 --- a/dao/LikeDao.go +++ b/dao/LikeDao.go @@ -85,17 +85,18 @@ func (*LikeDao) GetLikeInfo(userId int64, videoId int64) (Like, error) { //创建一条空like结构体,用来存储查询到的信息 var likeInfo Like //根据userid,videoid查询是否有该条信息,如果有,存储在likeInfo,返回查询结果 - result := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "video_id": videoId}). - First(&likeInfo) - //如果查询数据失败,返回获取likeInfo信息失败 - if result.Error != nil { - log.Println(result.Error.Error()) - return likeInfo, errors.New("get likeInfo failed") - } - //查询数据为0,打印"can't find data",返回空结构体,这时候就应该要考虑是否插入这条数据了 - if result.RowsAffected == 0 { - log.Println("can't find data") - return Like{}, nil + err := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "video_id": videoId}). + First(&likeInfo).Error + if err != nil { + //查询数据为0,打印"can't find data",返回空结构体,这时候就应该要考虑是否插入这条数据了 + if "record not found" == err.Error() { + log.Println("can't find data") + return Like{}, nil + } else { + //如果查询数据库失败,返回获取likeInfo信息失败 + log.Println(err.Error()) + return likeInfo, errors.New("get likeInfo failed") + } } return likeInfo, nil } @@ -105,17 +106,18 @@ func (*LikeDao) GetLikeList(userId int64) ([]Like, error) { //创建likeList切片,用来存储查询到的当前用户点赞列表信息 var likeList []Like //根据userid查询所有点赞视频信息,如果有,存储在likeList切片中,返回查询结果 - result := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "cancel": config.Islike}). - Find(&likeList) - //如果操作数据库失败,返回获取likelist失败 - if result.Error != nil { - log.Println(result.Error.Error()) - return likeList, errors.New("get likeList failed") - } - //查询数据为0,返回空likeList切片,以及返回无错误 - if result.RowsAffected == 0 { - log.Println(errors.New("there are no likes")) - return likeList, nil + err := Db.Model(Like{}).Where(map[string]interface{}{"user_id": userId, "cancel": config.Islike}). + Find(&likeList).Error + if err != nil { + //查询数据为0,返回空likeList切片,以及返回无错误 + if "record not found" == err.Error() { + log.Println("there are no likes") + return likeList, nil + } else { + //如果查询数据库失败,返回获取likelist失败 + log.Println(err.Error()) + return likeList, errors.New("get likeList failed") + } } return likeList, nil } diff --git a/service/likeServiceImpl.go b/service/likeServiceImpl.go index 9cd1e51..479e373 100644 --- a/service/likeServiceImpl.go +++ b/service/likeServiceImpl.go @@ -52,24 +52,28 @@ func (like *LikeServiceImpl) FavouriteAction(userId int64, videoId int64, action //如果有问题,说明查询数据库失败,返回错误信息err:"get likeInfo failed" if err != nil { return err - } else if likeInfo == (dao.Like{}) { //没查到这条数据,则新建这条数据; - likedata.User_id = userId //插入userid - likedata.Video_id = videoId //插入videoid - likedata.Cancel = config.Islike //插入点赞cancel=0 - return dao.NewLikeDaoInstance().InsertLike(likedata) - } else { //查到这条数据,更新即可; - return dao.NewLikeDaoInstance().UpdateLike(userId, videoId, config.Islike) + } else { + if likeInfo == (dao.Like{}) { //没查到这条数据,则新建这条数据; + likedata.User_id = userId //插入userid + likedata.Video_id = videoId //插入videoid + likedata.Cancel = config.Islike //插入点赞cancel=0 + return dao.NewLikeDaoInstance().InsertLike(likedata) + } else { //查到这条数据,更新即可; + return dao.NewLikeDaoInstance().UpdateLike(userId, videoId, config.Islike) + } } } else { //取消赞行为,只有当前状态是点赞状态才会发起取消赞行为,所以如果查询到,必然是cancel==0(点赞) //如果有问题,说明查询数据库失败,返回错误信息err:"get likeInfo failed" if err != nil { return err - } else if likeInfo == (dao.Like{}) { //只有当前是点赞状态才能取消点赞这个行为 - // 所以如果查询不到数据则返回错误,err:"can't find data,this action invalid",就不该有取消赞这个行为 - return errors.New("can't find data,this action invalid") } else { - //如果查询到数据,则更新为取消赞状态 - return dao.NewLikeDaoInstance().UpdateLike(userId, videoId, config.Unlike) + if likeInfo == (dao.Like{}) { //只有当前是点赞状态才能取消点赞这个行为 + // 所以如果查询不到数据则返回错误,err:"can't find data,this action invalid",就不该有取消赞这个行为 + return errors.New("can't find data,this action invalid") + } else { + //如果查询到数据,则更新为取消赞状态 + return dao.NewLikeDaoInstance().UpdateLike(userId, videoId, config.Unlike) + } } } return nil @@ -93,8 +97,8 @@ func (like *LikeServiceImpl) GetFavouriteList(userId int64) ([]Video, error) { //video, err1 := likesub.GetVideo(likedata.Video_id,userId) //调用video接口,Getvideo:根据videoid,当前用户id,返回video对象 video, err1 := like.GetVideo(likedata.Video_id, userId) - if err1 != nil { //如果没有获取这个video_id的视频,视频可能被删除了,抛出异常,并且跳过 - log.Panicln(errors.New("can't find this favourite video")) + if err1 != nil { //如果没有获取这个video_id的视频,视频可能被删除了,打印异常,并且跳过 + log.Println(errors.New("can't find this favourite video")) continue } //将每个video对象添加到集合中去 favorite_videolist = append(favorite_videolist, video) From d5917e73621bc81bf374a3d9e554760b7ba300fb Mon Sep 17 00:00:00 2001 From: siyixiong <18552541076@163.com> Date: Mon, 23 May 2022 22:40:09 +0800 Subject: [PATCH 70/70] =?UTF-8?q?dev-20220523-user=20=E6=B3=A8=E9=87=8A?= =?UTF-8?q?=E6=8E=89UserDao=E9=87=8C=E9=9D=A2=E6=8E=89Init()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dao/UserDao.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dao/UserDao.go b/dao/UserDao.go index 4b53237..45270e0 100644 --- a/dao/UserDao.go +++ b/dao/UserDao.go @@ -38,7 +38,7 @@ func NewUserDaoInstance() *UserDao { // GetTableUserList 获取全部TableUser对象 func (*UserDao) GetTableUserList() ([]TableUser, error) { tableUsers := []TableUser{} - Init() + //Init() if err := Db.Find(&tableUsers).Error; err != nil { log.Println(err.Error()) return tableUsers, err @@ -49,7 +49,7 @@ func (*UserDao) GetTableUserList() ([]TableUser, error) { // GetTableUserByUsername 根据username获得TableUser对象 func (*UserDao) GetTableUserByUsername(name string) (TableUser, error) { tableUser := TableUser{} - Init() + //Init() if err := Db.Where("name = ?", name).First(&tableUser).Error; err != nil { log.Println(err.Error()) return tableUser, err @@ -60,7 +60,7 @@ func (*UserDao) GetTableUserByUsername(name string) (TableUser, error) { // GetTableUserById 根据user_id获得TableUser对象 func (*UserDao) GetTableUserById(id int64) (TableUser, error) { tableUser := TableUser{} - Init() + //Init() if err := Db.Where("id = ?", id).First(&tableUser).Error; err != nil { log.Println(err.Error()) return tableUser, err @@ -70,7 +70,7 @@ func (*UserDao) GetTableUserById(id int64) (TableUser, error) { // InsertTableUser 将tableUser插入表内 func (*UserDao) InsertTableUser(tableUser *TableUser) bool { - Init() + //Init() if err := Db.Create(&tableUser).Error; err != nil { log.Println(err.Error()) return false