From c5711e13e0896deefc3f617d687ac47fa044b9d0 Mon Sep 17 00:00:00 2001 From: yangfeng <1719957182@qq.com> Date: Wed, 23 Aug 2023 17:07:21 +0800 Subject: [PATCH 01/16] feat: update .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 9bfd2ab..b69b8de 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ debug/ output/ log/ .env -docker/static \ No newline at end of file +docker/static +static/ \ No newline at end of file From 8cc15f02cff2637d6c3e1d5d331d9b7972e980bb Mon Sep 17 00:00:00 2001 From: XFFFCCCC Date: Wed, 23 Aug 2023 02:48:26 -0700 Subject: [PATCH 02/16] modify message --- src/services/message/handler.go | 41 +++++++++++++++++---------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/src/services/message/handler.go b/src/services/message/handler.go index 1da90e4..61d96a4 100644 --- a/src/services/message/handler.go +++ b/src/services/message/handler.go @@ -14,7 +14,6 @@ import ( "fmt" "github.com/sirupsen/logrus" - "go.opentelemetry.io/otel/trace" ) var UserClient user.UserServiceClient @@ -47,8 +46,11 @@ func (c MessageServiceImpl) ChatAction(ctx context.Context, request *chat.Action if err != nil || userResponse.StatusCode != strings.ServiceOKCode { logger.WithFields(logrus.Fields{ - "err": err, - "cctor_id": request.ActorId, + "err": err, + "ActorId": request.ActorId, + "user_id": request.UserId, + "action_type": request.ActionType, + "content_text": request.Content, }).Errorf("User service error") logging.SetSpanError(span, err) @@ -58,12 +60,14 @@ func (c MessageServiceImpl) ChatAction(ctx context.Context, request *chat.Action }, err } - res, err = addMessage(ctx, logger, span, request.ActorId, request.UserId, request.Content) + res, err = addMessage(ctx, request.ActorId, request.UserId, request.Content) if err != nil { logger.WithFields(logrus.Fields{ - "err": err, - "ActorId": request.ActorId, - }).Errorf("User service error") + "err": err, + "user_id": request.UserId, + "action_type": request.ActionType, + "content_text": request.Content, + }).Errorf("database insert error") logging.SetSpanError(span, err) return res, err } @@ -81,8 +85,9 @@ func (c MessageServiceImpl) Chat(ctx context.Context, request *chat.ChatRequest) defer span.End() logger := logging.LogService("ChatService.chat").WithContext(ctx) logger.WithFields(logrus.Fields{ - "user_id": request.UserId, - "ActorId": request.ActorId, + "user_id": request.UserId, + "ActorId": request.ActorId, + "pre_msg_time": request.PreMsgTime, }).Debugf("Process start") toUserId := request.UserId fromUserId := request.ActorId @@ -96,13 +101,16 @@ func (c MessageServiceImpl) Chat(ctx context.Context, request *chat.ChatRequest) //TO DO 看怎么需要一下 var rMessageList []*chat.Message - result := database.Client.WithContext(ctx).Where("conversation_id=?", conversationId). + result := database.Client.WithContext(ctx).Where("conversation_id=? and ", conversationId). Order("created_at desc").Find(&rMessageList) if result.Error != nil { logger.WithFields(logrus.Fields{ - "err": result.Error, - }).Errorf("ChatServiceImpl list chat failed to response when listing message") + "err": result.Error, + "user_id": request.UserId, + "ActorId": request.ActorId, + "pre_msg_time": request.PreMsgTime, + }).Errorf("ChatServiceImpl list chat failed to response when listing message,database err") logging.SetSpanError(span, err) resp = &chat.ChatResponse{ @@ -125,7 +133,7 @@ func (c MessageServiceImpl) Chat(ctx context.Context, request *chat.ChatRequest) return } -func addMessage(ctx context.Context, logger *logrus.Entry, span trace.Span, fromUserId uint32, toUserId uint32, Context string) (resp *chat.ActionResponse, err error) { +func addMessage(ctx context.Context, fromUserId uint32, toUserId uint32, Context string) (resp *chat.ActionResponse, err error) { conversationId := fmt.Sprintf("%d_%d", toUserId, fromUserId) if toUserId > fromUserId { @@ -142,13 +150,6 @@ func addMessage(ctx context.Context, logger *logrus.Entry, span trace.Span, from result := database.Client.WithContext(ctx).Create(&message) if result.Error != nil { - //TO_DO 错误 替换 - logger.WithFields(logrus.Fields{ - "err": result.Error, - "id": message.ID, - "ActorId": message.FromUserId, - "to_id": message.ToUserId, - }).Errorf("send message failed when insert to database") resp = &chat.ActionResponse{ StatusCode: strings.UnableToAddMessageErrorCode, From 7ab35e2f813ca1308e186854a80b8eb765e401dd Mon Sep 17 00:00:00 2001 From: EpicMo <1982742309@qq.com> Date: Wed, 23 Aug 2023 18:28:41 +0800 Subject: [PATCH 03/16] feat: Dockerfile & authenticate.go --- .gitignore | 3 ++- docker/{ => basic}/Dockerfile | 0 docker/rabbitmq/Dockerfile | 3 +++ src/web/middleware/authenticate.go | 8 +++++++- 4 files changed, 12 insertions(+), 2 deletions(-) rename docker/{ => basic}/Dockerfile (100%) create mode 100644 docker/rabbitmq/Dockerfile diff --git a/.gitignore b/.gitignore index 9bfd2ab..e03c60e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ debug/ output/ log/ .env -docker/static \ No newline at end of file +docker/basic/static +docker/rabbitmq/static \ No newline at end of file diff --git a/docker/Dockerfile b/docker/basic/Dockerfile similarity index 100% rename from docker/Dockerfile rename to docker/basic/Dockerfile diff --git a/docker/rabbitmq/Dockerfile b/docker/rabbitmq/Dockerfile new file mode 100644 index 0000000..93d0c19 --- /dev/null +++ b/docker/rabbitmq/Dockerfile @@ -0,0 +1,3 @@ +FROM rabbitmq:3.12.3-management + +COPY ./static /plugins \ No newline at end of file diff --git a/src/web/middleware/authenticate.go b/src/web/middleware/authenticate.go index c70b5f2..a39fba0 100644 --- a/src/web/middleware/authenticate.go +++ b/src/web/middleware/authenticate.go @@ -23,7 +23,13 @@ func TokenAuthMiddleware() gin.HandlerFunc { return } - token := c.Query("token") + var token string + if c.Request.URL.Path == "/douyin/publish/action/" { + token = c.PostForm("token") + } else { + token = c.Query("token") + } + ctx, span := tracing.Tracer.Start(c.Request.Context(), "AuthMiddleWare") defer span.End() span.SetAttributes(attribute.String("token", token)) From f1f81274afb56fcee009355dc828392040eb9abb Mon Sep 17 00:00:00 2001 From: EpicMo <1982742309@qq.com> Date: Wed, 23 Aug 2023 18:46:48 +0800 Subject: [PATCH 04/16] fix: like -> favorite --- src/constant/config/service.go | 3 --- src/services/favorite/main.go | 14 +++++++------- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/constant/config/service.go b/src/constant/config/service.go index 1a15cc8..813ad14 100644 --- a/src/constant/config/service.go +++ b/src/constant/config/service.go @@ -27,7 +27,4 @@ const MessageRpcServerPort = ":37007" const RelationRpcServerName = "GuGoTik-RelationService" const RelationRpcServerPort = ":37008" -const LikeRpcServerName = "GuGoTik-likeService" -const LikeRpcServerPort = ":37009" - const VideoPicker = "GuGoTik-VideoPicker" diff --git a/src/services/favorite/main.go b/src/services/favorite/main.go index 3566a41..be135a6 100644 --- a/src/services/favorite/main.go +++ b/src/services/favorite/main.go @@ -18,7 +18,7 @@ import ( ) func main() { - tp, err := tracing.SetTraceProvider(config.LikeRpcServerName) + tp, err := tracing.SetTraceProvider(config.FavoriteRpcServerName) if err != nil { logging.Logger.WithFields(logrus.Fields{ @@ -40,12 +40,12 @@ func main() { grpc.UnaryInterceptor(otelgrpc.UnaryServerInterceptor()), ) - log := logging.LogService(config.LikeRpcServerName) + log := logging.LogService(config.FavoriteRpcServerName) - lis, err := net.Listen("tcp", config.LikeRpcServerPort) + lis, err := net.Listen("tcp", config.FavoriteRpcServerPort) if err != nil { - log.Panicf("Rpc %s listen happens error: %v", config.LikeRpcServerName, err) + log.Panicf("Rpc %s listen happens error: %v", config.FavoriteRpcServerName, err) } var srv FavoriteServiceServerImpl @@ -55,12 +55,12 @@ func main() { health.RegisterHealthServer(s, &probe) - if err := consul.RegisterConsul(config.LikeRpcServerName, config.LikeRpcServerPort); err != nil { - log.Panicf("Rpc %s register consul happens error for: %v", config.LikeRpcServerName, err) + if err := consul.RegisterConsul(config.FavoriteRpcServerName, config.FavoriteRpcServerPort); err != nil { + log.Panicf("Rpc %s register consul happens error for: %v", config.FavoriteRpcServerName, err) } srv.New() - log.Infof("Rpc %s is running at %s now", config.LikeRpcServerName, config.LikeRpcServerPort) + log.Infof("Rpc %s is running at %s now", config.FavoriteRpcServerName, config.FavoriteRpcServerPort) if err := s.Serve(lis); err != nil { log.Panicf("Rpc %s listen happens error for: %v", config.FavoriteRpcServerName, err) } From 538cd27dfae1522323e989e869094ef9bd9493be Mon Sep 17 00:00:00 2001 From: EpicMo <1982742309@qq.com> Date: Wed, 23 Aug 2023 19:05:32 +0800 Subject: [PATCH 05/16] fix: ut & user's service name --- src/web/user/handler.go | 3 +-- test/rpc/like_test.go | 2 +- test/rpc/userrpc_test.go | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/web/user/handler.go b/src/web/user/handler.go index ec2e055..3dc81ec 100644 --- a/src/web/user/handler.go +++ b/src/web/user/handler.go @@ -16,9 +16,8 @@ import ( var userClient user.UserServiceClient func init() { - userConn := grpc2.Connect(config.RelationRpcServerName) + userConn := grpc2.Connect(config.UserRpcServerName) userClient = user.NewUserServiceClient(userConn) - } func UserHandler(c *gin.Context) { diff --git a/test/rpc/like_test.go b/test/rpc/like_test.go index e49a0c1..ac286e4 100644 --- a/test/rpc/like_test.go +++ b/test/rpc/like_test.go @@ -15,7 +15,7 @@ import ( var likeClient favorite.FavoriteServiceClient func setups1() { - conn, _ := grpc.Dial(fmt.Sprintf("127.0.0.1%s", config.LikeRpcServerPort), + conn, _ := grpc.Dial(fmt.Sprintf("127.0.0.1%s", config.FavoriteRpcServerPort), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`)) likeClient = favorite.NewFavoriteServiceClient(conn) diff --git a/test/rpc/userrpc_test.go b/test/rpc/userrpc_test.go index 4c28ea9..2bc46c8 100644 --- a/test/rpc/userrpc_test.go +++ b/test/rpc/userrpc_test.go @@ -20,7 +20,7 @@ func TestGetUserInfo(t *testing.T) { Client = user.NewUserServiceClient(conn) res, err := Client.GetUserInfo(context.Background(), &user.UserRequest{ UserId: 2, - ActorId: 0, + ActorId: 1, }) assert.Empty(t, err) assert.Equal(t, int32(0), res.StatusCode) From 3e221dff795577cd71d4d7e449fd8fac401ea7a9 Mon Sep 17 00:00:00 2001 From: yangfeng <1719957182@qq.com> Date: Wed, 23 Aug 2023 19:05:55 +0800 Subject: [PATCH 06/16] feat: update .gitignore --- .gitignore | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index b69b8de..9bfd2ab 100644 --- a/.gitignore +++ b/.gitignore @@ -3,5 +3,4 @@ debug/ output/ log/ .env -docker/static -static/ \ No newline at end of file +docker/static \ No newline at end of file From 086ea506a265665118d7c53a14cea2370378f6ee Mon Sep 17 00:00:00 2001 From: EpicMo <1982742309@qq.com> Date: Wed, 23 Aug 2023 19:24:25 +0800 Subject: [PATCH 07/16] fix: relation query field --- src/services/user/handler.go | 63 +++++++++++++++++++++++++++++++++++- src/web/models/Relation.go | 2 +- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/services/user/handler.go b/src/services/user/handler.go index a95c098..ba888f3 100644 --- a/src/services/user/handler.go +++ b/src/services/user/handler.go @@ -5,6 +5,7 @@ import ( "GuGoTik/src/constant/strings" "GuGoTik/src/extra/tracing" "GuGoTik/src/models" + "GuGoTik/src/rpc/favorite" "GuGoTik/src/rpc/publish" "GuGoTik/src/rpc/relation" "GuGoTik/src/rpc/user" @@ -25,12 +26,17 @@ var relationClient relation.RelationServiceClient var publishClient publish.PublishServiceClient +var favoriteClient favorite.FavoriteServiceClient + func (a UserServiceImpl) New() { relationConn := grpc2.Connect(config.RelationRpcServerName) relationClient = relation.NewRelationServiceClient(relationConn) publishConn := grpc2.Connect(config.PublishRpcServerName) publishClient = publish.NewPublishServiceClient(publishConn) + + favoriteConn := grpc2.Connect(config.FavoriteRpcServerName) + favoriteClient = favorite.NewFavoriteServiceClient(favoriteConn) } func (a UserServiceImpl) GetUserInfo(ctx context.Context, request *user.UserRequest) (resp *user.UserResponse, err error) { @@ -82,7 +88,7 @@ func (a UserServiceImpl) GetUserInfo(ctx context.Context, request *user.UserRequ } var wg sync.WaitGroup - wg.Add(4) + wg.Add(6) isErr := false go func() { @@ -192,6 +198,61 @@ func (a UserServiceImpl) GetUserInfo(ctx context.Context, request *user.UserRequ resp.User.WorkCount = &rResp.Count }() + go func() { + defer wg.Done() + rResp, err := favoriteClient.CountUserTotalFavorited(ctx, &favorite.CountUserTotalFavoritedRequest{ + ActorId: request.ActorId, + UserId: request.UserId, + }) + if err != nil { + logger.WithFields(logrus.Fields{ + "err": err, + "userId": request.UserId, + }).Errorf("Error when user service get toal favorited") + isErr = true + return + } + + if rResp != nil && rResp.StatusCode == strings.ServiceOKCode { + if err != nil { + logger.WithFields(logrus.Fields{ + "errMsg": rResp.StatusMsg, + "userId": request.UserId, + }).Errorf("Error when user service get toal favorited") + isErr = true + return + } + } + + resp.User.TotalFavorited = &rResp.Count + }() + + go func() { + defer wg.Done() + rResp, err := favoriteClient.CountUserFavorite(ctx, &favorite.CountUserFavoriteRequest{UserId: request.UserId}) + if err != nil { + logger.WithFields(logrus.Fields{ + "err": err, + "userId": request.UserId, + }).Errorf("Error when user service get favorite") + isErr = true + return + } + + if rResp != nil && rResp.StatusCode == strings.ServiceOKCode { + if err != nil { + logger.WithFields(logrus.Fields{ + "errMsg": rResp.StatusMsg, + "userId": request.UserId, + }).Errorf("Error when user service get favorite") + isErr = true + return + } + } + + resp.User.FavoriteCount = &rResp.Count + }() + wg.Wait() if isErr { diff --git a/src/web/models/Relation.go b/src/web/models/Relation.go index 91e0439..dcc82e3 100644 --- a/src/web/models/Relation.go +++ b/src/web/models/Relation.go @@ -12,7 +12,7 @@ import "GuGoTik/src/rpc/user" type RelationActionReq struct { Token string `form:"token" binding:"required"` ActorId int `form:"actor_id"` - UserId int `form:"user_id"` + UserId int `form:"to_user_id"` ActionType int `form:"action_type" binding:"required"` } From 2248595fc756b0b3d565822d864462b4de4ab271 Mon Sep 17 00:00:00 2001 From: EpicMo <1982742309@qq.com> Date: Wed, 23 Aug 2023 19:27:39 +0800 Subject: [PATCH 08/16] fix: auth abort --- src/web/middleware/authenticate.go | 1 + 1 file changed, 1 insertion(+) diff --git a/src/web/middleware/authenticate.go b/src/web/middleware/authenticate.go index a39fba0..32449d9 100644 --- a/src/web/middleware/authenticate.go +++ b/src/web/middleware/authenticate.go @@ -45,6 +45,7 @@ func TokenAuthMiddleware() gin.HandlerFunc { "status_code": strings.GateWayErrorCode, "status_msg": strings.GateWayError, }) + c.Abort() return } From 0283e89b0eb3613c5bc629967e4a9f1b7725a574 Mon Sep 17 00:00:00 2001 From: yangfeng <1719957182@qq.com> Date: Wed, 23 Aug 2023 22:14:39 +0800 Subject: [PATCH 09/16] fix: use custom json marshal to rpc response --- src/web/auth/handler.go | 9 +++++---- src/web/comment/handler.go | 13 +++++++------ src/web/favorite/handler.go | 9 +++++---- src/web/feed/handler.go | 3 ++- src/web/message/handler.go | 9 +++++---- src/web/publish/handler.go | 9 +++++---- src/web/relation/handler.go | 37 +++++++++++++++++++------------------ src/web/user/handler.go | 5 +++-- src/web/utils/json.go | 29 +++++++++++++++++++++++++++++ 9 files changed, 80 insertions(+), 43 deletions(-) create mode 100644 src/web/utils/json.go diff --git a/src/web/auth/handler.go b/src/web/auth/handler.go index 8f4ec90..df0eb96 100644 --- a/src/web/auth/handler.go +++ b/src/web/auth/handler.go @@ -8,6 +8,7 @@ import ( grpc2 "GuGoTik/src/utils/grpc" "GuGoTik/src/utils/logging" "GuGoTik/src/web/models" + "GuGoTik/src/web/utils" "github.com/gin-gonic/gin" _ "github.com/mbobakov/grpc-consul-resolver" "github.com/sirupsen/logrus" @@ -40,7 +41,7 @@ func LoginHandle(c *gin.Context) { logger.WithFields(logrus.Fields{ "Username": req.UserName, }).Warnf("Error when trying to connect with AuthService") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -50,7 +51,7 @@ func LoginHandle(c *gin.Context) { "UserId": res.UserId, }).Infof("User log in") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func RegisterHandle(c *gin.Context) { @@ -77,7 +78,7 @@ func RegisterHandle(c *gin.Context) { logger.WithFields(logrus.Fields{ "Username": req.UserName, }).Warnf("Error when trying to connect with AuthService") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -87,7 +88,7 @@ func RegisterHandle(c *gin.Context) { "UserId": res.UserId, }).Infof("User register in") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func init() { diff --git a/src/web/comment/handler.go b/src/web/comment/handler.go index 7f6d3d9..44af34a 100644 --- a/src/web/comment/handler.go +++ b/src/web/comment/handler.go @@ -8,6 +8,7 @@ import ( grpc2 "GuGoTik/src/utils/grpc" "GuGoTik/src/utils/logging" "GuGoTik/src/web/models" + "GuGoTik/src/web/utils" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "net/http" @@ -57,7 +58,7 @@ func ActionCommentHandler(c *gin.Context) { "video_id": req.VideoId, "actor_id": req.ActorId, }).Warnf("Error when trying to connect with ActionCommentService") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -66,7 +67,7 @@ func ActionCommentHandler(c *gin.Context) { "actor_id": req.ActorId, }).Infof("Action comment success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func ListCommentHandler(c *gin.Context) { @@ -92,7 +93,7 @@ func ListCommentHandler(c *gin.Context) { "video_id": req.VideoId, "actor_id": req.ActorId, }).Warnf("Error when trying to connect with ListCommentService") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -101,7 +102,7 @@ func ListCommentHandler(c *gin.Context) { "actor_id": req.ActorId, }).Infof("List comment success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func CountCommentHandler(c *gin.Context) { @@ -127,7 +128,7 @@ func CountCommentHandler(c *gin.Context) { "video_id": req.VideoId, "actor_id": req.ActorId, }).Warnf("Error when trying to connect with CountCommentService") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -136,5 +137,5 @@ func CountCommentHandler(c *gin.Context) { "actor_id": req.ActorId, }).Infof("Count comment success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } diff --git a/src/web/favorite/handler.go b/src/web/favorite/handler.go index 36b3cfd..efe1e53 100644 --- a/src/web/favorite/handler.go +++ b/src/web/favorite/handler.go @@ -8,6 +8,7 @@ import ( grpc2 "GuGoTik/src/utils/grpc" "GuGoTik/src/utils/logging" "GuGoTik/src/web/models" + "GuGoTik/src/web/utils" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "net/http" @@ -47,7 +48,7 @@ func ActionFavoriteHandler(c *gin.Context) { "VideoId": req.VideoId, "ActionType": req.ActionType, }).Warnf("Error when trying to connect with ActionFavoriteService") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -57,7 +58,7 @@ func ActionFavoriteHandler(c *gin.Context) { "ActionType": req.ActionType, }).Infof("Action favorite success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func ListFavoriteHandler(c *gin.Context) { @@ -83,7 +84,7 @@ func ListFavoriteHandler(c *gin.Context) { "ActorId": req.ActorId, "UserId": req.UserId, }).Warnf("Error when trying to connect with ListFavoriteHandler") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -92,5 +93,5 @@ func ListFavoriteHandler(c *gin.Context) { "UserId": req.UserId, }).Infof("List favorite videos success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } diff --git a/src/web/feed/handler.go b/src/web/feed/handler.go index 4a3007c..a679a43 100644 --- a/src/web/feed/handler.go +++ b/src/web/feed/handler.go @@ -8,6 +8,7 @@ import ( grpc2 "GuGoTik/src/utils/grpc" "GuGoTik/src/utils/logging" "GuGoTik/src/web/models" + "GuGoTik/src/web/utils" "github.com/gin-gonic/gin" _ "github.com/mbobakov/grpc-consul-resolver" "github.com/sirupsen/logrus" @@ -56,7 +57,7 @@ func ListVideosHandle(c *gin.Context) { "LatestTime": latestTime, "res": res, }).Infof("Feed List videos") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func init() { diff --git a/src/web/message/handler.go b/src/web/message/handler.go index a3eaabf..e040288 100644 --- a/src/web/message/handler.go +++ b/src/web/message/handler.go @@ -8,6 +8,7 @@ import ( grpc2 "GuGoTik/src/utils/grpc" "GuGoTik/src/utils/logging" "GuGoTik/src/web/models" + "GuGoTik/src/web/utils" "net/http" @@ -59,7 +60,7 @@ func ActionMessageHandler(c *gin.Context) { "content": req.Content, }).Error("Error when trying to connect with ActionMessageHandler") - c.JSON(http.StatusBadRequest, res) + c.Render(http.StatusBadRequest, utils.CustomJSON{Data: res, Context: c}) return } logger.WithFields(logrus.Fields{ @@ -67,7 +68,7 @@ func ActionMessageHandler(c *gin.Context) { "content": req.Content, }).Infof("Action send message success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func ListMessageHandler(c *gin.Context) { @@ -95,7 +96,7 @@ func ListMessageHandler(c *gin.Context) { "ActorId": req.ActorId, "user_id": req.UserId, }).Error("Error when trying to connect with ListMessageHandler") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -104,5 +105,5 @@ func ListMessageHandler(c *gin.Context) { "user_id": req.UserId, }).Infof("List comment success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } diff --git a/src/web/publish/handler.go b/src/web/publish/handler.go index c5b82e8..f008789 100644 --- a/src/web/publish/handler.go +++ b/src/web/publish/handler.go @@ -8,6 +8,7 @@ import ( grpc2 "GuGoTik/src/utils/grpc" "GuGoTik/src/utils/logging" "GuGoTik/src/web/models" + "GuGoTik/src/web/utils" "fmt" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" @@ -43,7 +44,7 @@ func ListPublishHandle(c *gin.Context) { logger.WithFields(logrus.Fields{ "UserId": req.UserId, }).Warnf("Error when trying to connect with PublishService") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } userId := req.UserId @@ -51,7 +52,7 @@ func ListPublishHandle(c *gin.Context) { "UserId": userId, }).Infof("Publish List videos") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func paramValidate(c *gin.Context) (err error) { @@ -135,11 +136,11 @@ func ActionPublishHandle(c *gin.Context) { logger.WithFields(logrus.Fields{ "err": err, }).Warnf("Error when trying to connect with CreateVideoService") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } logger.WithFields(logrus.Fields{ "response": res, }).Debugf("Create video success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } diff --git a/src/web/relation/handler.go b/src/web/relation/handler.go index f32b57a..658d6a3 100644 --- a/src/web/relation/handler.go +++ b/src/web/relation/handler.go @@ -8,6 +8,7 @@ import ( grpc2 "GuGoTik/src/utils/grpc" "GuGoTik/src/utils/logging" "GuGoTik/src/web/models" + "GuGoTik/src/web/utils" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "net/http" @@ -55,7 +56,7 @@ func ActionRelationHandler(c *gin.Context) { "actor_id": req.ActorId, "user_id": req.UserId, }).Warnf("RelationActionService returned an error response: %v", err) - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -64,7 +65,7 @@ func ActionRelationHandler(c *gin.Context) { "user_id": req.UserId, }).Infof("RelationAction success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func FollowHandler(c *gin.Context) { @@ -92,7 +93,7 @@ func FollowHandler(c *gin.Context) { "actor_id": req.ActorId, "user_id": req.UserId, }).Warnf("FollowService returned an error response: %v", err) - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -101,7 +102,7 @@ func FollowHandler(c *gin.Context) { "user_id": req.UserId, }).Infof("Follow success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } @@ -129,7 +130,7 @@ func UnfollowHandler(c *gin.Context) { "actor_id": req.ActorId, "user_id": req.UserId, }).Warnf("UnFollowService returned an error response: %v", err) - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -138,7 +139,7 @@ func UnfollowHandler(c *gin.Context) { "user_id": req.UserId, }).Infof("Unfollow success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func GetFollowListHandler(c *gin.Context) { @@ -164,7 +165,7 @@ func GetFollowListHandler(c *gin.Context) { "actor_id": req.ActorId, "user_id": req.UserId, }).Warnf("GetFollowListService returned an error response: %v", err) - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -173,7 +174,7 @@ func GetFollowListHandler(c *gin.Context) { "user_id": req.UserId, }).Infof("GetFollowList success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } @@ -198,14 +199,14 @@ func CountFollowHandler(c *gin.Context) { logger.WithFields(logrus.Fields{ "user_id": req.UserId, }).Warnf("CountFollowListService returned an error response: %v", err) - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } logger.WithFields(logrus.Fields{ "user_id": req.UserId, }).Infof("Count follow success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } @@ -232,7 +233,7 @@ func GetFollowerListHandler(c *gin.Context) { "actor_id": req.ActorId, "user_id": req.UserId, }).Warnf("GetFollowerListService returned an error response: %v", err) - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -241,7 +242,7 @@ func GetFollowerListHandler(c *gin.Context) { "user_id": req.UserId, }).Infof("GetFollowerList success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } @@ -266,14 +267,14 @@ func CountFollowerHandler(c *gin.Context) { logger.WithFields(logrus.Fields{ "user_id": req.UserId, }).Warnf("CountFollowerListService returned an error response: %v", err) - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } logger.WithFields(logrus.Fields{ "user_id": req.UserId, }).Infof("Count follower success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } func GetFriendListHandler(c *gin.Context) { @@ -300,7 +301,7 @@ func GetFriendListHandler(c *gin.Context) { "actor_id": req.ActorId, "user_id": req.UserId, }).Warnf("GetFriendListService returned an error response: %v", err) - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -309,7 +310,7 @@ func GetFriendListHandler(c *gin.Context) { "user_id": req.UserId, }).Infof("GetFriendList success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } @@ -336,7 +337,7 @@ func IsFollowHandler(c *gin.Context) { "actor_id": req.ActorId, "user_id": req.UserId, }).Warnf("IsFollowService returned an error response: %v", err) - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return } @@ -344,5 +345,5 @@ func IsFollowHandler(c *gin.Context) { "actor_id": req.ActorId, "user_id": req.UserId, }).Infof("IsFollow success") - c.JSON(http.StatusOK, res) + c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) } diff --git a/src/web/user/handler.go b/src/web/user/handler.go index 3dc81ec..b789d88 100644 --- a/src/web/user/handler.go +++ b/src/web/user/handler.go @@ -8,6 +8,7 @@ import ( grpc2 "GuGoTik/src/utils/grpc" "GuGoTik/src/utils/logging" "GuGoTik/src/web/models" + "GuGoTik/src/web/utils" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "net/http" @@ -45,9 +46,9 @@ func UserHandler(c *gin.Context) { "err": err, }).Errorf("Error when gateway get info from UserInfo Service") logging.SetSpanError(span, err) - c.JSON(http.StatusOK, resp) + c.Render(http.StatusOK, utils.CustomJSON{Data: resp, Context: c}) return } - c.JSON(http.StatusOK, resp) + c.Render(http.StatusOK, utils.CustomJSON{Data: resp, Context: c}) } diff --git a/src/web/utils/json.go b/src/web/utils/json.go new file mode 100644 index 0000000..2f313ae --- /dev/null +++ b/src/web/utils/json.go @@ -0,0 +1,29 @@ +package utils + +import ( + "github.com/gin-gonic/gin" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + "net/http" +) + +type CustomJSON struct { + Data proto.Message + Context *gin.Context +} + +var m = protojson.MarshalOptions{ + EmitUnpopulated: true, + UseProtoNames: true, +} + +func (r CustomJSON) Render(w http.ResponseWriter) (err error) { + r.WriteContentType(w) + res, _ := m.Marshal(r.Data) + _, err = w.Write(res) + return +} + +func (r CustomJSON) WriteContentType(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") +} From 75dfae9b3fd64c10df354dec1ab31fd8a9261736 Mon Sep 17 00:00:00 2001 From: yangfeng <1719957182@qq.com> Date: Wed, 23 Aug 2023 22:20:06 +0800 Subject: [PATCH 10/16] feat: update .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index e03c60e..ebba923 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ output/ log/ .env docker/basic/static -docker/rabbitmq/static \ No newline at end of file +docker/rabbitmq/static +static/ \ No newline at end of file From 5a834ab5266a86dc4b8983177b35da3866a6cc62 Mon Sep 17 00:00:00 2001 From: yangfeng <1719957182@qq.com> Date: Wed, 23 Aug 2023 23:00:18 +0800 Subject: [PATCH 11/16] test: add publish video test --- src/web/models/Publish.go | 10 ++++++++ test/web/comment_test.go | 8 +++--- test/web/favorite_test.go | 12 ++++++--- test/web/publish_test.go | 53 ++++++++++++++++++++++++++++++++++++++- test/web/value.go | 3 +++ 5 files changed, 78 insertions(+), 8 deletions(-) create mode 100644 test/web/value.go diff --git a/src/web/models/Publish.go b/src/web/models/Publish.go index 197ba69..a4be39e 100644 --- a/src/web/models/Publish.go +++ b/src/web/models/Publish.go @@ -3,6 +3,7 @@ package models import "GuGoTik/src/rpc/feed" type ListPublishReq struct { + Token string `form:"token" binding:"required"` ActorId uint32 `form:"actor_id" binding:"required"` UserId uint32 `form:"user_id" binding:"required"` } @@ -12,3 +13,12 @@ type ListPublishRes struct { StatusMsg string `json:"status_msg"` VideoList []*feed.Video `json:"vide_list"` } + +type ActionPublishReq struct { + ActorId uint32 `form:"actor_id" binding:"required"` +} + +type ActionPublishRes struct { + StatusCode int `json:"status_code"` + StatusMsg string `json:"status_msg"` +} diff --git a/test/web/comment_test.go b/test/web/comment_test.go index 7c9b6f5..3d7bb82 100644 --- a/test/web/comment_test.go +++ b/test/web/comment_test.go @@ -17,7 +17,7 @@ func TestActionComment_Add(t *testing.T) { method := "POST" req, err := http.NewRequest(method, url, nil) q := req.URL.Query() - q.Add("token", "c8e50d04-ebc6-4c36-ad67-9b46a61a2197") + q.Add("token", token) q.Add("actor_id", "1") q.Add("video_id", "0") q.Add("action_type", "1") @@ -46,7 +46,7 @@ func TestActionComment_Delete(t *testing.T) { method := "POST" req, err := http.NewRequest(method, url, nil) q := req.URL.Query() - q.Add("token", "c8e50d04-ebc6-4c36-ad67-9b46a61a2197") + q.Add("token", token) q.Add("actor_id", "1") q.Add("video_id", "0") q.Add("action_type", "2") @@ -75,7 +75,7 @@ func TestListComment(t *testing.T) { method := "GET" req, err := http.NewRequest(method, url, nil) q := req.URL.Query() - q.Add("token", "c8e50d04-ebc6-4c36-ad67-9b46a61a2197") + q.Add("token", token) q.Add("actor_id", "1") q.Add("video_id", "0") req.URL.RawQuery = q.Encode() @@ -102,7 +102,7 @@ func TestCountComment(t *testing.T) { method := "GET" req, err := http.NewRequest(method, url, nil) q := req.URL.Query() - q.Add("token", "c8e50d04-ebc6-4c36-ad67-9b46a61a2197") + q.Add("token", token) q.Add("actor_id", "1") q.Add("video_id", "0") req.URL.RawQuery = q.Encode() diff --git a/test/web/favorite_test.go b/test/web/favorite_test.go index b1e7380..567c880 100644 --- a/test/web/favorite_test.go +++ b/test/web/favorite_test.go @@ -14,13 +14,15 @@ var favoriteBaseUrl = "http://127.0.0.1:37000/douyin/favorite" func TestActionFavorite_Do(t *testing.T) { url := favoriteBaseUrl + "/action" method := "POST" - req, _ := http.NewRequest(method, url, nil) + req, err := http.NewRequest(method, url, nil) q := req.URL.Query() q.Add("token", "") // replace token, video_id q.Add("video_id", "1948195853") q.Add("action_type", "1") req.URL.RawQuery = q.Encode() + assert.Empty(t, err) + res, err := client.Do(req) assert.Empty(t, err) defer func(Body io.ReadCloser) { @@ -39,13 +41,15 @@ func TestActionFavorite_Do(t *testing.T) { func TestActionFavorite_Cancel(t *testing.T) { url := favoriteBaseUrl + "/action" method := "POST" - req, _ := http.NewRequest(method, url, nil) + req, err := http.NewRequest(method, url, nil) q := req.URL.Query() q.Add("token", "") // replace token, video_id q.Add("video_id", "1948195853") q.Add("action_type", "2") req.URL.RawQuery = q.Encode() + assert.Empty(t, err) + res, err := client.Do(req) assert.Empty(t, err) defer func(Body io.ReadCloser) { @@ -64,12 +68,14 @@ func TestActionFavorite_Cancel(t *testing.T) { func TestListFavorite(t *testing.T) { url := favoriteBaseUrl + "/list" method := "POST" - req, _ := http.NewRequest(method, url, nil) + req, err := http.NewRequest(method, url, nil) q := req.URL.Query() q.Add("token", "") // replace token, user_id q.Add("user_id", "1") req.URL.RawQuery = q.Encode() + assert.Empty(t, err) + res, err := client.Do(req) assert.Empty(t, err) defer func(Body io.ReadCloser) { diff --git a/test/web/publish_test.go b/test/web/publish_test.go index 9878c49..2bd906b 100644 --- a/test/web/publish_test.go +++ b/test/web/publish_test.go @@ -2,10 +2,13 @@ package web import ( "GuGoTik/src/web/models" + "bytes" "encoding/json" "github.com/stretchr/testify/assert" "io" + "mime/multipart" "net/http" + "os" "testing" ) @@ -14,8 +17,9 @@ func TestListVideo(t *testing.T) { method := "GET" req, err := http.NewRequest(method, url, nil) q := req.URL.Query() + q.Add("token", token) q.Add("actor_id", "1") - q.Add("video_id", "0") + q.Add("user_id", "2") req.URL.RawQuery = q.Encode() assert.Empty(t, err) @@ -34,3 +38,50 @@ func TestListVideo(t *testing.T) { assert.Empty(t, err) assert.Equal(t, 0, ListPublishRes.StatusCode) } + +func TestPublishVideo(t *testing.T) { + url := "http://127.0.0.1:37000/douyin/publish/action" + method := "POST" + filePath := "/home/yangfeng/Repos/youthcamp/videos/upload_video_1_1080p.mp4" + + payload := &bytes.Buffer{} + writer := multipart.NewWriter(payload) + + file, err := os.Open(filePath) + assert.Empty(t, err) + defer func(file *os.File) { + err := file.Close() + assert.Empty(t, err) + }(file) + + fileWriter, err := writer.CreateFormFile("data", file.Name()) + assert.Empty(t, err) + + _, err = io.Copy(fileWriter, file) + assert.Empty(t, err) + + _ = writer.WriteField("token", token) + _ = writer.WriteField("title", "午夜小电影") + + err = writer.Close() + assert.Empty(t, err) + + req, err := http.NewRequest(method, url, payload) + assert.Empty(t, err) + + req.Header.Set("Content-Type", writer.FormDataContentType()) + + res, err := client.Do(req) + assert.Empty(t, err) + defer func(Body io.ReadCloser) { + err := Body.Close() + assert.Empty(t, err) + }(res.Body) + + body, err := io.ReadAll(res.Body) + assert.Empty(t, err) + actionPublishRes := &models.ActionPublishRes{} + err = json.Unmarshal(body, &actionPublishRes) + assert.Empty(t, err) + assert.Equal(t, 0, actionPublishRes.StatusCode) +} diff --git a/test/web/value.go b/test/web/value.go new file mode 100644 index 0000000..b2e4860 --- /dev/null +++ b/test/web/value.go @@ -0,0 +1,3 @@ +package web + +const token = "a594ab0f-4d95-480d-8977-f62eb692776a" From 27ae01ae7c3444f36e18d7ea0106761326e12d69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=87=E6=9D=B0?= <2707138687@qq.com> Date: Thu, 24 Aug 2023 00:01:54 +0800 Subject: [PATCH 12/16] fix: fix (issue #130) --- src/services/feed/handler.go | 1 + 1 file changed, 1 insertion(+) diff --git a/src/services/feed/handler.go b/src/services/feed/handler.go index 068928c..065550a 100644 --- a/src/services/feed/handler.go +++ b/src/services/feed/handler.go @@ -258,6 +258,7 @@ func queryDetailed( go func(i int, v *models.Video) { defer wg.Done() commentCount, localErr := CommentClient.ListComment(ctx, &comment.ListCommentRequest{ + ActorId: actorId, VideoId: v.ID, }) if localErr != nil { From 42b11cca95e6d6f61be97bf097c5f0958ea80735 Mon Sep 17 00:00:00 2001 From: EpicMo <1982742309@qq.com> Date: Thu, 24 Aug 2023 00:24:21 +0800 Subject: [PATCH 13/16] fix: auth err --- src/web/middleware/authenticate.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/middleware/authenticate.go b/src/web/middleware/authenticate.go index 32449d9..f0fc17e 100644 --- a/src/web/middleware/authenticate.go +++ b/src/web/middleware/authenticate.go @@ -24,7 +24,7 @@ func TokenAuthMiddleware() gin.HandlerFunc { } var token string - if c.Request.URL.Path == "/douyin/publish/action/" { + if c.Request.URL.Path == "/douyin/publish/action" { token = c.PostForm("token") } else { token = c.Query("token") From 92a780b7a50b5027bd20658c5781379af8dbc9ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=87=E6=9D=B0?= <2707138687@qq.com> Date: Thu, 24 Aug 2023 00:41:15 +0800 Subject: [PATCH 14/16] fix: change latestTime format --- src/services/feed/handler.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/services/feed/handler.go b/src/services/feed/handler.go index 065550a..243cae7 100644 --- a/src/services/feed/handler.go +++ b/src/services/feed/handler.go @@ -49,10 +49,7 @@ func (s FeedServiceImpl) ListVideos(ctx context.Context, request *feed.ListFeedR logger := logging.LogService("FeedService.ListVideos").WithContext(ctx) now := uint32(time.Now().UnixMilli()) - - layout := "2006-01-02T15:04:05.999Z" - t, err := time.Parse(layout, *request.LatestTime) - latestTime := t.Unix() + latestTime, err := strconv.ParseInt(*request.LatestTime, 10, 64) if err != nil { var numError *strconv.NumError if errors.As(err, &numError) { From f5dea01f9b8acb09bac6684bc53f58299bb6a197 Mon Sep 17 00:00:00 2001 From: yangfeng <1719957182@qq.com> Date: Thu, 24 Aug 2023 15:46:05 +0800 Subject: [PATCH 15/16] fix(message): rpc and gateway --- src/services/message/handler.go | 4 ++-- src/web/message/handler.go | 42 +++++++++++++++++++++++---------- src/web/models/Message.go | 22 ++++++++--------- test/rpc/messagerpc_test.go | 7 +++--- test/web/message_test.go | 12 ++++------ 5 files changed, 50 insertions(+), 37 deletions(-) diff --git a/src/services/message/handler.go b/src/services/message/handler.go index 61d96a4..2556fa3 100644 --- a/src/services/message/handler.go +++ b/src/services/message/handler.go @@ -79,7 +79,7 @@ func (c MessageServiceImpl) ChatAction(ctx context.Context, request *chat.Action return res, err } -// Chat(context.Context, *ChatRequest) (*ChatResponse, error) +// Chat Chat(context.Context, *ChatRequest) (*ChatResponse, error) func (c MessageServiceImpl) Chat(ctx context.Context, request *chat.ChatRequest) (resp *chat.ChatResponse, err error) { ctx, span := tracing.Tracer.Start(ctx, "ChatService") defer span.End() @@ -101,7 +101,7 @@ func (c MessageServiceImpl) Chat(ctx context.Context, request *chat.ChatRequest) //TO DO 看怎么需要一下 var rMessageList []*chat.Message - result := database.Client.WithContext(ctx).Where("conversation_id=? and ", conversationId). + result := database.Client.WithContext(ctx).Where("conversation_id=?", conversationId). Order("created_at desc").Find(&rMessageList) if result.Error != nil { diff --git a/src/web/message/handler.go b/src/web/message/handler.go index e040288..1b71321 100644 --- a/src/web/message/handler.go +++ b/src/web/message/handler.go @@ -32,9 +32,11 @@ func ActionMessageHandler(c *gin.Context) { if err := c.ShouldBindQuery(&req); err != nil { logger.WithFields(logrus.Fields{ //"CreateTime": req.Create_time, - "ActorId": req.ActorId, - "from_id": req.UserId, - "err": err, + "ActorId": req.ActorId, + "ToUserId": req.ToUserId, + "ActionType": req.ActionType, + "Content": req.Content, + "err": err, }).Errorf("Error when trying to bind query") c.JSON(http.StatusOK, models.ActionCommentRes{ @@ -49,23 +51,29 @@ func ActionMessageHandler(c *gin.Context) { res, err = Client.ChatAction(c.Request.Context(), &chat.ActionRequest{ ActorId: uint32(req.ActorId), - UserId: uint32(req.UserId), - ActionType: uint32(req.Action_type), + UserId: uint32(req.ToUserId), + ActionType: uint32(req.ActionType), Content: req.Content, }) if err != nil { logger.WithFields(logrus.Fields{ - "ActorId": req.ActorId, - "content": req.Content, + "ActorId": req.ActorId, + "ToUserId": req.ToUserId, + "ActionType": req.ActionType, + "Content": req.Content, + "err": err, }).Error("Error when trying to connect with ActionMessageHandler") c.Render(http.StatusBadRequest, utils.CustomJSON{Data: res, Context: c}) return } logger.WithFields(logrus.Fields{ - "ActorId": req.ActorId, - "content": req.Content, + "ActorId": req.ActorId, + "ToUserId": req.ToUserId, + "ActionType": req.ActionType, + "Content": req.Content, + "err": err, }).Infof("Action send message success") c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) @@ -78,6 +86,12 @@ func ListMessageHandler(c *gin.Context) { logger := logging.LogService("GateWay.ListMessage").WithContext(c.Request.Context()) if err := c.ShouldBindQuery(&req); err != nil { + logger.WithFields(logrus.Fields{ + "ActorId": req.ActorId, + "ToUserId": req.ToUserId, + "PreMsgTime": req.PreMsgTime, + "Err": err, + }).Error("Error when trying to bind query") c.JSON(http.StatusOK, models.ListCommentRes{ StatusCode: strings.GateWayParamsErrorCode, StatusMsg: strings.GateWayParamsError, @@ -87,14 +101,16 @@ func ListMessageHandler(c *gin.Context) { res, err := Client.Chat(c.Request.Context(), &chat.ChatRequest{ ActorId: req.ActorId, - UserId: req.UserId, + UserId: req.ToUserId, PreMsgTime: req.PreMsgTime, }) if err != nil { logger.WithFields(logrus.Fields{ - "ActorId": req.ActorId, - "user_id": req.UserId, + "ActorId": req.ActorId, + "ToUserId": req.ToUserId, + "PreMsgTime": req.PreMsgTime, + "Err": err, }).Error("Error when trying to connect with ListMessageHandler") c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) return @@ -102,7 +118,7 @@ func ListMessageHandler(c *gin.Context) { logger.WithFields(logrus.Fields{ "ActorId": req.ActorId, - "user_id": req.UserId, + "user_id": req.ToUserId, }).Infof("List comment success") c.Render(http.StatusOK, utils.CustomJSON{Data: res, Context: c}) diff --git a/src/web/models/Message.go b/src/web/models/Message.go index e49f6e9..1634794 100644 --- a/src/web/models/Message.go +++ b/src/web/models/Message.go @@ -4,27 +4,27 @@ import ( "GuGoTik/src/rpc/chat" ) -// 这个是发数据的数据结构 +// SMessageReq 这个是发数据的数据结构 type SMessageReq struct { - ActorId int `form:"actor_id"` - UserId int `form:"user_id"` - Content string `form:"content"` - Action_type int `form:"action_type"` // send message + ActorId int `form:"actor_id" binding:"required"` + ToUserId int `form:"to_user_id" binding:"required"` + Content string `form:"content" binding:"required"` + ActionType int `form:"action_type" binding:"required"` // send message //Create_time string //time maybe have some question } -// 收的状态 -// statuc code 状态码 0- 成功 其他值 -失败 +// SMessageRes 收的状态 +// status_code 状态码 0- 成功 其他值 -失败 // status_msg 返回状态描述 type SMessageRes struct { StatusCode int `json:"status_code"` - Status_msg string `json:"status_msg"` + StatusMsg string `json:"status_msg"` } type ListMessageReq struct { - ActorId uint32 `form:"actor_id"` - UserId uint32 `from:"user_id"` - PreMsgTime uint32 `from:"preMsgTime"` + ActorId uint32 `form:"actor_id" binding:"required"` + ToUserId uint32 `form:"to_user_id" binding:"required"` + PreMsgTime uint32 `form:"pre_msg_time"` } type ListMessageRes struct { diff --git a/test/rpc/messagerpc_test.go b/test/rpc/messagerpc_test.go index 68c98b8..5a511a8 100644 --- a/test/rpc/messagerpc_test.go +++ b/test/rpc/messagerpc_test.go @@ -24,8 +24,8 @@ func setups() { func TestActionMessage_Add(t *testing.T) { setups() res, err := chatClient.ChatAction(context.Background(), &chat.ActionRequest{ - ActorId: 3, - UserId: 1, + ActorId: 1, + UserId: 2, ActionType: 1, Content: "Test message1", }) @@ -39,11 +39,10 @@ func TestChat(t *testing.T) { setups() res, err := chatClient.Chat(context.Background(), &chat.ChatRequest{ ActorId: 1, - UserId: 3, + UserId: 2, PreMsgTime: 0, }) assert.Empty(t, err) assert.Equal(t, int32(0), res.StatusCode) - assert.Equal(t, 2, len(res.MessageList)) } diff --git a/test/web/message_test.go b/test/web/message_test.go index 16629c4..2be1f76 100644 --- a/test/web/message_test.go +++ b/test/web/message_test.go @@ -19,11 +19,10 @@ func TestActionMessage_Add(t *testing.T) { method := "POST" req, err := http.NewRequest(method, url, nil) q := req.URL.Query() - q.Add("token", "1ae83f2a-7b82-4901-9e66-50d49dba00d5") - q.Add("actor_id", "1") - q.Add("user_id", "1") + q.Add("token", token) + q.Add("to_user_id", "2") q.Add("action_type", "1") - q.Add("content", "test comment") + q.Add("content", "test comment in gateway") req.URL.RawQuery = q.Encode() assert.Empty(t, err) @@ -51,9 +50,8 @@ func TestChat(t *testing.T) { req, err := http.NewRequest(method, url, nil) q := req.URL.Query() - q.Add("token", "1ae83f2a-7b82-4901-9e66-50d49dba00d5") - q.Add("actor_id", "1") - q.Add("user_id", "1") + q.Add("token", "token") + q.Add("to_user_id", "2") q.Add("perMsgTime", "0") req.URL.RawQuery = q.Encode() assert.Empty(t, err) From ac6086669d0314052421d001e7c52e1d96447055 Mon Sep 17 00:00:00 2001 From: yangfeng <1719957182@qq.com> Date: Thu, 24 Aug 2023 16:13:49 +0800 Subject: [PATCH 16/16] fix(message): add message create_time in response --- src/services/message/handler.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/services/message/handler.go b/src/services/message/handler.go index 2556fa3..4f5ab38 100644 --- a/src/services/message/handler.go +++ b/src/services/message/handler.go @@ -100,9 +100,11 @@ func (c MessageServiceImpl) Chat(ctx context.Context, request *chat.ChatRequest) //这个地方应该取出多少条消息? //TO DO 看怎么需要一下 - var rMessageList []*chat.Message - result := database.Client.WithContext(ctx).Where("conversation_id=?", conversationId). - Order("created_at desc").Find(&rMessageList) + var pMessageList []models.Message + result := database.Client.WithContext(ctx). + Where("conversation_id=?", conversationId). + Order("created_at desc"). + Find(&pMessageList) if result.Error != nil { logger.WithFields(logrus.Fields{ @@ -120,6 +122,17 @@ func (c MessageServiceImpl) Chat(ctx context.Context, request *chat.ChatRequest) return } + rMessageList := make([]*chat.Message, 0, len(pMessageList)) + for _, pMessage := range pMessageList { + rMessageList = append(rMessageList, &chat.Message{ + Id: pMessage.ID, + Content: pMessage.Content, + CreateTime: uint32(pMessage.CreatedAt.Unix()), + FromUserId: &pMessage.FromUserId, + ToUserId: &pMessage.ToUserId, + }) + } + resp = &chat.ChatResponse{ StatusCode: strings.ServiceOKCode, StatusMsg: strings.ServiceOK,