From 5433eb9e8f02d313dd3e306d9274233c70b6f8ad Mon Sep 17 00:00:00 2001 From: Michael Li Date: Fri, 11 Nov 2022 13:45:24 +0800 Subject: [PATCH 01/28] prepare use mir --- Makefile | 5 + go.mod | 5 + internal/dao/jinzhu/dbr/attachment.go | 27 +++ internal/dao/jinzhu/dbr/captcha.go | 38 ++++ internal/dao/jinzhu/dbr/comment.go | 127 +++++++++++ internal/dao/jinzhu/dbr/comment_content.go | 59 +++++ internal/dao/jinzhu/dbr/comment_reply.go | 110 +++++++++ internal/dao/jinzhu/dbr/contact.go | 119 ++++++++++ internal/dao/jinzhu/dbr/dbr.go | 36 +++ internal/dao/jinzhu/dbr/message.go | 148 +++++++++++++ internal/dao/jinzhu/dbr/post.go | 208 ++++++++++++++++++ .../dao/jinzhu/dbr/post_attachment_bill.go | 36 +++ internal/dao/jinzhu/dbr/post_collection.go | 102 +++++++++ internal/dao/jinzhu/dbr/post_content.go | 121 ++++++++++ internal/dao/jinzhu/dbr/post_star.go | 98 +++++++++ internal/dao/jinzhu/dbr/tag.go | 97 ++++++++ internal/dao/jinzhu/dbr/user.go | 94 ++++++++ internal/dao/jinzhu/dbr/wallet_recharge.go | 34 +++ internal/dao/jinzhu/dbr/wallet_statement.go | 83 +++++++ internal/mirc/auto/api/v1/site.go | 144 ++++++++++++ internal/mirc/main.go | 24 ++ internal/mirc/routes/README.md | 1 + internal/mirc/routes/v1/localoss.go | 15 ++ internal/mirc/routes/v1/web_admin.go | 15 ++ internal/mirc/routes/v1/web_alipay.go | 15 ++ internal/mirc/routes/v1/web_core.go | 44 ++++ internal/mirc/routes/v1/web_followship.go | 15 ++ internal/mirc/routes/v1/web_friendship.go | 15 ++ internal/mirc/routes/v1/web_loose.go | 15 ++ internal/mirc/routes/v1/web_priv.go | 15 ++ internal/mirc/routes/v1/web_pub.go | 15 ++ internal/servants/chain/admin.go | 25 +++ internal/servants/chain/jwt.go | 113 ++++++++++ internal/servants/chain/priv.go | 45 ++++ internal/servants/core.go | 26 +++ internal/servants/localoss.go | 5 + internal/servants/servants.go | 12 + internal/servants/web_admin.go | 5 + internal/servants/web_alipay.go | 5 + internal/servants/web_core.go | 32 +++ internal/servants/web_followship.go | 5 + internal/servants/web_friendship.go | 5 + internal/servants/web_loose.go | 5 + internal/servants/web_priv.go | 5 + internal/servants/web_pub.go | 5 + 45 files changed, 2173 insertions(+) create mode 100644 internal/dao/jinzhu/dbr/attachment.go create mode 100644 internal/dao/jinzhu/dbr/captcha.go create mode 100644 internal/dao/jinzhu/dbr/comment.go create mode 100644 internal/dao/jinzhu/dbr/comment_content.go create mode 100644 internal/dao/jinzhu/dbr/comment_reply.go create mode 100644 internal/dao/jinzhu/dbr/contact.go create mode 100644 internal/dao/jinzhu/dbr/dbr.go create mode 100644 internal/dao/jinzhu/dbr/message.go create mode 100644 internal/dao/jinzhu/dbr/post.go create mode 100644 internal/dao/jinzhu/dbr/post_attachment_bill.go create mode 100644 internal/dao/jinzhu/dbr/post_collection.go create mode 100644 internal/dao/jinzhu/dbr/post_content.go create mode 100644 internal/dao/jinzhu/dbr/post_star.go create mode 100644 internal/dao/jinzhu/dbr/tag.go create mode 100644 internal/dao/jinzhu/dbr/user.go create mode 100644 internal/dao/jinzhu/dbr/wallet_recharge.go create mode 100644 internal/dao/jinzhu/dbr/wallet_statement.go create mode 100644 internal/mirc/auto/api/v1/site.go create mode 100644 internal/mirc/main.go create mode 100644 internal/mirc/routes/README.md create mode 100644 internal/mirc/routes/v1/localoss.go create mode 100644 internal/mirc/routes/v1/web_admin.go create mode 100644 internal/mirc/routes/v1/web_alipay.go create mode 100644 internal/mirc/routes/v1/web_core.go create mode 100644 internal/mirc/routes/v1/web_followship.go create mode 100644 internal/mirc/routes/v1/web_friendship.go create mode 100644 internal/mirc/routes/v1/web_loose.go create mode 100644 internal/mirc/routes/v1/web_priv.go create mode 100644 internal/mirc/routes/v1/web_pub.go create mode 100644 internal/servants/chain/admin.go create mode 100644 internal/servants/chain/jwt.go create mode 100644 internal/servants/chain/priv.go create mode 100644 internal/servants/core.go create mode 100644 internal/servants/localoss.go create mode 100644 internal/servants/servants.go create mode 100644 internal/servants/web_admin.go create mode 100644 internal/servants/web_alipay.go create mode 100644 internal/servants/web_core.go create mode 100644 internal/servants/web_followship.go create mode 100644 internal/servants/web_friendship.go create mode 100644 internal/servants/web_loose.go create mode 100644 internal/servants/web_priv.go create mode 100644 internal/servants/web_pub.go diff --git a/Makefile b/Makefile index 4d0b94a2..700e2d29 100644 --- a/Makefile +++ b/Makefile @@ -68,6 +68,11 @@ windows-x64: @echo Build paopao-ce [windows-x64] CGO_ENABLED=$(CGO_ENABLED) @CGO_ENABLED=$(CGO_ENABLED) GOOS=windows GOARCH=amd64 go build -trimpath -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -o $(RELEASE_WINDOWS_AMD64)/$(basename $(TARGET)).exe +.PHONY: generate +generate: + @go generate internal/mirc/main.go + @go fmt ./internal/mirc/... + clean: @go clean @find ./release -type f -exec rm -r {} + diff --git a/go.mod b/go.mod index 8f4c9435..8e3819e5 100644 --- a/go.mod +++ b/go.mod @@ -39,6 +39,7 @@ require ( gorm.io/plugin/dbresolver v1.1.0 gorm.io/plugin/soft_delete v1.1.0 modernc.org/sqlite v1.17.3 + github.com/alimy/mir/v3 v3.0.0 ) require ( @@ -131,3 +132,7 @@ require ( modernc.org/strutil v1.1.1 // indirect modernc.org/token v1.0.0 // indirect ) + +replace ( + github.com/alimy/mir/v3 => ../../alimy/mir +) \ No newline at end of file diff --git a/internal/dao/jinzhu/dbr/attachment.go b/internal/dao/jinzhu/dbr/attachment.go new file mode 100644 index 00000000..0c748b00 --- /dev/null +++ b/internal/dao/jinzhu/dbr/attachment.go @@ -0,0 +1,27 @@ +package model + +import "gorm.io/gorm" + +type AttachmentType int + +const ( + ATTACHMENT_TYPE_IMAGE AttachmentType = iota + 1 + ATTACHMENT_TYPE_VIDEO + ATTACHMENT_TYPE_OTHER +) + +type Attachment struct { + *Model + UserID int64 `json:"user_id"` + FileSize int64 `json:"file_size"` + ImgWidth int `json:"img_width"` + ImgHeight int `json:"img_height"` + Type AttachmentType `json:"type"` + Content string `json:"content"` +} + +func (a *Attachment) Create(db *gorm.DB) (*Attachment, error) { + err := db.Create(&a).Error + + return a, err +} diff --git a/internal/dao/jinzhu/dbr/captcha.go b/internal/dao/jinzhu/dbr/captcha.go new file mode 100644 index 00000000..210cc691 --- /dev/null +++ b/internal/dao/jinzhu/dbr/captcha.go @@ -0,0 +1,38 @@ +package model + +import "gorm.io/gorm" + +type Captcha struct { + *Model + Phone string `json:"phone"` + Captcha string `json:"captcha"` + UseTimes int `json:"use_times"` + ExpiredOn int64 `json:"expired_on"` +} + +func (c *Captcha) Create(db *gorm.DB) (*Captcha, error) { + err := db.Create(&c).Error + + return c, err +} + +func (c *Captcha) Update(db *gorm.DB) error { + return db.Model(&Captcha{}).Where("id = ? AND is_del = ?", c.Model.ID, 0).Save(c).Error +} + +func (c *Captcha) Get(db *gorm.DB) (*Captcha, error) { + var captcha Captcha + if c.Model != nil && c.ID > 0 { + db = db.Where("id = ? AND is_del = ?", c.ID, 0) + } + if c.Phone != "" { + db = db.Where("phone = ?", c.Phone) + } + + err := db.Last(&captcha).Error + if err != nil { + return &captcha, err + } + + return &captcha, nil +} diff --git a/internal/dao/jinzhu/dbr/comment.go b/internal/dao/jinzhu/dbr/comment.go new file mode 100644 index 00000000..72494b53 --- /dev/null +++ b/internal/dao/jinzhu/dbr/comment.go @@ -0,0 +1,127 @@ +package model + +import ( + "time" + + "gorm.io/gorm" +) + +type Comment struct { + *Model + PostID int64 `json:"post_id"` + UserID int64 `json:"user_id"` + IP string `json:"ip"` + IPLoc string `json:"ip_loc"` +} + +type CommentFormated struct { + ID int64 `json:"id"` + PostID int64 `json:"post_id"` + UserID int64 `json:"user_id"` + User *UserFormated `json:"user"` + Contents []*CommentContent `json:"contents"` + Replies []*CommentReplyFormated `json:"replies"` + IPLoc string `json:"ip_loc"` + CreatedOn int64 `json:"created_on"` + ModifiedOn int64 `json:"modified_on"` +} + +func (c *Comment) Format() *CommentFormated { + if c.Model == nil { + return &CommentFormated{} + } + return &CommentFormated{ + ID: c.Model.ID, + PostID: c.PostID, + UserID: c.UserID, + User: &UserFormated{}, + Contents: []*CommentContent{}, + Replies: []*CommentReplyFormated{}, + IPLoc: c.IPLoc, + CreatedOn: c.CreatedOn, + ModifiedOn: c.ModifiedOn, + } +} + +func (c *Comment) Get(db *gorm.DB) (*Comment, error) { + var comment Comment + if c.Model != nil && c.ID > 0 { + db = db.Where("id = ? AND is_del = ?", c.ID, 0) + } else { + return nil, gorm.ErrRecordNotFound + } + + err := db.First(&comment).Error + if err != nil { + return &comment, err + } + + return &comment, nil +} + +func (c *Comment) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*Comment, error) { + var comments []*Comment + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if c.PostID > 0 { + db = db.Where("id = ?", c.PostID) + } + + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(k, v) + } + } + + if err = db.Where("is_del = ?", 0).Find(&comments).Error; err != nil { + return nil, err + } + + return comments, nil +} + +func (c *Comment) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { + var count int64 + if c.PostID > 0 { + db = db.Where("post_id = ?", c.PostID) + } + for k, v := range *conditions { + if k != "ORDER" { + db = db.Where(k, v) + } + } + if err := db.Model(c).Count(&count).Error; err != nil { + return 0, err + } + + return count, nil +} + +func (c *Comment) Create(db *gorm.DB) (*Comment, error) { + err := db.Create(&c).Error + + return c, err +} + +func (c *Comment) Delete(db *gorm.DB) error { + return db.Model(c).Where("id = ?", c.Model.ID).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} + +func (c *Comment) CommentIdsByPostId(db *gorm.DB, postId int64) (ids []int64, err error) { + err = db.Model(c).Where("post_id = ?", postId).Select("id").Find(&ids).Error + return +} + +func (c *Comment) DeleteByPostId(db *gorm.DB, postId int64) error { + return db.Model(c).Where("post_id = ?", postId).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} diff --git a/internal/dao/jinzhu/dbr/comment_content.go b/internal/dao/jinzhu/dbr/comment_content.go new file mode 100644 index 00000000..b7d42dfd --- /dev/null +++ b/internal/dao/jinzhu/dbr/comment_content.go @@ -0,0 +1,59 @@ +package model + +import ( + "time" + + "gorm.io/gorm" +) + +type CommentContent struct { + *Model + CommentID int64 `json:"comment_id"` + UserID int64 `json:"user_id"` + Content string `json:"content"` + Type PostContentT `json:"type"` + Sort int64 `json:"sort"` +} + +func (c *CommentContent) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*CommentContent, error) { + var comments []*CommentContent + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if c.CommentID > 0 { + db = db.Where("id = ?", c.CommentID) + } + + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(k, v) + } + } + + if err = db.Where("is_del = ?", 0).Find(&comments).Error; err != nil { + return nil, err + } + + return comments, nil +} + +func (c *CommentContent) Create(db *gorm.DB) (*CommentContent, error) { + err := db.Create(&c).Error + + return c, err +} + +func (c *CommentContent) MediaContentsByCommentId(db *gorm.DB, commentIds []int64) (contents []string, err error) { + err = db.Model(c).Where("comment_id IN ? AND type = ?", commentIds, CONTENT_TYPE_IMAGE).Select("content").Find(&contents).Error + return +} + +func (c *CommentContent) DeleteByCommentIds(db *gorm.DB, commentIds []int64) error { + return db.Model(c).Where("comment_id IN ?", commentIds).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} diff --git a/internal/dao/jinzhu/dbr/comment_reply.go b/internal/dao/jinzhu/dbr/comment_reply.go new file mode 100644 index 00000000..fd22702f --- /dev/null +++ b/internal/dao/jinzhu/dbr/comment_reply.go @@ -0,0 +1,110 @@ +package model + +import ( + "time" + + "gorm.io/gorm" +) + +type CommentReply struct { + *Model + CommentID int64 `json:"comment_id"` + UserID int64 `json:"user_id"` + AtUserID int64 `json:"at_user_id"` + Content string `json:"content"` + IP string `json:"ip"` + IPLoc string `json:"ip_loc"` +} + +type CommentReplyFormated struct { + ID int64 `json:"id"` + CommentID int64 `json:"comment_id"` + UserID int64 `json:"user_id"` + User *UserFormated `json:"user"` + AtUserID int64 `json:"at_user_id"` + AtUser *UserFormated `json:"at_user"` + Content string `json:"content"` + IPLoc string `json:"ip_loc"` + CreatedOn int64 `json:"created_on"` + ModifiedOn int64 `json:"modified_on"` +} + +func (c *CommentReply) Format() *CommentReplyFormated { + if c.Model == nil { + return &CommentReplyFormated{} + } + + return &CommentReplyFormated{ + ID: c.ID, + CommentID: c.CommentID, + UserID: c.UserID, + User: &UserFormated{}, + AtUserID: c.AtUserID, + AtUser: &UserFormated{}, + Content: c.Content, + IPLoc: c.IPLoc, + CreatedOn: c.CreatedOn, + ModifiedOn: c.ModifiedOn, + } +} + +func (c *CommentReply) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*CommentReply, error) { + var comments []*CommentReply + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if c.CommentID > 0 { + db = db.Where("id = ?", c.CommentID) + } + + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(k, v) + } + } + + if err = db.Where("is_del = ?", 0).Find(&comments).Error; err != nil { + return nil, err + } + + return comments, nil +} + +func (c *CommentReply) Create(db *gorm.DB) (*CommentReply, error) { + err := db.Create(&c).Error + + return c, err +} + +func (c *CommentReply) Get(db *gorm.DB) (*CommentReply, error) { + var reply CommentReply + if c.Model != nil && c.ID > 0 { + db = db.Where("id = ? AND is_del = ?", c.ID, 0) + } else { + return nil, gorm.ErrRecordNotFound + } + + err := db.First(&reply).Error + if err != nil { + return &reply, err + } + + return &reply, nil +} + +func (c *CommentReply) Delete(db *gorm.DB) error { + return db.Model(&CommentReply{}).Where("id = ? AND is_del = ?", c.Model.ID, 0).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} + +func (c *CommentReply) DeleteByCommentIds(db *gorm.DB, commentIds []int64) error { + return db.Model(c).Where("comment_id IN ?", commentIds).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} diff --git a/internal/dao/jinzhu/dbr/contact.go b/internal/dao/jinzhu/dbr/contact.go new file mode 100644 index 00000000..14049f77 --- /dev/null +++ b/internal/dao/jinzhu/dbr/contact.go @@ -0,0 +1,119 @@ +package model + +import ( + "github.com/sirupsen/logrus" + "gorm.io/gorm" +) + +const ( + ContactStatusRequesting int8 = iota + 1 + ContactStatusAgree + ContactStatusReject + ContactStatusDeleted +) + +type Contact struct { + *Model + User *User `json:"-" gorm:"foreignKey:ID;references:FriendId"` + UserId int64 `json:"user_id"` + FriendId int64 `json:"friend_id"` + GroupId int64 `json:"group_id"` + Remark string `json:"remark"` + Status int8 `json:"status"` // 1请求好友, 2已同意好友, 3已拒绝好友, 4已删除好友 + IsTop int8 `json:"is_top"` + IsBlack int8 `json:"is_black"` + NoticeEnable int8 `json:"notice_enable"` +} + +func (c *Contact) FetchUser(db *gorm.DB) (*Contact, error) { + var contact Contact + err := db.Omit("User").Unscoped().Where("user_id = ? AND friend_id = ?", c.UserId, c.FriendId).First(&contact).Error + if err != nil { + logrus.Debugf("Contact.FetchUser fetch user error:%s", err) + return nil, err + } + return &contact, nil +} + +func (c *Contact) GetByUserFriend(db *gorm.DB) (*Contact, error) { + var contact Contact + err := db.Omit("User").Where("user_id = ? AND friend_id = ?", c.UserId, c.FriendId).First(&contact).Error + if err != nil { + return nil, err + } + return &contact, nil +} + +func (c *Contact) FetchByUserFriendAll(db *gorm.DB) ([]*Contact, error) { + var contacts []*Contact + if err := db.Omit("User"). + Where("(user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)", + c.UserId, c.FriendId, c.FriendId, c.UserId). + Find(&contacts).Error; err != nil { + return nil, err + } + return contacts, nil +} + +func (c *Contact) List(db *gorm.DB, conditions ConditionsT, offset, limit int) ([]*Contact, error) { + var contacts []*Contact + var err error + tn := db.NamingStrategy.TableName("Contact") + "." + + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + for k, v := range conditions { + if k != "ORDER" { + db = db.Where(tn+k, v) + } + } + + db.Joins("User").Order("`User`.`nickname` ASC") + if err = db.Find(&contacts).Error; err != nil { + return nil, err + } + return contacts, nil +} + +func (c *Contact) BeFriendIds(db *gorm.DB) (ids []int64, err error) { + if err = db.Model(c).Omit("User").Select("user_id").Where("friend_id = ? AND status = ?", c.FriendId, ContactStatusAgree).Find(&ids).Error; err != nil { + return nil, err + } + return +} + +func (c *Contact) MyFriendIds(db *gorm.DB) (ids []string, err error) { + if err = db.Model(c).Omit("User").Select("friend_id").Where("user_id = ? AND status = ?", c.UserId, ContactStatusAgree).Find(&ids).Error; err != nil { + return nil, err + } + return +} + +func (m *Contact) Count(db *gorm.DB, conditions ConditionsT) (int64, error) { + var count int64 + + for k, v := range conditions { + if k != "ORDER" { + db = db.Where(k, v) + } + } + if err := db.Model(m).Omit("User").Count(&count).Error; err != nil { + return 0, err + } + + return count, nil +} + +func (c *Contact) Create(db *gorm.DB) (*Contact, error) { + err := db.Omit("User").Create(&c).Error + return c, err +} + +func (c *Contact) Update(db *gorm.DB) error { + return db.Model(&Contact{}).Omit("User").Where("id = ?", c.Model.ID).Save(c).Error +} + +func (c *Contact) UpdateInUnscoped(db *gorm.DB) error { + return db.Unscoped().Omit("User").Save(c).Error +} diff --git a/internal/dao/jinzhu/dbr/dbr.go b/internal/dao/jinzhu/dbr/dbr.go new file mode 100644 index 00000000..99bc8296 --- /dev/null +++ b/internal/dao/jinzhu/dbr/dbr.go @@ -0,0 +1,36 @@ +package model + +import ( + "time" + + "gorm.io/gorm" + "gorm.io/plugin/soft_delete" +) + +// Model 公共Model +type Model struct { + ID int64 `gorm:"primary_key" json:"id"` + CreatedOn int64 `json:"created_on"` + ModifiedOn int64 `json:"modified_on"` + DeletedOn int64 `json:"deleted_on"` + IsDel soft_delete.DeletedAt `gorm:"softDelete:flag" json:"is_del"` +} + +type ConditionsT map[string]any +type Predicates map[string][]any + +func (m *Model) BeforeCreate(tx *gorm.DB) (err error) { + nowTime := time.Now().Unix() + + tx.Statement.SetColumn("created_on", nowTime) + tx.Statement.SetColumn("modified_on", nowTime) + return +} + +func (m *Model) BeforeUpdate(tx *gorm.DB) (err error) { + if !tx.Statement.Changed("modified_on") { + tx.Statement.SetColumn("modified_on", time.Now().Unix()) + } + + return +} diff --git a/internal/dao/jinzhu/dbr/message.go b/internal/dao/jinzhu/dbr/message.go new file mode 100644 index 00000000..c1277cf7 --- /dev/null +++ b/internal/dao/jinzhu/dbr/message.go @@ -0,0 +1,148 @@ +package model + +import "gorm.io/gorm" + +type MessageT int8 + +const ( + MsgTypePost MessageT = iota + 1 + MsgtypeComment + MsgTypeReply + MsgTypeWhisper + MsgTypeRequestingFriend + MsgTypeSystem MessageT = 99 + + MsgStatusUnread = 0 + MsgStatusReaded = 1 +) + +type Message struct { + *Model + SenderUserID int64 `json:"sender_user_id"` + ReceiverUserID int64 `json:"receiver_user_id"` + Type MessageT `json:"type"` + Brief string `json:"brief"` + Content string `json:"content"` + PostID int64 `json:"post_id"` + CommentID int64 `json:"comment_id"` + ReplyID int64 `json:"reply_id"` + IsRead int8 `json:"is_read"` +} + +type MessageFormated struct { + ID int64 `json:"id"` + SenderUserID int64 `json:"sender_user_id"` + SenderUser *UserFormated `json:"sender_user"` + ReceiverUserID int64 `json:"receiver_user_id"` + Type MessageT `json:"type"` + Brief string `json:"brief"` + Content string `json:"content"` + PostID int64 `json:"post_id"` + Post *PostFormated `json:"post"` + CommentID int64 `json:"comment_id"` + Comment *Comment `json:"comment"` + ReplyID int64 `json:"reply_id"` + Reply *CommentReply `json:"reply"` + IsRead int8 `json:"is_read"` + CreatedOn int64 `json:"created_on"` + ModifiedOn int64 `json:"modified_on"` +} + +func (m *Message) Format() *MessageFormated { + if m.Model == nil || m.Model.ID == 0 { + return nil + } + mf := &MessageFormated{ + ID: m.ID, + SenderUserID: m.SenderUserID, + SenderUser: &UserFormated{}, + ReceiverUserID: m.ReceiverUserID, + Type: m.Type, + Brief: m.Brief, + Content: m.Content, + PostID: m.PostID, + Post: &PostFormated{}, + CommentID: m.CommentID, + Comment: &Comment{}, + ReplyID: m.ReplyID, + Reply: &CommentReply{}, + IsRead: m.IsRead, + CreatedOn: m.CreatedOn, + ModifiedOn: m.ModifiedOn, + } + + return mf +} + +func (m *Message) Create(db *gorm.DB) (*Message, error) { + err := db.Create(&m).Error + + return m, err +} + +func (m *Message) Update(db *gorm.DB) error { + return db.Model(&Message{}).Where("id = ? AND is_del = ?", m.Model.ID, 0).Save(m).Error +} + +func (m *Message) Get(db *gorm.DB) (*Message, error) { + var message Message + if m.Model != nil && m.ID > 0 { + db = db.Where("id = ? AND is_del = ?", m.ID, 0) + } + if m.ReceiverUserID > 0 { + db = db.Where("receiver_user_id = ?", m.ReceiverUserID) + } + if err := db.First(&message).Error; err != nil { + return nil, err + } + return &message, nil +} + +func (m *Message) FetchBy(db *gorm.DB, predicates Predicates) ([]*Message, error) { + var messages []*Message + for k, v := range predicates { + db = db.Where(k, v...) + } + db = db.Where("is_del = 0") + if err := db.Find(&messages).Error; err != nil { + return nil, err + } + return messages, nil +} + +func (c *Message) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*Message, error) { + var messages []*Message + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(k, v) + } + } + + if err = db.Where("is_del = ?", 0).Find(&messages).Error; err != nil { + return nil, err + } + + return messages, nil +} + +func (m *Message) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { + var count int64 + + for k, v := range *conditions { + if k != "ORDER" { + db = db.Where(k, v) + } + } + if err := db.Model(m).Count(&count).Error; err != nil { + return 0, err + } + + return count, nil +} diff --git a/internal/dao/jinzhu/dbr/post.go b/internal/dao/jinzhu/dbr/post.go new file mode 100644 index 00000000..ae428a9a --- /dev/null +++ b/internal/dao/jinzhu/dbr/post.go @@ -0,0 +1,208 @@ +package model + +import ( + "strings" + "time" + + "gorm.io/gorm" +) + +// PostVisibleT 可访问类型,0公开,1私密,2好友 +type PostVisibleT uint8 + +const ( + PostVisitPublic PostVisibleT = iota + PostVisitPrivate + PostVisitFriend + PostVisitInvalid +) + +type Post struct { + *Model + UserID int64 `json:"user_id"` + CommentCount int64 `json:"comment_count"` + CollectionCount int64 `json:"collection_count"` + UpvoteCount int64 `json:"upvote_count"` + Visibility PostVisibleT `json:"visibility"` + IsTop int `json:"is_top"` + IsEssence int `json:"is_essence"` + IsLock int `json:"is_lock"` + LatestRepliedOn int64 `json:"latest_replied_on"` + Tags string `json:"tags"` + AttachmentPrice int64 `json:"attachment_price"` + IP string `json:"ip"` + IPLoc string `json:"ip_loc"` +} + +type PostFormated struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + User *UserFormated `json:"user"` + Contents []*PostContentFormated `json:"contents"` + CommentCount int64 `json:"comment_count"` + CollectionCount int64 `json:"collection_count"` + UpvoteCount int64 `json:"upvote_count"` + Visibility PostVisibleT `json:"visibility"` + IsTop int `json:"is_top"` + IsEssence int `json:"is_essence"` + IsLock int `json:"is_lock"` + LatestRepliedOn int64 `json:"latest_replied_on"` + CreatedOn int64 `json:"created_on"` + ModifiedOn int64 `json:"modified_on"` + Tags map[string]int8 `json:"tags"` + AttachmentPrice int64 `json:"attachment_price"` + IPLoc string `json:"ip_loc"` +} + +func (p *Post) Format() *PostFormated { + if p.Model != nil { + tagsMap := map[string]int8{} + for _, tag := range strings.Split(p.Tags, ",") { + tagsMap[tag] = 1 + } + return &PostFormated{ + ID: p.ID, + UserID: p.UserID, + User: &UserFormated{}, + Contents: []*PostContentFormated{}, + CommentCount: p.CommentCount, + CollectionCount: p.CollectionCount, + UpvoteCount: p.UpvoteCount, + Visibility: p.Visibility, + IsTop: p.IsTop, + IsEssence: p.IsEssence, + IsLock: p.IsLock, + LatestRepliedOn: p.LatestRepliedOn, + CreatedOn: p.CreatedOn, + ModifiedOn: p.ModifiedOn, + AttachmentPrice: p.AttachmentPrice, + Tags: tagsMap, + IPLoc: p.IPLoc, + } + } + + return nil +} + +func (p *Post) Create(db *gorm.DB) (*Post, error) { + err := db.Create(&p).Error + + return p, err +} + +func (s *Post) Delete(db *gorm.DB) error { + return db.Model(s).Where("id = ?", s.Model.ID).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} + +func (p *Post) Get(db *gorm.DB) (*Post, error) { + var post Post + if p.Model != nil && p.ID > 0 { + db = db.Where("id = ? AND is_del = ?", p.ID, 0) + } else { + return nil, gorm.ErrRecordNotFound + } + + err := db.First(&post).Error + if err != nil { + return &post, err + } + + return &post, nil +} + +func (p *Post) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*Post, error) { + var posts []*Post + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if p.UserID > 0 { + db = db.Where("user_id = ?", p.UserID) + } + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(k, v) + } + } + + if err = db.Where("is_del = ?", 0).Find(&posts).Error; err != nil { + return nil, err + } + + return posts, nil +} + +func (p *Post) Fetch(db *gorm.DB, predicates Predicates, offset, limit int) ([]*Post, error) { + var posts []*Post + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if p.UserID > 0 { + db = db.Where("user_id = ?", p.UserID) + } + for query, args := range predicates { + if query == "ORDER" { + db = db.Order(args[0]) + } else { + db = db.Where(query, args...) + } + } + + if err = db.Where("is_del = ?", 0).Find(&posts).Error; err != nil { + return nil, err + } + + return posts, nil +} + +func (p *Post) CountBy(db *gorm.DB, predicates Predicates) (count int64, err error) { + for query, args := range predicates { + if query != "ORDER" { + db = db.Where(query, args...) + } + } + err = db.Model(p).Count(&count).Error + return +} + +func (p *Post) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { + var count int64 + if p.UserID > 0 { + db = db.Where("user_id = ?", p.UserID) + } + for k, v := range *conditions { + if k != "ORDER" { + db = db.Where(k, v) + } + } + if err := db.Model(p).Count(&count).Error; err != nil { + return 0, err + } + + return count, nil +} + +func (p *Post) Update(db *gorm.DB) error { + return db.Model(&Post{}).Where("id = ? AND is_del = ?", p.Model.ID, 0).Save(p).Error +} + +func (p PostVisibleT) String() string { + switch p { + case PostVisitPublic: + return "public" + case PostVisitPrivate: + return "private" + case PostVisitFriend: + return "friend" + case PostVisitInvalid: + return "invalid" + default: + return "unknow" + } +} diff --git a/internal/dao/jinzhu/dbr/post_attachment_bill.go b/internal/dao/jinzhu/dbr/post_attachment_bill.go new file mode 100644 index 00000000..8ee7aae6 --- /dev/null +++ b/internal/dao/jinzhu/dbr/post_attachment_bill.go @@ -0,0 +1,36 @@ +package model + +import "gorm.io/gorm" + +type PostAttachmentBill struct { + *Model + PostID int64 `json:"post_id"` + UserID int64 `json:"user_id"` + PaidAmount int64 `json:"paid_amount"` +} + +func (p *PostAttachmentBill) Get(db *gorm.DB) (*PostAttachmentBill, error) { + var pas PostAttachmentBill + if p.Model != nil && p.ID > 0 { + db = db.Where("id = ? AND is_del = ?", p.ID, 0) + } + if p.PostID > 0 { + db = db.Where("post_id = ?", p.PostID) + } + if p.UserID > 0 { + db = db.Where("user_id = ?", p.UserID) + } + + err := db.First(&pas).Error + if err != nil { + return &pas, err + } + + return &pas, nil +} + +func (p *PostAttachmentBill) Create(db *gorm.DB) (*PostAttachmentBill, error) { + err := db.Create(&p).Error + + return p, err +} diff --git a/internal/dao/jinzhu/dbr/post_collection.go b/internal/dao/jinzhu/dbr/post_collection.go new file mode 100644 index 00000000..0ea0cb29 --- /dev/null +++ b/internal/dao/jinzhu/dbr/post_collection.go @@ -0,0 +1,102 @@ +package model + +import ( + "time" + + "gorm.io/gorm" +) + +type PostCollection struct { + *Model + Post *Post `json:"-"` + PostID int64 `json:"post_id"` + UserID int64 `json:"user_id"` +} + +func (p *PostCollection) Get(db *gorm.DB) (*PostCollection, error) { + var star PostCollection + tn := db.NamingStrategy.TableName("PostCollection") + "." + + if p.Model != nil && p.ID > 0 { + db = db.Where(tn+"id = ? AND "+tn+"is_del = ?", p.ID, 0) + } + if p.PostID > 0 { + db = db.Where(tn+"post_id = ?", p.PostID) + } + if p.UserID > 0 { + db = db.Where(tn+"user_id = ?", p.UserID) + } + + db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC") + err := db.First(&star).Error + if err != nil { + return &star, err + } + + return &star, nil +} + +func (p *PostCollection) Create(db *gorm.DB) (*PostCollection, error) { + err := db.Omit("Post").Create(&p).Error + + return p, err +} + +func (p *PostCollection) Delete(db *gorm.DB) error { + return db.Model(&PostCollection{}).Omit("Post").Where("id = ? AND is_del = ?", p.Model.ID, 0).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} + +func (p *PostCollection) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostCollection, error) { + var collections []*PostCollection + var err error + tn := db.NamingStrategy.TableName("PostCollection") + "." + + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if p.UserID > 0 { + db = db.Where(tn+"user_id = ?", p.UserID) + } + + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(tn+k, v) + } + } + + db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC") + if err = db.Where(tn+"is_del = ?", 0).Find(&collections).Error; err != nil { + return nil, err + } + + return collections, nil +} + +func (p *PostCollection) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { + var count int64 + tn := db.NamingStrategy.TableName("PostCollection") + "." + + if p.PostID > 0 { + db = db.Where(tn+"post_id = ?", p.PostID) + } + if p.UserID > 0 { + db = db.Where(tn+"user_id = ?", p.UserID) + } + for k, v := range *conditions { + if k != "ORDER" { + db = db.Where(tn+k, v) + } + } + + db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate) + if err := db.Model(p).Count(&count).Error; err != nil { + return 0, err + } + + return count, nil +} diff --git a/internal/dao/jinzhu/dbr/post_content.go b/internal/dao/jinzhu/dbr/post_content.go new file mode 100644 index 00000000..b301de62 --- /dev/null +++ b/internal/dao/jinzhu/dbr/post_content.go @@ -0,0 +1,121 @@ +package model + +import ( + "time" + + "gorm.io/gorm" +) + +// 类型,1标题,2文字段落,3图片地址,4视频地址,5语音地址,6链接地址,7附件资源 + +type PostContentT int + +const ( + CONTENT_TYPE_TITLE PostContentT = iota + 1 + CONTENT_TYPE_TEXT + CONTENT_TYPE_IMAGE + CONTENT_TYPE_VIDEO + CONTENT_TYPE_AUDIO + CONTENT_TYPE_LINK + CONTENT_TYPE_ATTACHMENT + CONTENT_TYPE_CHARGE_ATTACHMENT +) + +var ( + mediaContentType = []PostContentT{ + CONTENT_TYPE_IMAGE, + CONTENT_TYPE_VIDEO, + CONTENT_TYPE_AUDIO, + CONTENT_TYPE_ATTACHMENT, + CONTENT_TYPE_CHARGE_ATTACHMENT, + } +) + +type PostContent struct { + *Model + PostID int64 `json:"post_id"` + UserID int64 `json:"user_id"` + Content string `json:"content"` + Type PostContentT `json:"type"` + Sort int64 `json:"sort"` +} + +type PostContentFormated struct { + ID int64 `json:"id"` + PostID int64 `json:"post_id"` + Content string `json:"content"` + Type PostContentT `json:"type"` + Sort int64 `json:"sort"` +} + +func (p *PostContent) DeleteByPostId(db *gorm.DB, postId int64) error { + return db.Model(p).Where("post_id = ?", postId).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} + +func (p *PostContent) MediaContentsByPostId(db *gorm.DB, postId int64) (contents []string, err error) { + err = db.Model(p).Where("post_id = ? AND type IN ?", postId, mediaContentType).Select("content").Find(&contents).Error + return +} + +func (p *PostContent) Create(db *gorm.DB) (*PostContent, error) { + err := db.Create(&p).Error + + return p, err +} + +func (p *PostContent) Format() *PostContentFormated { + if p.Model == nil { + return nil + } + return &PostContentFormated{ + ID: p.ID, + PostID: p.PostID, + Content: p.Content, + Type: p.Type, + Sort: p.Sort, + } +} + +func (p *PostContent) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostContent, error) { + var contents []*PostContent + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if p.PostID > 0 { + db = db.Where("id = ?", p.PostID) + } + + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(k, v) + } + } + + if err = db.Where("is_del = ?", 0).Find(&contents).Error; err != nil { + return nil, err + } + + return contents, nil +} + +func (p *PostContent) Get(db *gorm.DB) (*PostContent, error) { + var content PostContent + if p.Model != nil && p.ID > 0 { + db = db.Where("id = ? AND is_del = ?", p.ID, 0) + } else { + return nil, gorm.ErrRecordNotFound + } + + err := db.First(&content).Error + if err != nil { + return &content, err + } + + return &content, nil +} diff --git a/internal/dao/jinzhu/dbr/post_star.go b/internal/dao/jinzhu/dbr/post_star.go new file mode 100644 index 00000000..3846a9c2 --- /dev/null +++ b/internal/dao/jinzhu/dbr/post_star.go @@ -0,0 +1,98 @@ +package model + +import ( + "time" + + "gorm.io/gorm" +) + +type PostStar struct { + *Model + Post *Post `json:"-"` + PostID int64 `json:"post_id"` + UserID int64 `json:"user_id"` +} + +func (p *PostStar) Get(db *gorm.DB) (*PostStar, error) { + var star PostStar + tn := db.NamingStrategy.TableName("PostStar") + "." + + if p.Model != nil && p.ID > 0 { + db = db.Where(tn+"id = ? AND "+tn+"is_del = ?", p.ID, 0) + } + if p.PostID > 0 { + db = db.Where(tn+"post_id = ?", p.PostID) + } + if p.UserID > 0 { + db = db.Where(tn+"user_id = ?", p.UserID) + } + + db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC") + if err := db.First(&star).Error; err != nil { + return nil, err + } + return &star, nil +} + +func (p *PostStar) Create(db *gorm.DB) (*PostStar, error) { + err := db.Omit("Post").Create(&p).Error + + return p, err +} + +func (p *PostStar) Delete(db *gorm.DB) error { + return db.Model(&PostStar{}).Omit("Post").Where("id = ? AND is_del = ?", p.Model.ID, 0).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} + +func (p *PostStar) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostStar, error) { + var stars []*PostStar + var err error + tn := db.NamingStrategy.TableName("PostStar") + "." + + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if p.UserID > 0 { + db = db.Where(tn+"user_id = ?", p.UserID) + } + + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(tn+k, v) + } + } + + db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC") + if err = db.Find(&stars).Error; err != nil { + return nil, err + } + return stars, nil +} + +func (p *PostStar) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { + var count int64 + tn := db.NamingStrategy.TableName("PostStar") + "." + + if p.PostID > 0 { + db = db.Where(tn+"post_id = ?", p.PostID) + } + if p.UserID > 0 { + db = db.Where(tn+"user_id = ?", p.UserID) + } + for k, v := range *conditions { + if k != "ORDER" { + db = db.Where(tn+k, v) + } + } + + db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate) + if err := db.Model(p).Count(&count).Error; err != nil { + return 0, err + } + return count, nil +} diff --git a/internal/dao/jinzhu/dbr/tag.go b/internal/dao/jinzhu/dbr/tag.go new file mode 100644 index 00000000..34bb64f9 --- /dev/null +++ b/internal/dao/jinzhu/dbr/tag.go @@ -0,0 +1,97 @@ +package model + +import ( + "time" + + "gorm.io/gorm" +) + +type Tag struct { + *Model + UserID int64 `json:"user_id"` + Tag string `json:"tag"` + QuoteNum int64 `json:"quote_num"` +} +type TagFormated struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + User *UserFormated `json:"user"` + Tag string `json:"tag"` + QuoteNum int64 `json:"quote_num"` +} + +func (t *Tag) Format() *TagFormated { + if t.Model == nil { + return &TagFormated{} + } + + return &TagFormated{ + ID: t.ID, + UserID: t.UserID, + User: &UserFormated{}, + Tag: t.Tag, + QuoteNum: t.QuoteNum, + } +} + +func (t *Tag) Get(db *gorm.DB) (*Tag, error) { + var tag Tag + if t.Model != nil && t.Model.ID > 0 { + db = db.Where("id= ? AND is_del = ?", t.Model.ID, 0) + } else { + db = db.Where("tag = ? AND is_del = ?", t.Tag, 0) + } + + err := db.First(&tag).Error + if err != nil { + return &tag, err + } + + return &tag, nil +} + +func (t *Tag) Create(db *gorm.DB) (*Tag, error) { + err := db.Create(&t).Error + + return t, err +} + +func (t *Tag) Update(db *gorm.DB) error { + return db.Model(&Tag{}).Where("id = ? AND is_del = ?", t.Model.ID, 0).Save(t).Error +} + +func (t *Tag) Delete(db *gorm.DB) error { + return db.Model(t).Where("id = ?", t.Model.ID).Updates(map[string]any{ + "deleted_on": time.Now().Unix(), + "is_del": 1, + }).Error +} + +func (t *Tag) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*Tag, error) { + var tags []*Tag + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if t.UserID > 0 { + db = db.Where("user_id = ?", t.UserID) + } + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(k, v) + } + } + + if err = db.Where("is_del = ?", 0).Find(&tags).Error; err != nil { + return nil, err + } + + return tags, nil +} + +func (t *Tag) TagsFrom(db *gorm.DB, tags []string) (res []*Tag, err error) { + err = db.Where("tag IN ?", tags).Find(&res).Error + return +} diff --git a/internal/dao/jinzhu/dbr/user.go b/internal/dao/jinzhu/dbr/user.go new file mode 100644 index 00000000..39c52d79 --- /dev/null +++ b/internal/dao/jinzhu/dbr/user.go @@ -0,0 +1,94 @@ +package model + +import "gorm.io/gorm" + +const ( + UserStatusNormal int = iota + 1 + UserStatusClosed +) + +type User struct { + *Model + Nickname string `json:"nickname"` + Username string `json:"username"` + Phone string `json:"phone"` + Password string `json:"password"` + Salt string `json:"salt"` + Status int `json:"status"` + Avatar string `json:"avatar"` + Balance int64 `json:"balance"` + IsAdmin bool `json:"is_admin"` +} + +type UserFormated struct { + ID int64 `json:"id"` + Nickname string `json:"nickname"` + Username string `json:"username"` + Status int `json:"status"` + Avatar string `json:"avatar"` + IsAdmin bool `json:"is_admin"` +} + +func (u *User) Format() *UserFormated { + if u.Model != nil { + return &UserFormated{ + ID: u.ID, + Nickname: u.Nickname, + Username: u.Username, + Status: u.Status, + Avatar: u.Avatar, + IsAdmin: u.IsAdmin, + } + } + + return nil +} + +func (u *User) Get(db *gorm.DB) (*User, error) { + var user User + if u.Model != nil && u.Model.ID > 0 { + db = db.Where("id= ? AND is_del = ?", u.Model.ID, 0) + } else if u.Phone != "" { + db = db.Where("phone = ? AND is_del = ?", u.Phone, 0) + } else { + db = db.Where("username = ? AND is_del = ?", u.Username, 0) + } + + err := db.First(&user).Error + if err != nil { + return &user, err + } + + return &user, nil +} + +func (u *User) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*User, error) { + var users []*User + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(k, v) + } + } + + if err = db.Where("is_del = ?", 0).Find(&users).Error; err != nil { + return nil, err + } + + return users, nil +} + +func (u *User) Create(db *gorm.DB) (*User, error) { + err := db.Create(&u).Error + + return u, err +} + +func (u *User) Update(db *gorm.DB) error { + return db.Model(&User{}).Where("id = ? AND is_del = ?", u.Model.ID, 0).Save(u).Error +} diff --git a/internal/dao/jinzhu/dbr/wallet_recharge.go b/internal/dao/jinzhu/dbr/wallet_recharge.go new file mode 100644 index 00000000..bfb3bc6f --- /dev/null +++ b/internal/dao/jinzhu/dbr/wallet_recharge.go @@ -0,0 +1,34 @@ +package model + +import "gorm.io/gorm" + +type WalletRecharge struct { + *Model + UserID int64 `json:"user_id"` + Amount int64 `json:"amount"` + TradeNo string `json:"trade_no"` + TradeStatus string `json:"trade_status"` +} + +func (p *WalletRecharge) Get(db *gorm.DB) (*WalletRecharge, error) { + var pas WalletRecharge + if p.Model != nil && p.ID > 0 { + db = db.Where("id = ? AND is_del = ?", p.ID, 0) + } + if p.UserID > 0 { + db = db.Where("user_id = ?", p.UserID) + } + + err := db.First(&pas).Error + if err != nil { + return &pas, err + } + + return &pas, nil +} + +func (p *WalletRecharge) Create(db *gorm.DB) (*WalletRecharge, error) { + err := db.Create(&p).Error + + return p, err +} diff --git a/internal/dao/jinzhu/dbr/wallet_statement.go b/internal/dao/jinzhu/dbr/wallet_statement.go new file mode 100644 index 00000000..163e2430 --- /dev/null +++ b/internal/dao/jinzhu/dbr/wallet_statement.go @@ -0,0 +1,83 @@ +package model + +import "gorm.io/gorm" + +type WalletStatement struct { + *Model + UserID int64 `json:"user_id"` + ChangeAmount int64 `json:"change_amount"` + BalanceSnapshot int64 `json:"balance_snapshot"` + Reason string `json:"reason"` + PostID int64 `json:"post_id"` +} + +func (w *WalletStatement) Get(db *gorm.DB) (*WalletStatement, error) { + var ws WalletStatement + if w.Model != nil && w.ID > 0 { + db = db.Where("id = ? AND is_del = ?", w.ID, 0) + } + if w.PostID > 0 { + db = db.Where("post_id = ?", w.PostID) + } + if w.UserID > 0 { + db = db.Where("user_id = ?", w.UserID) + } + + err := db.First(&ws).Error + if err != nil { + return &ws, err + } + + return &ws, nil +} + +func (w *WalletStatement) Create(db *gorm.DB) (*WalletStatement, error) { + err := db.Create(&w).Error + + return w, err +} + +func (w *WalletStatement) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*WalletStatement, error) { + var records []*WalletStatement + var err error + if offset >= 0 && limit > 0 { + db = db.Offset(offset).Limit(limit) + } + if w.UserID > 0 { + db = db.Where("user_id = ?", w.UserID) + } + + for k, v := range *conditions { + if k == "ORDER" { + db = db.Order(v) + } else { + db = db.Where(k, v) + } + } + + if err = db.Where("is_del = ?", 0).Find(&records).Error; err != nil { + return nil, err + } + + return records, nil +} + +func (w *WalletStatement) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { + var count int64 + if w.PostID > 0 { + db = db.Where("post_id = ?", w.PostID) + } + if w.UserID > 0 { + db = db.Where("user_id = ?", w.UserID) + } + for k, v := range *conditions { + if k != "ORDER" { + db = db.Where(k, v) + } + } + if err := db.Model(w).Count(&count).Error; err != nil { + return 0, err + } + + return count, nil +} diff --git a/internal/mirc/auto/api/v1/site.go b/internal/mirc/auto/api/v1/site.go new file mode 100644 index 00000000..03c50281 --- /dev/null +++ b/internal/mirc/auto/api/v1/site.go @@ -0,0 +1,144 @@ +// Code generated by go-mir. DO NOT EDIT. + +package v1 + +import ( + "errors" + "net/http" + + gin "github.com/gin-gonic/gin" +) + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type WebCore interface { + // Chain provide handlers chain for gin + Chain() gin.HandlersChain + + Index(c *gin.Context) error + Articles(c *gin.Context) error + Login(c *gin.Context, req *LoginReq) (*LoginResp, error) + Logout(c *gin.Context) error + + mustEmbedUnimplementedWebCoreServant() +} + +type WebCoreBinding interface { + BindLogin(c *gin.Context) (*LoginReq, error) + + mustEmbedUnimplementedWebCoreBinding() +} + +type WebCoreRender interface { + RenderIndex(c *gin.Context, err error) + RenderArticles(c *gin.Context, err error) + RenderLogin(c *gin.Context, data *LoginResp, err error) + RenderLogout(c *gin.Context, err error) + + mustEmbedUnimplementedWebCoreRender() +} + +// RegisterWebCoreServant register WebCore servant to gin +func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCoreRender) { + router := e.Group("v1") + // use chain for router + middlewares := s.Chain() + router.Use(middlewares...) + + // register routes info to router + router.Handle("GET", "/index/", func(c *gin.Context) { + r.RenderIndex(c, s.Index(c)) + }) + router.Handle("GET", "/articles/:category/", func(c *gin.Context) { + r.RenderArticles(c, s.Articles(c)) + }) + router.Handle("POST", "/user/login/", func(c *gin.Context) { + req, err := b.BindLogin(c) + if err != nil { + r.RenderLogin(c, nil, err) + } + resp, err := s.Login(c, req) + r.RenderLogin(c, resp, err) + }) + router.Handle("POST", "/user/logout/", func(c *gin.Context) { + r.RenderLogout(c, s.Logout(c)) + }) +} + +// UnimplementedWebCoreServant can be embedded to have forward compatible implementations. +type UnimplementedWebCoreServant struct{} + +// UnimplementedWebCoreBinding can be embedded to have forward compatible implementations. +type UnimplementedWebCoreBinding struct{} + +// UnimplementedWebCoreRender can be embedded to have forward compatible implementations. +type UnimplementedWebCoreRender struct{} + +func (UnimplementedWebCoreServant) Chain() gin.HandlersChain { + return nil +} + +func (UnimplementedWebCoreServant) Index(c *gin.Context) error { + return errors.New("method Index not implemented") +} + +func (UnimplementedWebCoreServant) Articles(c *gin.Context) error { + return errors.New("method Index not implemented") +} + +func (UnimplementedWebCoreServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, error) { + return nil, errors.New("method Login not implemented") +} + +func (UnimplementedWebCoreServant) Logout(c *gin.Context) error { + return errors.New("method Logout not implemented") +} + +func (UnimplementedWebCoreServant) mustEmbedUnimplementedWebCoreServant() {} + +func (UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, error) { + return nil, errors.New("method BindLogin not implemented") +} + +func (UnimplementedWebCoreBinding) mustEmbedUnimplementedWebCoreBinding() {} + +func (UnimplementedWebCoreRender) RenderIndex(c *gin.Context, err error) { + c.String(http.StatusInternalServerError, "method RenderLogout not implemented") +} + +func (UnimplementedWebCoreRender) RenderArticles(c *gin.Context, err error) { + c.String(http.StatusInternalServerError, "method RenderLogout not implemented") +} + +func (UnimplementedWebCoreRender) RenderLogin(c *gin.Context, data *LoginResp, err error) { + c.String(http.StatusInternalServerError, "method RenderLogin not implemented") +} + +func (UnimplementedWebCoreRender) RenderLogout(c *gin.Context, err error) { + c.String(http.StatusInternalServerError, "method RenderLogout not implemented") +} + +func (UnimplementedWebCoreRender) mustEmbedUnimplementedWebCoreRender() {} diff --git a/internal/mirc/main.go b/internal/mirc/main.go new file mode 100644 index 00000000..c2e47411 --- /dev/null +++ b/internal/mirc/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "log" + + . "github.com/alimy/mir/v3/core" + . "github.com/alimy/mir/v3/engine" + + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/v1" +) + +//go:generate go run main.go +func main() { + log.Println("generate code start") + opts := Options{ + RunMode(InSerialMode), + GeneratorName(GeneratorGin), + SinkPath("auto"), + } + if err := Generate(opts); err != nil { + log.Fatal(err) + } + log.Println("generate code finish") +} diff --git a/internal/mirc/routes/README.md b/internal/mirc/routes/README.md new file mode 100644 index 00000000..0d7ac0c1 --- /dev/null +++ b/internal/mirc/routes/README.md @@ -0,0 +1 @@ +### RESTful API for paopao-ce diff --git a/internal/mirc/routes/v1/localoss.go b/internal/mirc/routes/v1/localoss.go new file mode 100644 index 00000000..bf2d09d8 --- /dev/null +++ b/internal/mirc/routes/v1/localoss.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(LocalOSS)) +} + +type LocalOSS struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_admin.go b/internal/mirc/routes/v1/web_admin.go new file mode 100644 index 00000000..db95fc86 --- /dev/null +++ b/internal/mirc/routes/v1/web_admin.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebAdmin)) +} + +type WebAdmin struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_alipay.go b/internal/mirc/routes/v1/web_alipay.go new file mode 100644 index 00000000..61de0906 --- /dev/null +++ b/internal/mirc/routes/v1/web_alipay.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebAlipay)) +} + +type WebAlipay struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_core.go b/internal/mirc/routes/v1/web_core.go new file mode 100644 index 00000000..565fb04a --- /dev/null +++ b/internal/mirc/routes/v1/web_core.go @@ -0,0 +1,44 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebCore)) +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type WebCore struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` + Index func(Get) `mir:"/index/"` + Articles func(Get) `mir:"/articles/:category/"` + Login func(Post, LoginReq) LoginResp `mir:"/user/login/"` + Logout func(Post) `mir:"/user/logout/"` +} diff --git a/internal/mirc/routes/v1/web_followship.go b/internal/mirc/routes/v1/web_followship.go new file mode 100644 index 00000000..1dd9de82 --- /dev/null +++ b/internal/mirc/routes/v1/web_followship.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebFollowship)) +} + +type WebFollowship struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_friendship.go b/internal/mirc/routes/v1/web_friendship.go new file mode 100644 index 00000000..e1276e99 --- /dev/null +++ b/internal/mirc/routes/v1/web_friendship.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebFriendship)) +} + +type WebFriendship struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_loose.go b/internal/mirc/routes/v1/web_loose.go new file mode 100644 index 00000000..7eff7d44 --- /dev/null +++ b/internal/mirc/routes/v1/web_loose.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebLoose)) +} + +type WebLoose struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_priv.go b/internal/mirc/routes/v1/web_priv.go new file mode 100644 index 00000000..3d73eb1b --- /dev/null +++ b/internal/mirc/routes/v1/web_priv.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebPriv)) +} + +type WebPriv struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_pub.go b/internal/mirc/routes/v1/web_pub.go new file mode 100644 index 00000000..7bfe2e3a --- /dev/null +++ b/internal/mirc/routes/v1/web_pub.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebPub)) +} + +type WebPub struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/servants/chain/admin.go b/internal/servants/chain/admin.go new file mode 100644 index 00000000..846d6b68 --- /dev/null +++ b/internal/servants/chain/admin.go @@ -0,0 +1,25 @@ +package chain + +import ( + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/pkg/app" + "github.com/rocboss/paopao-ce/pkg/errcode" +) + +func Admin() gin.HandlerFunc { + return func(c *gin.Context) { + if user, exist := c.Get("USER"); exist { + if userModel, ok := user.(*model.User); ok { + if userModel.Status == model.UserStatusNormal && userModel.IsAdmin { + c.Next() + return + } + } + } + + response := app.NewResponse(c) + response.ToErrorResponse(errcode.NoAdminPermission) + c.Abort() + } +} diff --git a/internal/servants/chain/jwt.go b/internal/servants/chain/jwt.go new file mode 100644 index 00000000..75a4c9ad --- /dev/null +++ b/internal/servants/chain/jwt.go @@ -0,0 +1,113 @@ +package chain + +import ( + "strings" + + "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v4" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/pkg/app" + "github.com/rocboss/paopao-ce/pkg/errcode" +) + +func JWT() gin.HandlerFunc { + // TODO: optimize get user from a simple service that provide fetch a user info interface. + db := conf.MustGormDB() + return func(c *gin.Context) { + var ( + token string + ecode = errcode.Success + ) + if s, exist := c.GetQuery("token"); exist { + token = s + } else { + token = c.GetHeader("Authorization") + + // 验证前端传过来的token格式,不为空,开头为Bearer + if token == "" || !strings.HasPrefix(token, "Bearer ") { + response := app.NewResponse(c) + response.ToErrorResponse(errcode.UnauthorizedTokenError) + c.Abort() + return + } + + // 验证通过,提取有效部分(除去Bearer) + token = token[7:] + } + if token == "" { + ecode = errcode.InvalidParams + } else { + claims, err := app.ParseToken(token) + if err != nil { + switch err.(*jwt.ValidationError).Errors { + case jwt.ValidationErrorExpired: + ecode = errcode.UnauthorizedTokenTimeout + default: + ecode = errcode.UnauthorizedTokenError + } + } else { + c.Set("UID", claims.UID) + c.Set("USERNAME", claims.Username) + + // 加载用户信息 + user := &model.User{ + Model: &model.Model{ + ID: claims.UID, + }, + } + user, _ = user.Get(db) + c.Set("USER", user) + + // 强制下线机制 + if (conf.JWTSetting.Issuer + ":" + user.Salt) != claims.Issuer { + ecode = errcode.UnauthorizedTokenTimeout + } + } + } + + if ecode != errcode.Success { + response := app.NewResponse(c) + response.ToErrorResponse(ecode) + c.Abort() + return + } + + c.Next() + } +} + +func JwtLoose() gin.HandlerFunc { + // TODO: optimize get user from a simple service that provide fetch a user info interface. + db := conf.MustGormDB() + return func(c *gin.Context) { + token, exist := c.GetQuery("token") + if !exist { + token = c.GetHeader("Authorization") + // 验证前端传过来的token格式,不为空,开头为Bearer + if strings.HasPrefix(token, "Bearer ") { + // 验证通过,提取有效部分(除去Bearer) + token = token[7:] + } else { + c.Next() + } + } + if len(token) > 0 { + if claims, err := app.ParseToken(token); err == nil { + c.Set("UID", claims.UID) + c.Set("USERNAME", claims.Username) + // 加载用户信息 + user := &model.User{ + Model: &model.Model{ + ID: claims.UID, + }, + } + user, err := user.Get(db) + if err == nil && (conf.JWTSetting.Issuer+":"+user.Salt) == claims.Issuer { + c.Set("USER", user) + } + } + } + c.Next() + } +} diff --git a/internal/servants/chain/priv.go b/internal/servants/chain/priv.go new file mode 100644 index 00000000..60409b6b --- /dev/null +++ b/internal/servants/chain/priv.go @@ -0,0 +1,45 @@ +package chain + +import ( + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/pkg/app" + "github.com/rocboss/paopao-ce/pkg/errcode" +) + +func Priv() gin.HandlerFunc { + if conf.CfgIf("PhoneBind") { + return func(c *gin.Context) { + if u, exist := c.Get("USER"); exist { + if user, ok := u.(*model.User); ok { + if user.Status == model.UserStatusNormal { + if user.Phone == "" { + response := app.NewResponse(c) + response.ToErrorResponse(errcode.AccountNoPhoneBind) + c.Abort() + return + } + c.Next() + return + } + } + } + response := app.NewResponse(c) + response.ToErrorResponse(errcode.UserHasBeenBanned) + c.Abort() + } + } else { + return func(c *gin.Context) { + if u, exist := c.Get("USER"); exist { + if user, ok := u.(*model.User); ok && user.Status == model.UserStatusNormal { + c.Next() + return + } + } + response := app.NewResponse(c) + response.ToErrorResponse(errcode.UserHasBeenBanned) + c.Abort() + } + } +} diff --git a/internal/servants/core.go b/internal/servants/core.go new file mode 100644 index 00000000..6deb274c --- /dev/null +++ b/internal/servants/core.go @@ -0,0 +1,26 @@ +package servants + +import ( + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/model" +) + +type baseServant struct { + // TODO +} + +type baseBinding struct { + // TODO +} + +type baseRender struct { + // TODO +} + +func (baseServant) userFrom(c *gin.Context) (*model.User, bool) { + if u, exists := c.Get("USER"); exists { + user, ok := u.(*model.User) + return user, ok + } + return nil, false +} diff --git a/internal/servants/localoss.go b/internal/servants/localoss.go new file mode 100644 index 00000000..b99a78f0 --- /dev/null +++ b/internal/servants/localoss.go @@ -0,0 +1,5 @@ +package servants + +type localossSrv struct { + // TODO +} diff --git a/internal/servants/servants.go b/internal/servants/servants.go new file mode 100644 index 00000000..cc808cdb --- /dev/null +++ b/internal/servants/servants.go @@ -0,0 +1,12 @@ +package servants + +import ( + "github.com/gin-gonic/gin" + + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" +) + +// RegisterServants register all the servants to gin.Engine +func RegisterServants(e *gin.Engine) { + api.RegisterWebCoreServant(e, newWebCoreSrv(), newWebCoreBinding(), newWebCoreRender()) +} diff --git a/internal/servants/web_admin.go b/internal/servants/web_admin.go new file mode 100644 index 00000000..f527df8a --- /dev/null +++ b/internal/servants/web_admin.go @@ -0,0 +1,5 @@ +package servants + +type webAdminSrv struct { + // TODO +} diff --git a/internal/servants/web_alipay.go b/internal/servants/web_alipay.go new file mode 100644 index 00000000..680a3df8 --- /dev/null +++ b/internal/servants/web_alipay.go @@ -0,0 +1,5 @@ +package servants + +type webAlipaySrv struct { + // TODO +} diff --git a/internal/servants/web_core.go b/internal/servants/web_core.go new file mode 100644 index 00000000..027676b8 --- /dev/null +++ b/internal/servants/web_core.go @@ -0,0 +1,32 @@ +package servants + +import ( + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" +) + +type webCoreSrv struct { + baseServant + api.UnimplementedWebCoreServant +} + +type webCoreBinding struct { + baseBinding + api.UnimplementedWebCoreBinding +} + +type webCoreRender struct { + baseRender + api.UnimplementedWebCoreRender +} + +func newWebCoreSrv() api.WebCore { + return &webCoreSrv{} +} + +func newWebCoreBinding() api.WebCoreBinding { + return &webCoreBinding{} +} + +func newWebCoreRender() api.WebCoreRender { + return &webCoreRender{} +} diff --git a/internal/servants/web_followship.go b/internal/servants/web_followship.go new file mode 100644 index 00000000..f069d8e7 --- /dev/null +++ b/internal/servants/web_followship.go @@ -0,0 +1,5 @@ +package servants + +type webFollowshipSrv struct { + // TODO +} diff --git a/internal/servants/web_friendship.go b/internal/servants/web_friendship.go new file mode 100644 index 00000000..63bd9896 --- /dev/null +++ b/internal/servants/web_friendship.go @@ -0,0 +1,5 @@ +package servants + +type webFriendshipSrv struct { + // TODO +} diff --git a/internal/servants/web_loose.go b/internal/servants/web_loose.go new file mode 100644 index 00000000..04eaa907 --- /dev/null +++ b/internal/servants/web_loose.go @@ -0,0 +1,5 @@ +package servants + +type webLooseSrv struct { + // TODO +} diff --git a/internal/servants/web_priv.go b/internal/servants/web_priv.go new file mode 100644 index 00000000..8a0a830e --- /dev/null +++ b/internal/servants/web_priv.go @@ -0,0 +1,5 @@ +package servants + +type webPrivSrv struct { + // TODO +} diff --git a/internal/servants/web_pub.go b/internal/servants/web_pub.go new file mode 100644 index 00000000..d66a09b2 --- /dev/null +++ b/internal/servants/web_pub.go @@ -0,0 +1,5 @@ +package servants + +type webPubSrv struct { + // TODO +} From 367e0b018bd00f309e8c35de85486733846890dc Mon Sep 17 00:00:00 2001 From: Michael Li Date: Fri, 11 Nov 2022 14:44:57 +0800 Subject: [PATCH 02/28] optimize source code layout --- internal/mirc/README.md | 1 + internal/proto/RADME.md | 2 ++ internal/servants/{ => core}/core.go | 10 +++---- internal/servants/servants.go | 4 +-- .../servants/{web_admin.go => web/admin.go} | 2 +- .../servants/{web_alipay.go => web/alipay.go} | 2 +- .../servants/{web_core.go => web/core.go} | 27 ++++++++----------- .../{web_followship.go => web/followship.go} | 2 +- .../{web_friendship.go => web/friendship.go} | 2 +- .../servants/{web_loose.go => web/loose.go} | 2 +- .../servants/{web_priv.go => web/priv.go} | 2 +- internal/servants/{web_pub.go => web/pub.go} | 2 +- internal/servants/web/web.go | 17 ++++++++++++ internal/version/version.go | 8 ++++++ 14 files changed, 53 insertions(+), 30 deletions(-) create mode 100644 internal/mirc/README.md create mode 100644 internal/proto/RADME.md rename internal/servants/{ => core}/core.go (60%) rename internal/servants/{web_admin.go => web/admin.go} (69%) rename internal/servants/{web_alipay.go => web/alipay.go} (69%) rename internal/servants/{web_core.go => web/core.go} (50%) rename internal/servants/{web_followship.go => web/followship.go} (71%) rename internal/servants/{web_friendship.go => web/friendship.go} (71%) rename internal/servants/{web_loose.go => web/loose.go} (69%) rename internal/servants/{web_priv.go => web/priv.go} (68%) rename internal/servants/{web_pub.go => web/pub.go} (67%) create mode 100644 internal/servants/web/web.go create mode 100644 internal/version/version.go diff --git a/internal/mirc/README.md b/internal/mirc/README.md new file mode 100644 index 00000000..5b2162a2 --- /dev/null +++ b/internal/mirc/README.md @@ -0,0 +1 @@ +### RESTful API for paopao-ce use [go-mir](https://github.com/alimy/mir) to generate service interface code automatic. diff --git a/internal/proto/RADME.md b/internal/proto/RADME.md new file mode 100644 index 00000000..05d78ece --- /dev/null +++ b/internal/proto/RADME.md @@ -0,0 +1,2 @@ +### gRPC API +This directory contain some gRPC API define files. diff --git a/internal/servants/core.go b/internal/servants/core/core.go similarity index 60% rename from internal/servants/core.go rename to internal/servants/core/core.go index 6deb274c..6bedfa92 100644 --- a/internal/servants/core.go +++ b/internal/servants/core/core.go @@ -1,23 +1,23 @@ -package servants +package core import ( "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/model" ) -type baseServant struct { +type BaseServant struct { // TODO } -type baseBinding struct { +type BaseBinding struct { // TODO } -type baseRender struct { +type BaseRender struct { // TODO } -func (baseServant) userFrom(c *gin.Context) (*model.User, bool) { +func (BaseServant) userFrom(c *gin.Context) (*model.User, bool) { if u, exists := c.Get("USER"); exists { user, ok := u.(*model.User) return user, ok diff --git a/internal/servants/servants.go b/internal/servants/servants.go index cc808cdb..9cd595c7 100644 --- a/internal/servants/servants.go +++ b/internal/servants/servants.go @@ -2,11 +2,11 @@ package servants import ( "github.com/gin-gonic/gin" - api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" + "github.com/rocboss/paopao-ce/internal/servants/web" ) // RegisterServants register all the servants to gin.Engine func RegisterServants(e *gin.Engine) { - api.RegisterWebCoreServant(e, newWebCoreSrv(), newWebCoreBinding(), newWebCoreRender()) + api.RegisterWebCoreServant(e, web.NewWebCoreSrv(), web.NewWebCoreBinding(), web.NewWebCoreRender()) } diff --git a/internal/servants/web_admin.go b/internal/servants/web/admin.go similarity index 69% rename from internal/servants/web_admin.go rename to internal/servants/web/admin.go index f527df8a..f97832ce 100644 --- a/internal/servants/web_admin.go +++ b/internal/servants/web/admin.go @@ -1,4 +1,4 @@ -package servants +package web type webAdminSrv struct { // TODO diff --git a/internal/servants/web_alipay.go b/internal/servants/web/alipay.go similarity index 69% rename from internal/servants/web_alipay.go rename to internal/servants/web/alipay.go index 680a3df8..a4f71e9f 100644 --- a/internal/servants/web_alipay.go +++ b/internal/servants/web/alipay.go @@ -1,4 +1,4 @@ -package servants +package web type webAlipaySrv struct { // TODO diff --git a/internal/servants/web_core.go b/internal/servants/web/core.go similarity index 50% rename from internal/servants/web_core.go rename to internal/servants/web/core.go index 027676b8..579b51b4 100644 --- a/internal/servants/web_core.go +++ b/internal/servants/web/core.go @@ -1,32 +1,27 @@ -package servants +package web import ( api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" + "github.com/rocboss/paopao-ce/internal/servants/core" +) + +var ( + _ api.WebCore = (*webCoreSrv)(nil) + _ api.WebCoreBinding = (*webCoreBinding)(nil) + _ api.WebCoreRender = (*webCoreRender)(nil) ) type webCoreSrv struct { - baseServant + core.BaseServant api.UnimplementedWebCoreServant } type webCoreBinding struct { - baseBinding + core.BaseBinding api.UnimplementedWebCoreBinding } type webCoreRender struct { - baseRender + core.BaseRender api.UnimplementedWebCoreRender } - -func newWebCoreSrv() api.WebCore { - return &webCoreSrv{} -} - -func newWebCoreBinding() api.WebCoreBinding { - return &webCoreBinding{} -} - -func newWebCoreRender() api.WebCoreRender { - return &webCoreRender{} -} diff --git a/internal/servants/web_followship.go b/internal/servants/web/followship.go similarity index 71% rename from internal/servants/web_followship.go rename to internal/servants/web/followship.go index f069d8e7..6965c4a5 100644 --- a/internal/servants/web_followship.go +++ b/internal/servants/web/followship.go @@ -1,4 +1,4 @@ -package servants +package web type webFollowshipSrv struct { // TODO diff --git a/internal/servants/web_friendship.go b/internal/servants/web/friendship.go similarity index 71% rename from internal/servants/web_friendship.go rename to internal/servants/web/friendship.go index 63bd9896..87690037 100644 --- a/internal/servants/web_friendship.go +++ b/internal/servants/web/friendship.go @@ -1,4 +1,4 @@ -package servants +package web type webFriendshipSrv struct { // TODO diff --git a/internal/servants/web_loose.go b/internal/servants/web/loose.go similarity index 69% rename from internal/servants/web_loose.go rename to internal/servants/web/loose.go index 04eaa907..051a86ef 100644 --- a/internal/servants/web_loose.go +++ b/internal/servants/web/loose.go @@ -1,4 +1,4 @@ -package servants +package web type webLooseSrv struct { // TODO diff --git a/internal/servants/web_priv.go b/internal/servants/web/priv.go similarity index 68% rename from internal/servants/web_priv.go rename to internal/servants/web/priv.go index 8a0a830e..efe80d49 100644 --- a/internal/servants/web_priv.go +++ b/internal/servants/web/priv.go @@ -1,4 +1,4 @@ -package servants +package web type webPrivSrv struct { // TODO diff --git a/internal/servants/web_pub.go b/internal/servants/web/pub.go similarity index 67% rename from internal/servants/web_pub.go rename to internal/servants/web/pub.go index d66a09b2..2b55e3ac 100644 --- a/internal/servants/web_pub.go +++ b/internal/servants/web/pub.go @@ -1,4 +1,4 @@ -package servants +package web type webPubSrv struct { // TODO diff --git a/internal/servants/web/web.go b/internal/servants/web/web.go new file mode 100644 index 00000000..5f505dc1 --- /dev/null +++ b/internal/servants/web/web.go @@ -0,0 +1,17 @@ +package web + +import ( + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" +) + +func NewWebCoreSrv() api.WebCore { + return &webCoreSrv{} +} + +func NewWebCoreBinding() api.WebCoreBinding { + return &webCoreBinding{} +} + +func NewWebCoreRender() api.WebCoreRender { + return &webCoreRender{} +} diff --git a/internal/version/version.go b/internal/version/version.go new file mode 100644 index 00000000..b3bcb903 --- /dev/null +++ b/internal/version/version.go @@ -0,0 +1,8 @@ +package version + +var ( + // GitHash Value will be set during build + GitHash = "" + // BuildTime Value will be set during build + BuildTime = "" +) From a63744479b9647ee5d5bd7a5858fdf869a2ad4cd Mon Sep 17 00:00:00 2001 From: Michael Li Date: Fri, 11 Nov 2022 15:41:30 +0800 Subject: [PATCH 03/28] optimize source code layout --- internal/app/app.go | 39 +++++++++++++ internal/servants/core/xerror/common.go | 26 +++++++++ internal/servants/core/xerror/xerror.go | 75 +++++++++++++++++++++++++ internal/servants/docs.go | 13 +++++ internal/servants/docs_embed.go | 17 ++++++ internal/servants/localoss.go | 5 -- internal/servants/localoss/localoss.go | 28 +++++++++ internal/servants/localoss/xerror.go | 11 ++++ internal/servants/servants.go | 15 +++-- internal/servants/statick.go | 13 +++++ internal/servants/statick_embed.go | 27 +++++++++ internal/servants/web/core.go | 12 ++++ internal/servants/web/web.go | 14 ++--- internal/servants/web/xerror.go | 73 ++++++++++++++++++++++++ 14 files changed, 349 insertions(+), 19 deletions(-) create mode 100644 internal/app/app.go create mode 100644 internal/servants/core/xerror/common.go create mode 100644 internal/servants/core/xerror/xerror.go create mode 100644 internal/servants/docs.go create mode 100644 internal/servants/docs_embed.go delete mode 100644 internal/servants/localoss.go create mode 100644 internal/servants/localoss/localoss.go create mode 100644 internal/servants/localoss/xerror.go create mode 100644 internal/servants/statick.go create mode 100644 internal/servants/statick_embed.go create mode 100644 internal/servants/web/xerror.go diff --git a/internal/app/app.go b/internal/app/app.go new file mode 100644 index 00000000..c38b473f --- /dev/null +++ b/internal/app/app.go @@ -0,0 +1,39 @@ +package app + +import ( + "net/http" + + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" +) + +func NewWebEngine() *gin.Engine { + e := gin.New() + e.HandleMethodNotAllowed = true + e.Use(gin.Logger()) + e.Use(gin.Recovery()) + + // 跨域配置 + corsConfig := cors.DefaultConfig() + corsConfig.AllowAllOrigins = true + corsConfig.AddAllowHeaders("Authorization") + e.Use(cors.New(corsConfig)) + + // 默认404 + e.NoRoute(func(c *gin.Context) { + c.JSON(http.StatusNotFound, gin.H{ + "code": 404, + "msg": "Not Found", + }) + }) + + // 默认405 + e.NoMethod(func(c *gin.Context) { + c.JSON(http.StatusMethodNotAllowed, gin.H{ + "code": 405, + "msg": "Method Not Allowed", + }) + }) + + return e +} diff --git a/internal/servants/core/xerror/common.go b/internal/servants/core/xerror/common.go new file mode 100644 index 00000000..a59c62e8 --- /dev/null +++ b/internal/servants/core/xerror/common.go @@ -0,0 +1,26 @@ +package xerror + +var ( + Success = NewError(0, "成功") + ServerError = NewError(10000, "服务内部错误") + InvalidParams = NewError(10001, "入参错误") + NotFound = NewError(10002, "找不到") + UnauthorizedAuthNotExist = NewError(10003, "账户不存在") + UnauthorizedAuthFailed = NewError(10004, "账户密码错误") + UnauthorizedTokenError = NewError(10005, "鉴权失败,Token 错误或丢失") + UnauthorizedTokenTimeout = NewError(10006, "鉴权失败,Token 超时") + UnauthorizedTokenGenerate = NewError(10007, "鉴权失败,Token 生成失败") + TooManyRequests = NewError(10008, "请求过多") + + GatewayMethodsLimit = NewError(10109, "网关仅接受GET或POST请求") + GatewayLostSign = NewError(10110, "网关请求缺少签名") + GatewayLostAppKey = NewError(10111, "网关请求缺少APP KEY") + GatewayAppKeyInvalid = NewError(10112, "网关请求无效APP KEY") + GatewayAppKeyClosed = NewError(10113, "网关请求APP KEY已停用") + GatewayParamSignError = NewError(10114, "网关请求参数签名错误") + GatewayTooManyRequests = NewError(10115, "网关请求频次超限") + + FileUploadFailed = NewError(10200, "文件上传失败") + FileInvalidExt = NewError(10201, "文件类型不合法") + FileInvalidSize = NewError(10202, "文件大小超限") +) diff --git a/internal/servants/core/xerror/xerror.go b/internal/servants/core/xerror/xerror.go new file mode 100644 index 00000000..b1b8a23a --- /dev/null +++ b/internal/servants/core/xerror/xerror.go @@ -0,0 +1,75 @@ +package xerror + +import ( + "fmt" + "net/http" +) + +type Error struct { + code int + msg string + details []string +} + +var codes = map[int]string{} + +func NewError(code int, msg string) *Error { + if _, ok := codes[code]; ok { + panic(fmt.Sprintf("错误码 %d 已经存在,请更换一个", code)) + } + codes[code] = msg + return &Error{code: code, msg: msg} +} + +func (e *Error) Error() string { + return fmt.Sprintf("错误码: %d, 错误信息: %s", e.Code(), e.Msg()) +} + +func (e *Error) Code() int { + return e.code +} + +func (e *Error) Msg() string { + return e.msg +} + +func (e *Error) Msgf(args []any) string { + return fmt.Sprintf(e.msg, args...) +} + +func (e *Error) Details() []string { + return e.details +} + +func (e *Error) WithDetails(details ...string) *Error { + newError := *e + newError.details = []string{} + newError.details = append(newError.details, details...) + + return &newError +} + +func (e *Error) StatusCode() int { + switch e.Code() { + case Success.Code(): + return http.StatusOK + case ServerError.Code(): + return http.StatusInternalServerError + case InvalidParams.Code(): + return http.StatusBadRequest + case UnauthorizedAuthNotExist.Code(): + fallthrough + case UnauthorizedAuthFailed.Code(): + fallthrough + case UnauthorizedTokenError.Code(): + fallthrough + case UnauthorizedTokenGenerate.Code(): + fallthrough + case UnauthorizedTokenTimeout.Code(): + return http.StatusUnauthorized + case TooManyRequests.Code(): + return http.StatusTooManyRequests + } + + return http.StatusInternalServerError +} diff --git a/internal/servants/docs.go b/internal/servants/docs.go new file mode 100644 index 00000000..9d53cac5 --- /dev/null +++ b/internal/servants/docs.go @@ -0,0 +1,13 @@ +//go:build !docs +// +build !docs + +package servants + +import ( + "github.com/gin-gonic/gin" +) + +// registerDocs stub function for register docs asset route +func registerDocs(e *gin.Engine) { + // empty +} diff --git a/internal/servants/docs_embed.go b/internal/servants/docs_embed.go new file mode 100644 index 00000000..aeb0b4cd --- /dev/null +++ b/internal/servants/docs_embed.go @@ -0,0 +1,17 @@ +//go:build docs +// +build docs + +package servants + +import ( + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/docs/openapi" + "github.com/rocboss/paopao-ce/internal/conf" +) + +// registerDocs register docs asset route +func registerDocs(e *gin.Engine) { + if conf.CfgIf("Docs:OpenAPI") { + e.StaticFS("/docs/openapi", openapi.NewFileSystem()) + } +} diff --git a/internal/servants/localoss.go b/internal/servants/localoss.go deleted file mode 100644 index b99a78f0..00000000 --- a/internal/servants/localoss.go +++ /dev/null @@ -1,5 +0,0 @@ -package servants - -type localossSrv struct { - // TODO -} diff --git a/internal/servants/localoss/localoss.go b/internal/servants/localoss/localoss.go new file mode 100644 index 00000000..ba37ddf8 --- /dev/null +++ b/internal/servants/localoss/localoss.go @@ -0,0 +1,28 @@ +package localoss + +import ( + "path/filepath" + + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/sirupsen/logrus" +) + +type localossSrv struct { + // TODO +} + +// RouteLocalOSS register LocalOSS route if needed +func RouteLocalOSS(e *gin.Engine) { + if !conf.CfgIf("LocalOSS") { + return + } + + savePath, err := filepath.Abs(conf.LocalOSSSetting.SavePath) + if err != nil { + logrus.Fatalf("get localOSS save path err: %v", err) + } + e.Static("/oss", savePath) + + logrus.Infof("register LocalOSS route in /oss on save path: %s", savePath) +} diff --git a/internal/servants/localoss/xerror.go b/internal/servants/localoss/xerror.go new file mode 100644 index 00000000..3014a991 --- /dev/null +++ b/internal/servants/localoss/xerror.go @@ -0,0 +1,11 @@ +package localoss + +import ( + "github.com/rocboss/paopao-ce/internal/servants/core/xerror" +) + +var ( + errFileUploadFailed = xerror.NewError(10200, "文件上传失败") + errFileInvalidExt = xerror.NewError(10201, "文件类型不合法") + errFileInvalidSize = xerror.NewError(10202, "文件大小超限") +) diff --git a/internal/servants/servants.go b/internal/servants/servants.go index 9cd595c7..fb03aff1 100644 --- a/internal/servants/servants.go +++ b/internal/servants/servants.go @@ -2,11 +2,18 @@ package servants import ( "github.com/gin-gonic/gin" - api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" + "github.com/rocboss/paopao-ce/internal/servants/localoss" "github.com/rocboss/paopao-ce/internal/servants/web" ) -// RegisterServants register all the servants to gin.Engine -func RegisterServants(e *gin.Engine) { - api.RegisterWebCoreServant(e, web.NewWebCoreSrv(), web.NewWebCoreBinding(), web.NewWebCoreRender()) +// RegisterWebServants register all the servants to gin.Engine +func RegisterWebServants(e *gin.Engine) { + // 按需注册 docs、静态资源 + { + registerDocs(e) + registerStatick(e) + } + + web.RouteWeb(e) + localoss.RouteLocalOSS(e) } diff --git a/internal/servants/statick.go b/internal/servants/statick.go new file mode 100644 index 00000000..d711dfe3 --- /dev/null +++ b/internal/servants/statick.go @@ -0,0 +1,13 @@ +//go:build !embed +// +build !embed + +package servants + +import ( + "github.com/gin-gonic/gin" +) + +// registerStatick stub function for register static asset route +func registerStatick(e *gin.Engine) { + // empty +} diff --git a/internal/servants/statick_embed.go b/internal/servants/statick_embed.go new file mode 100644 index 00000000..de212e55 --- /dev/null +++ b/internal/servants/statick_embed.go @@ -0,0 +1,27 @@ +//go:build embed +// +build embed + +package servants + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/web" +) + +// registerStatick register static assets route +func registerStatick(e *gin.Engine) { + routeStatic(e, "/", "/index.html", "/favicon.ico", "/assets/*filepath") +} + +func routeStatic(e *gin.Engine, paths ...string) { + staticHandler := http.FileServer(web.NewFileSystem()) + handler := func(c *gin.Context) { + staticHandler.ServeHTTP(c.Writer, c.Request) + } + for _, path := range paths { + e.GET(path, handler) + e.HEAD(path, handler) + } +} diff --git a/internal/servants/web/core.go b/internal/servants/web/core.go index 579b51b4..701e9fb2 100644 --- a/internal/servants/web/core.go +++ b/internal/servants/web/core.go @@ -25,3 +25,15 @@ type webCoreRender struct { core.BaseRender api.UnimplementedWebCoreRender } + +func newWebCoreSrv() api.WebCore { + return &webCoreSrv{} +} + +func newWebCoreBinding() api.WebCoreBinding { + return &webCoreBinding{} +} + +func newWebCoreRender() api.WebCoreRender { + return &webCoreRender{} +} diff --git a/internal/servants/web/web.go b/internal/servants/web/web.go index 5f505dc1..60a0aeb1 100644 --- a/internal/servants/web/web.go +++ b/internal/servants/web/web.go @@ -1,17 +1,11 @@ package web import ( + "github.com/gin-gonic/gin" api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" ) -func NewWebCoreSrv() api.WebCore { - return &webCoreSrv{} -} - -func NewWebCoreBinding() api.WebCoreBinding { - return &webCoreBinding{} -} - -func NewWebCoreRender() api.WebCoreRender { - return &webCoreRender{} +// RouteWeb register web route +func RouteWeb(e *gin.Engine) { + api.RegisterWebCoreServant(e, newWebCoreSrv(), newWebCoreBinding(), newWebCoreRender()) } diff --git a/internal/servants/web/xerror.go b/internal/servants/web/xerror.go new file mode 100644 index 00000000..0398f648 --- /dev/null +++ b/internal/servants/web/xerror.go @@ -0,0 +1,73 @@ +package web + +import ( + "github.com/rocboss/paopao-ce/internal/servants/core/xerror" +) + +var ( + errUsernameHasExisted = xerror.NewError(20001, "用户名已存在") + errUsernameLengthLimit = xerror.NewError(20002, "用户名长度3~12") + errUsernameCharLimit = xerror.NewError(20003, "用户名只能包含字母、数字") + errPasswordLengthLimit = xerror.NewError(20004, "密码长度6~16") + errUserRegisterFailed = xerror.NewError(20005, "用户注册失败") + errUserHasBeenBanned = xerror.NewError(20006, "该账户已被封停") + errNoPermission = xerror.NewError(20007, "无权限执行该请求") + errUserHasBindOTP = xerror.NewError(20008, "当前用户已绑定二次验证") + errUserOTPInvalid = xerror.NewError(20009, "二次验证码验证失败") + errUserNoBindOTP = xerror.NewError(20010, "当前用户未绑定二次验证") + errErrorOldPassword = xerror.NewError(20011, "当前用户密码验证失败") + errErrorCaptchaPassword = xerror.NewError(20012, "图形验证码验证失败") + errAccountNoPhoneBind = xerror.NewError(20013, "拒绝操作: 账户未绑定手机号") + errTooManyLoginError = xerror.NewError(20014, "登录失败次数过多,请稍后再试") + errGetPhoneCaptchaError = xerror.NewError(20015, "短信验证码获取失败") + errTooManyPhoneCaptchaSend = xerror.NewError(20016, "短信验证码获取次数已达今日上限") + errExistedUserPhone = xerror.NewError(20017, "该手机号已被绑定") + errErrorPhoneCaptcha = xerror.NewError(20018, "手机验证码不正确") + errMaxPhoneCaptchaUseTimes = xerror.NewError(20019, "手机验证码已达最大使用次数") + errNicknameLengthLimit = xerror.NewError(20020, "昵称长度2~12") + errNoExistUsername = xerror.NewError(20021, "用户不存在") + errNoAdminPermission = xerror.NewError(20022, "无管理权限") + + errGetPostsFailed = xerror.NewError(30001, "获取动态列表失败") + errCreatePostFailed = xerror.NewError(30002, "动态发布失败") + errGetPostFailed = xerror.NewError(30003, "获取动态详情失败") + errDeletePostFailed = xerror.NewError(30004, "动态删除失败") + errLockPostFailed = xerror.NewError(30005, "动态锁定失败") + errGetPostTagsFailed = xerror.NewError(30006, "获取话题列表失败") + errInvalidDownloadReq = xerror.NewError(30007, "附件下载请求不合法") + errDownloadReqError = xerror.NewError(30008, "附件下载请求失败") + errInsuffientDownloadMoney = xerror.NewError(30009, "附件下载失败:账户资金不足") + errDownloadExecFail = xerror.NewError(30010, "附件下载失败:扣费失败") + errStickPostFailed = xerror.NewError(30011, "动态置顶失败") + errVisblePostFailed = xerror.NewError(30012, "更新可见性失败") + + errGetCommentsFailed = xerror.NewError(40001, "获取评论列表失败") + errCreateCommentFailed = xerror.NewError(40002, "评论发布失败") + errGetCommentFailed = xerror.NewError(40003, "获取评论详情失败") + errDeleteCommentFailed = xerror.NewError(40004, "评论删除失败") + errCreateReplyFailed = xerror.NewError(40005, "评论回复失败") + errGetReplyFailed = xerror.NewError(40006, "获取评论详情失败") + errMaxCommentCount = xerror.NewError(40007, "评论数已达最大限制") + + errGetMessagesFailed = xerror.NewError(50001, "获取消息列表失败") + errReadMessageFailed = xerror.NewError(50002, "标记消息已读失败") + errSendWhisperFailed = xerror.NewError(50003, "私信发送失败") + errNoWhisperToSelf = xerror.NewError(50004, "不允许给自己发送私信") + errTooManyWhisperNum = xerror.NewError(50005, "今日私信次数已达上限") + + errGetCollectionsFailed = xerror.NewError(60001, "获取收藏列表失败") + errGetStarsFailed = xerror.NewError(60002, "获取点赞列表失败") + + errRechargeReqFail = xerror.NewError(70001, "充值请求失败") + errRechargeNotifyError = xerror.NewError(70002, "充值回调失败") + errGetRechargeFailed = xerror.NewError(70003, "充值详情获取失败") + + errNoRequestingFriendToSelf = xerror.NewError(80001, "不允许添加自己为好友") + errNotExistFriendId = xerror.NewError(80002, "好友id不存在") + errSendRequestingFriendFailed = xerror.NewError(80003, "申请添加朋友请求发送失败") + errAddFriendFailed = xerror.NewError(80004, "添加好友失败") + errRejectFriendFailed = xerror.NewError(80005, "拒绝好友失败") + errDeleteFriendFailed = xerror.NewError(80006, "删除好友失败") + errGetContactsFailed = xerror.NewError(80007, "获取联系人列表失败") + errNoActionToSelf = xerror.NewError(80008, "不允许对自己操作") +) From 8e88500d8a76821f2c1f448b26471e945ca04eaa Mon Sep 17 00:00:00 2001 From: Michael Li Date: Fri, 11 Nov 2022 16:19:39 +0800 Subject: [PATCH 04/28] add app service start/stop common logic --- internal/app/app.go | 48 ++++++++++++++--------------------- internal/app/web.go | 62 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 29 deletions(-) create mode 100644 internal/app/web.go diff --git a/internal/app/app.go b/internal/app/app.go index c38b473f..d35fb235 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -3,37 +3,27 @@ package app import ( "net/http" - "github.com/gin-contrib/cors" - "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/servants" ) -func NewWebEngine() *gin.Engine { - e := gin.New() - e.HandleMethodNotAllowed = true - e.Use(gin.Logger()) - e.Use(gin.Recovery()) - - // 跨域配置 - corsConfig := cors.DefaultConfig() - corsConfig.AllowAllOrigins = true - corsConfig.AddAllowHeaders("Authorization") - e.Use(cors.New(corsConfig)) - - // 默认404 - e.NoRoute(func(c *gin.Context) { - c.JSON(http.StatusNotFound, gin.H{ - "code": 404, - "msg": "Not Found", - }) - }) +type Service interface { + Start() + Stop() + Info() string +} - // 默认405 - e.NoMethod(func(c *gin.Context) { - c.JSON(http.StatusMethodNotAllowed, gin.H{ - "code": 405, - "msg": "Method Not Allowed", - }) - }) +func NewWebService() Service { + e := newWebEngine() + servants.RegisterWebServants(e) - return e + return &webService{ + server: &http.Server{ + Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort, + Handler: e, + ReadTimeout: conf.ServerSetting.ReadTimeout, + WriteTimeout: conf.ServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } } diff --git a/internal/app/web.go b/internal/app/web.go new file mode 100644 index 00000000..79d0f5a7 --- /dev/null +++ b/internal/app/web.go @@ -0,0 +1,62 @@ +package app + +import ( + "context" + "fmt" + "log" + "net/http" + + "github.com/fatih/color" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" +) + +type webService struct { + server *http.Server +} + +func (s *webService) Start() { + if err := s.server.ListenAndServe(); err != nil { + log.Fatalf("run app failed: %s", err) + } +} + +func (s *webService) Stop() { + s.server.Shutdown(context.Background()) +} + +func (s *webService) Info() string { + return fmt.Sprintf("PaoPao service listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)) +} + +func newWebEngine() *gin.Engine { + e := gin.New() + e.HandleMethodNotAllowed = true + e.Use(gin.Logger()) + e.Use(gin.Recovery()) + + // 跨域配置 + corsConfig := cors.DefaultConfig() + corsConfig.AllowAllOrigins = true + corsConfig.AddAllowHeaders("Authorization") + e.Use(cors.New(corsConfig)) + + // 默认404 + e.NoRoute(func(c *gin.Context) { + c.JSON(http.StatusNotFound, gin.H{ + "code": 404, + "msg": "Not Found", + }) + }) + + // 默认405 + e.NoMethod(func(c *gin.Context) { + c.JSON(http.StatusMethodNotAllowed, gin.H{ + "code": 405, + "msg": "Method Not Allowed", + }) + }) + + return e +} From 3c14ced54267284182e2898c824ee51909a50178 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Fri, 11 Nov 2022 22:08:10 +0800 Subject: [PATCH 05/28] optimize base code for binding/render --- internal/mirc/auto/api/v1/site.go | 35 ++++++++------ internal/servants/core/core.go | 47 +++++++++++++++++++ internal/servants/localoss/xerror.go | 2 +- internal/servants/web/core.go | 16 +++++-- internal/servants/web/xerror.go | 2 +- .../servants/core => pkg}/xerror/common.go | 0 .../servants/core => pkg}/xerror/xerror.go | 27 ++++++++++- 7 files changed, 107 insertions(+), 22 deletions(-) rename {internal/servants/core => pkg}/xerror/common.go (100%) rename {internal/servants/core => pkg}/xerror/xerror.go (78%) diff --git a/internal/mirc/auto/api/v1/site.go b/internal/mirc/auto/api/v1/site.go index 03c50281..f10eeb54 100644 --- a/internal/mirc/auto/api/v1/site.go +++ b/internal/mirc/auto/api/v1/site.go @@ -4,7 +4,6 @@ package v1 import ( "errors" - "net/http" gin "github.com/gin-gonic/gin" ) @@ -92,10 +91,14 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor type UnimplementedWebCoreServant struct{} // UnimplementedWebCoreBinding can be embedded to have forward compatible implementations. -type UnimplementedWebCoreBinding struct{} +type UnimplementedWebCoreBinding struct { + BindAny func(*gin.Context, any) error +} // UnimplementedWebCoreRender can be embedded to have forward compatible implementations. -type UnimplementedWebCoreRender struct{} +type UnimplementedWebCoreRender struct { + RenderAny func(*gin.Context, any, error) +} func (UnimplementedWebCoreServant) Chain() gin.HandlersChain { return nil @@ -119,26 +122,28 @@ func (UnimplementedWebCoreServant) Logout(c *gin.Context) error { func (UnimplementedWebCoreServant) mustEmbedUnimplementedWebCoreServant() {} -func (UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, error) { - return nil, errors.New("method BindLogin not implemented") +func (b *UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, error) { + obj := new(LoginReq) + err := b.BindAny(c, obj) + return obj, err } -func (UnimplementedWebCoreBinding) mustEmbedUnimplementedWebCoreBinding() {} +func (b *UnimplementedWebCoreBinding) mustEmbedUnimplementedWebCoreBinding() {} -func (UnimplementedWebCoreRender) RenderIndex(c *gin.Context, err error) { - c.String(http.StatusInternalServerError, "method RenderLogout not implemented") +func (r *UnimplementedWebCoreRender) RenderIndex(c *gin.Context, err error) { + r.RenderAny(c, nil, err) } -func (UnimplementedWebCoreRender) RenderArticles(c *gin.Context, err error) { - c.String(http.StatusInternalServerError, "method RenderLogout not implemented") +func (r *UnimplementedWebCoreRender) RenderArticles(c *gin.Context, err error) { + r.RenderAny(c, nil, err) } -func (UnimplementedWebCoreRender) RenderLogin(c *gin.Context, data *LoginResp, err error) { - c.String(http.StatusInternalServerError, "method RenderLogin not implemented") +func (r *UnimplementedWebCoreRender) RenderLogin(c *gin.Context, data *LoginResp, err error) { + r.RenderAny(c, data, err) } -func (UnimplementedWebCoreRender) RenderLogout(c *gin.Context, err error) { - c.String(http.StatusInternalServerError, "method RenderLogout not implemented") +func (r *UnimplementedWebCoreRender) RenderLogout(c *gin.Context, err error) { + r.RenderAny(c, nil, err) } -func (UnimplementedWebCoreRender) mustEmbedUnimplementedWebCoreRender() {} +func (r *UnimplementedWebCoreRender) mustEmbedUnimplementedWebCoreRender() {} diff --git a/internal/servants/core/core.go b/internal/servants/core/core.go index 6bedfa92..7e744dab 100644 --- a/internal/servants/core/core.go +++ b/internal/servants/core/core.go @@ -1,8 +1,13 @@ package core import ( + "fmt" + "net/http" + "os" + "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/pkg/xerror" ) type BaseServant struct { @@ -24,3 +29,45 @@ func (BaseServant) userFrom(c *gin.Context) (*model.User, bool) { } return nil, false } + +func BindAny(c *gin.Context, obj any) error { + var errs xerror.ValidErrors + err := c.ShouldBind(obj) + if err != nil { + return fmt.Errorf("bind errs: %w", xerror.InvalidParams.WithDetails(errs.Error())) + } + return nil +} + +func RenderAny(c *gin.Context, data any, err error) { + if err == nil { + hostname, _ := os.Hostname() + if data == nil { + data = gin.H{ + "code": 0, + "msg": "success", + "tracehost": hostname, + } + } else { + data = gin.H{ + "code": 0, + "msg": "success", + "data": data, + "tracehost": hostname, + } + } + c.JSON(http.StatusOK, data) + } else { + // TODO: error process logic + resp := gin.H{"code": http.StatusInternalServerError, "msg": err.Error()} + // xerr := &xerror.Error{} + // if errors.As(err, xerr) { + // resp["code"], resp["msg"] = xerr.Code(), xerr.Msg() + // details := xerr.Details() + // if len(details) > 0 { + // resp["details"] = details + // } + // } + c.JSON(http.StatusInternalServerError, resp) + } +} diff --git a/internal/servants/localoss/xerror.go b/internal/servants/localoss/xerror.go index 3014a991..7b656b7d 100644 --- a/internal/servants/localoss/xerror.go +++ b/internal/servants/localoss/xerror.go @@ -1,7 +1,7 @@ package localoss import ( - "github.com/rocboss/paopao-ce/internal/servants/core/xerror" + "github.com/rocboss/paopao-ce/pkg/xerror" ) var ( diff --git a/internal/servants/web/core.go b/internal/servants/web/core.go index 701e9fb2..4a4ccd32 100644 --- a/internal/servants/web/core.go +++ b/internal/servants/web/core.go @@ -18,12 +18,12 @@ type webCoreSrv struct { type webCoreBinding struct { core.BaseBinding - api.UnimplementedWebCoreBinding + *api.UnimplementedWebCoreBinding } type webCoreRender struct { core.BaseRender - api.UnimplementedWebCoreRender + *api.UnimplementedWebCoreRender } func newWebCoreSrv() api.WebCore { @@ -31,9 +31,17 @@ func newWebCoreSrv() api.WebCore { } func newWebCoreBinding() api.WebCoreBinding { - return &webCoreBinding{} + return &webCoreBinding{ + UnimplementedWebCoreBinding: &api.UnimplementedWebCoreBinding{ + BindAny: core.BindAny, + }, + } } func newWebCoreRender() api.WebCoreRender { - return &webCoreRender{} + return &webCoreRender{ + UnimplementedWebCoreRender: &api.UnimplementedWebCoreRender{ + RenderAny: core.RenderAny, + }, + } } diff --git a/internal/servants/web/xerror.go b/internal/servants/web/xerror.go index 0398f648..305d1d0c 100644 --- a/internal/servants/web/xerror.go +++ b/internal/servants/web/xerror.go @@ -1,7 +1,7 @@ package web import ( - "github.com/rocboss/paopao-ce/internal/servants/core/xerror" + "github.com/rocboss/paopao-ce/pkg/xerror" ) var ( diff --git a/internal/servants/core/xerror/common.go b/pkg/xerror/common.go similarity index 100% rename from internal/servants/core/xerror/common.go rename to pkg/xerror/common.go diff --git a/internal/servants/core/xerror/xerror.go b/pkg/xerror/xerror.go similarity index 78% rename from internal/servants/core/xerror/xerror.go rename to pkg/xerror/xerror.go index b1b8a23a..5053b62f 100644 --- a/internal/servants/core/xerror/xerror.go +++ b/pkg/xerror/xerror.go @@ -3,6 +3,11 @@ package xerror import ( "fmt" "net/http" + "strings" +) + +var ( + codes = map[int]string{} ) type Error struct { @@ -11,7 +16,27 @@ type Error struct { details []string } -var codes = map[int]string{} +type ValidError struct { + Message string +} + +type ValidErrors []*ValidError + +func (v *ValidError) Error() string { + return v.Message +} + +func (v ValidErrors) Error() string { + return strings.Join(v.Errors(), ",") +} + +func (v ValidErrors) Errors() []string { + var errs []string + for _, err := range v { + errs = append(errs, err.Error()) + } + return errs +} func NewError(code int, msg string) *Error { if _, ok := codes[code]; ok { From 0eda77775fcfe1bc3048f192fd7b2c75bb1b9c74 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 12 Nov 2022 23:07:11 +0800 Subject: [PATCH 06/28] mv app's logic to service --- internal/app/app.go | 29 ----------------------------- internal/service/service.go | 24 ++++++++++++++++++++++++ internal/{app => service}/web.go | 2 +- 3 files changed, 25 insertions(+), 30 deletions(-) delete mode 100644 internal/app/app.go rename internal/{app => service}/web.go (98%) diff --git a/internal/app/app.go b/internal/app/app.go deleted file mode 100644 index d35fb235..00000000 --- a/internal/app/app.go +++ /dev/null @@ -1,29 +0,0 @@ -package app - -import ( - "net/http" - - "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/servants" -) - -type Service interface { - Start() - Stop() - Info() string -} - -func NewWebService() Service { - e := newWebEngine() - servants.RegisterWebServants(e) - - return &webService{ - server: &http.Server{ - Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort, - Handler: e, - ReadTimeout: conf.ServerSetting.ReadTimeout, - WriteTimeout: conf.ServerSetting.WriteTimeout, - MaxHeaderBytes: 1 << 20, - }, - } -} diff --git a/internal/service/service.go b/internal/service/service.go index d7afba23..b35bc541 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -1,10 +1,13 @@ package service import ( + "net/http" + "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/dao" "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/servants" "github.com/sirupsen/logrus" ) @@ -15,6 +18,27 @@ var ( DisablePhoneVerify bool ) +type Service interface { + Start() + Stop() + Info() string +} + +func NewWebService() Service { + e := newWebEngine() + servants.RegisterWebServants(e) + + return &webService{ + server: &http.Server{ + Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort, + Handler: e, + ReadTimeout: conf.ServerSetting.ReadTimeout, + WriteTimeout: conf.ServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } +} + func Initialize() { ds = dao.DataService() ts = dao.TweetSearchService() diff --git a/internal/app/web.go b/internal/service/web.go similarity index 98% rename from internal/app/web.go rename to internal/service/web.go index 79d0f5a7..458d8fa4 100644 --- a/internal/app/web.go +++ b/internal/service/web.go @@ -1,4 +1,4 @@ -package app +package service import ( "context" From 7b325e33b81a373ef7454d4b1c3621c5476d42d2 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Tue, 15 Nov 2022 15:50:24 +0800 Subject: [PATCH 07/28] optimzie error process logic adapter mir --- internal/mirc/auto/api/v1/site.go | 53 ++++++++++++++++--------------- internal/servants/core/core.go | 10 +++--- 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/internal/mirc/auto/api/v1/site.go b/internal/mirc/auto/api/v1/site.go index f10eeb54..22e9e826 100644 --- a/internal/mirc/auto/api/v1/site.go +++ b/internal/mirc/auto/api/v1/site.go @@ -3,9 +3,10 @@ package v1 import ( - "errors" + "net/http" - gin "github.com/gin-gonic/gin" + "github.com/alimy/mir/v3" + "github.com/gin-gonic/gin" ) type AgentInfo struct { @@ -37,25 +38,25 @@ type WebCore interface { // Chain provide handlers chain for gin Chain() gin.HandlersChain - Index(c *gin.Context) error - Articles(c *gin.Context) error - Login(c *gin.Context, req *LoginReq) (*LoginResp, error) - Logout(c *gin.Context) error + Index(c *gin.Context) mir.Error + Articles(c *gin.Context) mir.Error + Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + Logout(c *gin.Context) mir.Error mustEmbedUnimplementedWebCoreServant() } type WebCoreBinding interface { - BindLogin(c *gin.Context) (*LoginReq, error) + BindLogin(c *gin.Context) (*LoginReq, mir.Error) mustEmbedUnimplementedWebCoreBinding() } type WebCoreRender interface { - RenderIndex(c *gin.Context, err error) - RenderArticles(c *gin.Context, err error) - RenderLogin(c *gin.Context, data *LoginResp, err error) - RenderLogout(c *gin.Context, err error) + RenderIndex(c *gin.Context, err mir.Error) + RenderArticles(c *gin.Context, err mir.Error) + RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + RenderLogout(c *gin.Context, err mir.Error) mustEmbedUnimplementedWebCoreRender() } @@ -92,37 +93,37 @@ type UnimplementedWebCoreServant struct{} // UnimplementedWebCoreBinding can be embedded to have forward compatible implementations. type UnimplementedWebCoreBinding struct { - BindAny func(*gin.Context, any) error + BindAny func(*gin.Context, any) mir.Error } // UnimplementedWebCoreRender can be embedded to have forward compatible implementations. type UnimplementedWebCoreRender struct { - RenderAny func(*gin.Context, any, error) + RenderAny func(*gin.Context, any, mir.Error) } func (UnimplementedWebCoreServant) Chain() gin.HandlersChain { return nil } -func (UnimplementedWebCoreServant) Index(c *gin.Context) error { - return errors.New("method Index not implemented") +func (UnimplementedWebCoreServant) Index(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedWebCoreServant) Articles(c *gin.Context) error { - return errors.New("method Index not implemented") +func (UnimplementedWebCoreServant) Articles(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedWebCoreServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, error) { - return nil, errors.New("method Login not implemented") +func (UnimplementedWebCoreServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { + return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedWebCoreServant) Logout(c *gin.Context) error { - return errors.New("method Logout not implemented") +func (UnimplementedWebCoreServant) Logout(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } func (UnimplementedWebCoreServant) mustEmbedUnimplementedWebCoreServant() {} -func (b *UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, error) { +func (b *UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) { obj := new(LoginReq) err := b.BindAny(c, obj) return obj, err @@ -130,19 +131,19 @@ func (b *UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, erro func (b *UnimplementedWebCoreBinding) mustEmbedUnimplementedWebCoreBinding() {} -func (r *UnimplementedWebCoreRender) RenderIndex(c *gin.Context, err error) { +func (r *UnimplementedWebCoreRender) RenderIndex(c *gin.Context, err mir.Error) { r.RenderAny(c, nil, err) } -func (r *UnimplementedWebCoreRender) RenderArticles(c *gin.Context, err error) { +func (r *UnimplementedWebCoreRender) RenderArticles(c *gin.Context, err mir.Error) { r.RenderAny(c, nil, err) } -func (r *UnimplementedWebCoreRender) RenderLogin(c *gin.Context, data *LoginResp, err error) { +func (r *UnimplementedWebCoreRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) { r.RenderAny(c, data, err) } -func (r *UnimplementedWebCoreRender) RenderLogout(c *gin.Context, err error) { +func (r *UnimplementedWebCoreRender) RenderLogout(c *gin.Context, err mir.Error) { r.RenderAny(c, nil, err) } diff --git a/internal/servants/core/core.go b/internal/servants/core/core.go index 7e744dab..6dad41e7 100644 --- a/internal/servants/core/core.go +++ b/internal/servants/core/core.go @@ -1,10 +1,10 @@ package core import ( - "fmt" "net/http" "os" + "github.com/alimy/mir/v3" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/xerror" @@ -30,16 +30,16 @@ func (BaseServant) userFrom(c *gin.Context) (*model.User, bool) { return nil, false } -func BindAny(c *gin.Context, obj any) error { +func BindAny(c *gin.Context, obj any) mir.Error { var errs xerror.ValidErrors err := c.ShouldBind(obj) if err != nil { - return fmt.Errorf("bind errs: %w", xerror.InvalidParams.WithDetails(errs.Error())) + return mir.NewError(xerror.InvalidParams.Code(), xerror.InvalidParams.WithDetails(errs.Error())) } return nil } -func RenderAny(c *gin.Context, data any, err error) { +func RenderAny(c *gin.Context, data any, err mir.Error) { if err == nil { hostname, _ := os.Hostname() if data == nil { @@ -59,7 +59,7 @@ func RenderAny(c *gin.Context, data any, err error) { c.JSON(http.StatusOK, data) } else { // TODO: error process logic - resp := gin.H{"code": http.StatusInternalServerError, "msg": err.Error()} + resp := gin.H{"code": err.StatusCode(), "msg": err.Error()} // xerr := &xerror.Error{} // if errors.As(err, xerr) { // resp["code"], resp["msg"] = xerr.Code(), xerr.Msg() From e81772005d721f6936bfaac715b31f3b04ce73a1 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Thu, 17 Nov 2022 17:49:37 +0800 Subject: [PATCH 08/28] optimize service define in pkg/service package --- internal/service/service.go | 4 +++- internal/service/web.go | 18 +++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/internal/service/service.go b/internal/service/service.go index 7236fba2..4f9434f4 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -20,9 +20,11 @@ var ( ) type Service interface { + Name() string + PreStart() string + PreStop() string Start() Stop() - Info() string } func NewWebService() Service { diff --git a/internal/service/web.go b/internal/service/web.go index 458d8fa4..d346fbd8 100644 --- a/internal/service/web.go +++ b/internal/service/web.go @@ -12,10 +12,26 @@ import ( "github.com/rocboss/paopao-ce/internal/conf" ) +type baseService struct{} + type webService struct { + baseService + server *http.Server } +func (baseService) PreStart() string { + return "" +} + +func (baseService) PreStop() string { + return "" +} + +func (s *webService) Name() string { + return "WebService" +} + func (s *webService) Start() { if err := s.server.ListenAndServe(); err != nil { log.Fatalf("run app failed: %s", err) @@ -26,7 +42,7 @@ func (s *webService) Stop() { s.server.Shutdown(context.Background()) } -func (s *webService) Info() string { +func (s *webService) PreStart() string { return fmt.Sprintf("PaoPao service listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)) } From 59ef538dc3f5ba73aab8421bb445a7fca2e7eda8 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Mon, 21 Nov 2022 12:02:13 +0800 Subject: [PATCH 09/28] mir: add initial proposal document --- ...05-引入go-mir优化后端架构设计.md | 28 +++++++++++++++++++ docs/proposal/README.md | 3 +- 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 docs/proposal/005-引入go-mir优化后端架构设计.md diff --git a/docs/proposal/005-引入go-mir优化后端架构设计.md b/docs/proposal/005-引入go-mir优化后端架构设计.md new file mode 100644 index 00000000..f446bf5d --- /dev/null +++ b/docs/proposal/005-引入go-mir优化后端架构设计.md @@ -0,0 +1,28 @@ +| 编号 | 作者 | 发表时间 | 变更时间 | 版本 | 状态 | +| ----- | ----- | ----- | ----- | ----- | ----- | +| 005| 北野 | 2022-11-21 | 2022-11-21 | v0.0 | 提议 | + +### 引入go-mir优化后端架构设计 + 引入[github.com/alimy/mir/v3](https://github.com/alimy/mir)优化后端的架构设计,使得后端代码更具扩展型。 + +### 需求 +* 更方便添加后端功能项的实现; +* 优化代码结构,模块化、清晰化代码布局,使得更具扩展性; +* 兼容RESTful/gRPC 服务代码,RESTful API是服务于Web/Admin,gRPC API是提供给移动端(iOS/Android)的服务; + +### 方案 + +依赖库: +* [go-mir](https://github.com/alimy/mir) + +### 疑问 + +1. 为什么引入go-mir? +TODO; +1. 为什么要兼容RESTful/gRPC服务? +RESTful API是提供给Web端使用的,包括paopao-ce web端以及后期的运维端admin; gRPC API是提供给移动端(iOS/Android)使用的服务。RESTful API天然对web端浏览器友好,而gRPC生态对后端、移动端天然友好,可以根据google-protocol-buffers DSL定义服务API自动生成服务端、客户端代码,非常利于开发,特别是移动端开发,省去了编写客户端网络数据服务相关的业务逻辑,只需要专注于页面逻辑编写,后端数据获取的网络数据访问逻辑直接调用自动生成的gRPC API客户端代码即可,大大的减轻移动端开发的心智负担。后端引入gRPC主要就是考虑到移动端(iOS/Android)开发的开发效率,在减轻移动端开发网络数据获取业务逻辑的心智负担上,gRPC生态与RESTful生态相比优势明显,因此强力引入。再一个就是[go-mir](https://github.com/alimy/mir) v3为RESTful服务的开发提供类似gRPC服务的开发体验,也为后端兼容RESTful/gRPC服务创造了很好的条件,只要代码结构组织清晰,将会有很好的后端开发体验。 + >*目前移动端 iOS/Android APP还在规划中,这里后续的后端gRPC API服务也是为此做准备,敬请期待~* + +### 更新记录 +#### v0.0(2022-11-21) - 北野 +* 初始文档 \ No newline at end of file diff --git a/docs/proposal/README.md b/docs/proposal/README.md index 8301b365..42a4dda0 100644 --- a/docs/proposal/README.md +++ b/docs/proposal/README.md @@ -1,4 +1,5 @@ ## Draft * [001-关于paopao-ce的设计定位](001-关于paopao-ce的设计定位.md "关于paopao-ce的设计定位") * [002-关于Friendship功能项的设计](002-关于Friendship功能项的设计.md "关于Friendship功能项的设计") -* [003-关于Followship功能项的设计](003-关于Followship功能项的设计.md "关于Followship功能项的设计") \ No newline at end of file +* [003-关于Followship功能项的设计](003-关于Followship功能项的设计.md "关于Followship功能项的设计") +* [005-引入go-mir优化后端架构设计](005-引入go-mir优化后端架构设计.md "引入go-mir优化后端架构设计") \ No newline at end of file From df1744fc648dc9ef9b47cf61778cc1faa056811a Mon Sep 17 00:00:00 2001 From: Michael Li Date: Fri, 25 Nov 2022 23:57:16 +0800 Subject: [PATCH 10/28] optimize servants code layout --- internal/servants/docs.go | 13 ------------- internal/servants/docs/docs.go | 13 +++++++++++++ internal/servants/{ => docs}/docs_embed.go | 6 +++--- internal/servants/servants.go | 6 ++++-- internal/servants/statick.go | 13 ------------- internal/servants/statick/statick.go | 13 +++++++++++++ internal/servants/{ => statick}/statick_embed.go | 6 +++--- internal/version/version.go | 8 -------- 8 files changed, 36 insertions(+), 42 deletions(-) delete mode 100644 internal/servants/docs.go create mode 100644 internal/servants/docs/docs.go rename internal/servants/{ => docs}/docs_embed.go (72%) delete mode 100644 internal/servants/statick.go create mode 100644 internal/servants/statick/statick.go rename internal/servants/{ => statick}/statick_embed.go (82%) delete mode 100644 internal/version/version.go diff --git a/internal/servants/docs.go b/internal/servants/docs.go deleted file mode 100644 index 9d53cac5..00000000 --- a/internal/servants/docs.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !docs -// +build !docs - -package servants - -import ( - "github.com/gin-gonic/gin" -) - -// registerDocs stub function for register docs asset route -func registerDocs(e *gin.Engine) { - // empty -} diff --git a/internal/servants/docs/docs.go b/internal/servants/docs/docs.go new file mode 100644 index 00000000..ef062a47 --- /dev/null +++ b/internal/servants/docs/docs.go @@ -0,0 +1,13 @@ +//go:build !docs +// +build !docs + +package docs + +import ( + "github.com/gin-gonic/gin" +) + +// RegisterDocs stub function for register docs asset route +func RegisterDocs(e *gin.Engine) { + // empty +} diff --git a/internal/servants/docs_embed.go b/internal/servants/docs/docs_embed.go similarity index 72% rename from internal/servants/docs_embed.go rename to internal/servants/docs/docs_embed.go index 1d7efb0f..da457e50 100644 --- a/internal/servants/docs_embed.go +++ b/internal/servants/docs/docs_embed.go @@ -1,7 +1,7 @@ //go:build docs // +build docs -package servants +package docs import ( "github.com/gin-gonic/gin" @@ -9,8 +9,8 @@ import ( "github.com/rocboss/paopao-ce/pkg/cfg" ) -// registerDocs register docs asset route -func registerDocs(e *gin.Engine) { +// RegisterDocs register docs asset route +func RegisterDocs(e *gin.Engine) { cfg.Be("Docs:OpenAPI", func() { e.StaticFS("/docs/openapi", openapi.NewFileSystem()) }) diff --git a/internal/servants/servants.go b/internal/servants/servants.go index c61dcc82..4c36c0d6 100644 --- a/internal/servants/servants.go +++ b/internal/servants/servants.go @@ -2,7 +2,9 @@ package servants import ( "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/servants/docs" "github.com/rocboss/paopao-ce/internal/servants/localoss" + "github.com/rocboss/paopao-ce/internal/servants/statick" "github.com/rocboss/paopao-ce/internal/servants/web" "github.com/rocboss/paopao-ce/pkg/cfg" ) @@ -11,8 +13,8 @@ import ( func RegisterWebServants(e *gin.Engine) { // 按需注册 docs、静态资源 { - registerDocs(e) - registerStatick(e) + docs.RegisterDocs(e) + statick.RegisterStatick(e) } web.RouteWeb(e) diff --git a/internal/servants/statick.go b/internal/servants/statick.go deleted file mode 100644 index d711dfe3..00000000 --- a/internal/servants/statick.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !embed -// +build !embed - -package servants - -import ( - "github.com/gin-gonic/gin" -) - -// registerStatick stub function for register static asset route -func registerStatick(e *gin.Engine) { - // empty -} diff --git a/internal/servants/statick/statick.go b/internal/servants/statick/statick.go new file mode 100644 index 00000000..a852bdfc --- /dev/null +++ b/internal/servants/statick/statick.go @@ -0,0 +1,13 @@ +//go:build !embed +// +build !embed + +package statick + +import ( + "github.com/gin-gonic/gin" +) + +// RegisterStatick stub function for register static asset route +func RegisterStatick(e *gin.Engine) { + // empty +} diff --git a/internal/servants/statick_embed.go b/internal/servants/statick/statick_embed.go similarity index 82% rename from internal/servants/statick_embed.go rename to internal/servants/statick/statick_embed.go index de212e55..6dd4c77b 100644 --- a/internal/servants/statick_embed.go +++ b/internal/servants/statick/statick_embed.go @@ -1,7 +1,7 @@ //go:build embed // +build embed -package servants +package statick import ( "net/http" @@ -10,8 +10,8 @@ import ( "github.com/rocboss/paopao-ce/web" ) -// registerStatick register static assets route -func registerStatick(e *gin.Engine) { +// RegisterStatick register static assets route +func RegisterStatick(e *gin.Engine) { routeStatic(e, "/", "/index.html", "/favicon.ico", "/assets/*filepath") } diff --git a/internal/version/version.go b/internal/version/version.go deleted file mode 100644 index b3bcb903..00000000 --- a/internal/version/version.go +++ /dev/null @@ -1,8 +0,0 @@ -package version - -var ( - // GitHash Value will be set during build - GitHash = "" - // BuildTime Value will be set during build - BuildTime = "" -) From 7636412940d282205d3a9acfafb443d32b169039 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Fri, 2 Dec 2022 21:18:51 +0800 Subject: [PATCH 11/28] mir: optimize source code layout for import go-mir --- docs/openapi/embed.go | 4 + internal/broker/broker.go | 5 + internal/{ => broker}/migration/migration.go | 4 + .../{ => broker}/migration/migration_embed.go | 4 + internal/conf/conf.go | 4 + internal/conf/db.go | 4 + internal/conf/db_cgo.go | 4 + internal/conf/db_nocgo.go | 4 + internal/conf/logger.go | 4 + internal/conf/logger_meili.go | 4 + internal/conf/logger_zinc.go | 4 + internal/conf/settting.go | 4 + internal/core/authority.go | 39 ++-- internal/core/cache.go | 14 +- internal/core/comments.go | 36 ++- internal/core/core.go | 4 + internal/core/messages.go | 33 ++- internal/core/search.go | 47 ++-- internal/core/security.go | 14 +- internal/core/storage.go | 4 + internal/core/topics.go | 19 +- internal/core/tweets.go | 88 +++++--- internal/core/types.go | 24 ++ internal/core/user.go | 36 ++- internal/core/version.go | 4 + internal/core/wallet.go | 21 +- internal/dao/cache/bigcache.go | 22 +- internal/dao/cache/cache.go | 4 + internal/dao/cache/none.go | 10 +- internal/dao/cache/simple.go | 16 +- internal/dao/dao.go | 4 + internal/dao/jinzhu/authority.go | 18 +- internal/dao/jinzhu/comments.go | 50 +++-- internal/dao/jinzhu/contacts.go | 81 +++---- internal/dao/jinzhu/dbr/attachment.go | 12 +- internal/dao/jinzhu/dbr/captcha.go | 6 +- internal/dao/jinzhu/dbr/comment.go | 6 +- internal/dao/jinzhu/dbr/comment_content.go | 8 +- internal/dao/jinzhu/dbr/comment_reply.go | 6 +- internal/dao/jinzhu/dbr/contact.go | 6 +- internal/dao/jinzhu/dbr/dbr.go | 36 --- internal/dao/jinzhu/dbr/message.go | 6 +- internal/{model => dao/jinzhu/dbr}/model.go | 6 +- internal/dao/jinzhu/dbr/post.go | 6 +- .../dao/jinzhu/dbr/post_attachment_bill.go | 6 +- internal/dao/jinzhu/dbr/post_collection.go | 6 +- internal/dao/jinzhu/dbr/post_content.go | 33 +-- internal/dao/jinzhu/dbr/post_star.go | 6 +- internal/dao/jinzhu/dbr/tag.go | 6 +- internal/dao/jinzhu/dbr/user.go | 6 +- internal/dao/jinzhu/dbr/wallet_recharge.go | 6 +- internal/dao/jinzhu/dbr/wallet_statement.go | 6 +- internal/dao/jinzhu/index.go | 33 +-- internal/dao/jinzhu/jinzhu.go | 4 + internal/dao/jinzhu/messages.go | 30 +-- internal/dao/jinzhu/security.go | 14 +- internal/dao/jinzhu/topics.go | 22 +- internal/dao/jinzhu/tweets.go | 140 ++++++------ internal/dao/jinzhu/user.go | 46 ++-- internal/dao/jinzhu/utils.go | 18 +- internal/dao/jinzhu/wallet.go | 46 ++-- internal/dao/sakila/sakila.go | 4 + internal/dao/search/bridge.go | 7 +- internal/dao/search/filter.go | 15 +- internal/dao/search/meili.go | 47 ++-- internal/dao/search/search.go | 17 +- internal/dao/search/zinc.go | 17 +- internal/dao/security/attachment.go | 4 + internal/dao/slonik/slonik.go | 4 + internal/dao/storage/alioss.go | 4 + internal/dao/storage/cos.go | 4 + internal/dao/storage/huaweiobs.go | 4 + internal/dao/storage/localoss.go | 4 + internal/dao/storage/minio.go | 4 + internal/dao/storage/storage.go | 4 + internal/internal.go | 12 +- internal/middleware/admin.go | 25 --- internal/middleware/jwt.go | 113 ---------- internal/middleware/priv.go | 45 ---- internal/mirc/main.go | 4 + internal/model/attachment.go | 27 --- internal/model/captcha.go | 38 ---- internal/model/comment.go | 127 ----------- internal/model/comment_content.go | 59 ----- internal/model/comment_reply.go | 110 --------- internal/model/contact.go | 119 ---------- internal/model/message.go | 148 ------------- internal/model/post.go | 208 ------------------ internal/model/post_attachment_bill.go | 36 --- internal/model/post_collection.go | 102 --------- internal/model/post_content.go | 121 ---------- internal/model/post_star.go | 98 --------- internal/model/rest/contacts.go | 31 --- internal/model/rest/tweets.go | 8 - internal/model/rest/user.go | 11 - internal/model/tag.go | 97 -------- internal/model/user.go | 94 -------- internal/model/wallet_recharge.go | 34 --- internal/model/wallet_statement.go | 83 ------- internal/proto/gen.go | 5 + internal/proto/tweets.proto | 10 + .../servants/{core/core.go => base/base.go} | 12 +- internal/servants/chain/admin.go | 10 +- internal/servants/chain/jwt.go | 14 +- internal/servants/chain/priv.go | 12 +- internal/servants/docs/docs.go | 4 + internal/servants/docs/docs_embed.go | 4 + internal/servants/localoss/localoss.go | 4 + internal/servants/localoss/xerror.go | 4 + internal/servants/servants.go | 4 + internal/servants/statick/statick.go | 4 + internal/servants/statick/statick_embed.go | 4 + internal/servants/web/admin.go | 4 + internal/servants/web/alipay.go | 4 + internal/servants/web/broker/attachment.go | 13 ++ .../web/broker}/avatar.go | 6 +- internal/servants/web/broker/broker.go | 48 ++++ .../web/broker}/comment.go | 60 ++--- .../web/broker}/message.go | 16 +- .../{service => servants/web/broker}/post.go | 114 +++++----- .../{service => servants/web/broker}/sign.go | 6 +- .../{service => servants/web/broker}/user.go | 106 +++++---- .../web/broker}/wallet.go | 14 +- internal/servants/web/core.go | 16 +- internal/servants/web/followship.go | 4 + internal/servants/web/friendship.go | 4 + internal/servants/web/loose.go | 4 + internal/servants/web/priv.go | 4 + internal/servants/web/pub.go | 4 + .../{ => servants/web}/routers/api/api.go | 4 + .../web}/routers/api/assets/comic.ttf | Bin .../web}/routers/api/attachment.go | 50 +++-- .../{ => servants/web}/routers/api/comment.go | 34 +-- .../{ => servants/web}/routers/api/home.go | 16 +- .../{ => servants/web}/routers/api/message.go | 26 ++- .../{ => servants/web}/routers/api/post.go | 65 +++--- .../{ => servants/web}/routers/api/user.go | 127 +++++------ internal/{ => servants/web}/routers/docs.go | 4 + .../{ => servants/web}/routers/docs_embed.go | 4 + internal/{ => servants/web}/routers/router.go | 16 +- .../{ => servants/web}/routers/statick.go | 4 + .../web}/routers/statick_embed.go | 4 + internal/servants/web/web.go | 4 + internal/servants/web/xerror.go | 4 + internal/service/attachment.go | 7 - internal/service/service.go | 69 +----- internal/service/web.go | 31 ++- main.go | 6 +- pkg/app/app.go | 4 + pkg/app/form.go | 4 + pkg/app/jwt.go | 8 +- pkg/app/pagination.go | 4 + pkg/cfg/cfg.go | 4 + pkg/cfg/cfg_test.go | 4 + pkg/cfg/feature.go | 4 + pkg/cfg/feature_test.go | 4 + pkg/convert/convert.go | 4 + pkg/convert/convert_test.go | 4 + pkg/crypto/signature.go | 4 + pkg/debug/version.go | 4 + pkg/errcode/common_code.go | 4 + pkg/errcode/errcode.go | 4 + pkg/errcode/module_code.go | 4 + pkg/sign/sign.go | 4 + pkg/types/types.go | 4 + pkg/util/banner.go | 4 + pkg/util/ip.go | 4 + pkg/util/ip_test.go | 4 + pkg/util/iploc/iploc.go | 4 + pkg/util/iploc/iploc_test.go | 4 + pkg/util/md5.go | 4 + pkg/util/md5_test.go | 4 + pkg/util/str.go | 4 + pkg/xerror/common.go | 4 + pkg/xerror/xerror.go | 4 + pkg/zinc/zinc.go | 4 + scripts/migration/embed.go | 4 + web/embed.go | 4 + 178 files changed, 1566 insertions(+), 2603 deletions(-) create mode 100644 internal/broker/broker.go rename internal/{ => broker}/migration/migration.go (64%) rename internal/{ => broker}/migration/migration_embed.go (94%) create mode 100644 internal/core/types.go delete mode 100644 internal/dao/jinzhu/dbr/dbr.go rename internal/{model => dao/jinzhu/dbr}/model.go (83%) delete mode 100644 internal/middleware/admin.go delete mode 100644 internal/middleware/jwt.go delete mode 100644 internal/middleware/priv.go delete mode 100644 internal/model/attachment.go delete mode 100644 internal/model/captcha.go delete mode 100644 internal/model/comment.go delete mode 100644 internal/model/comment_content.go delete mode 100644 internal/model/comment_reply.go delete mode 100644 internal/model/contact.go delete mode 100644 internal/model/message.go delete mode 100644 internal/model/post.go delete mode 100644 internal/model/post_attachment_bill.go delete mode 100644 internal/model/post_collection.go delete mode 100644 internal/model/post_content.go delete mode 100644 internal/model/post_star.go delete mode 100644 internal/model/rest/contacts.go delete mode 100644 internal/model/rest/tweets.go delete mode 100644 internal/model/rest/user.go delete mode 100644 internal/model/tag.go delete mode 100644 internal/model/user.go delete mode 100644 internal/model/wallet_recharge.go delete mode 100644 internal/model/wallet_statement.go create mode 100644 internal/proto/gen.go create mode 100644 internal/proto/tweets.proto rename internal/servants/{core/core.go => base/base.go} (81%) create mode 100644 internal/servants/web/broker/attachment.go rename internal/{service => servants/web/broker}/avatar.go (95%) create mode 100644 internal/servants/web/broker/broker.go rename internal/{service => servants/web/broker}/comment.go (83%) rename internal/{service => servants/web/broker}/message.go (84%) rename internal/{service => servants/web/broker}/post.go (76%) rename internal/{service => servants/web/broker}/sign.go (79%) rename internal/{service => servants/web/broker}/user.go (76%) rename internal/{service => servants/web/broker}/wallet.go (69%) rename internal/{ => servants/web}/routers/api/api.go (89%) rename internal/{ => servants/web}/routers/api/assets/comic.ttf (100%) rename internal/{ => servants/web}/routers/api/attachment.go (79%) rename internal/{ => servants/web}/routers/api/comment.go (75%) rename internal/{ => servants/web}/routers/api/home.go (86%) rename internal/{ => servants/web}/routers/api/message.go (74%) rename internal/{ => servants/web}/routers/api/post.go (79%) rename internal/{ => servants/web}/routers/api/user.go (80%) rename internal/{ => servants/web}/routers/docs.go (57%) rename internal/{ => servants/web}/routers/docs_embed.go (69%) rename internal/{ => servants/web}/routers/router.go (92%) rename internal/{ => servants/web}/routers/statick.go (58%) rename internal/{ => servants/web}/routers/statick_embed.go (79%) delete mode 100644 internal/service/attachment.go diff --git a/docs/openapi/embed.go b/docs/openapi/embed.go index 8500ca3c..e72721fb 100644 --- a/docs/openapi/embed.go +++ b/docs/openapi/embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build docs // +build docs diff --git a/internal/broker/broker.go b/internal/broker/broker.go new file mode 100644 index 00000000..a47462c1 --- /dev/null +++ b/internal/broker/broker.go @@ -0,0 +1,5 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker diff --git a/internal/migration/migration.go b/internal/broker/migration/migration.go similarity index 64% rename from internal/migration/migration.go rename to internal/broker/migration/migration.go index 44c16fb4..7437e996 100644 --- a/internal/migration/migration.go +++ b/internal/broker/migration/migration.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !migration // +build !migration diff --git a/internal/migration/migration_embed.go b/internal/broker/migration/migration_embed.go similarity index 94% rename from internal/migration/migration_embed.go rename to internal/broker/migration/migration_embed.go index 84952538..976b4f26 100644 --- a/internal/migration/migration_embed.go +++ b/internal/broker/migration/migration_embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build migration // +build migration diff --git a/internal/conf/conf.go b/internal/conf/conf.go index 97512264..bbc8438c 100644 --- a/internal/conf/conf.go +++ b/internal/conf/conf.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/conf/db.go b/internal/conf/db.go index ef4f7c92..7f859152 100644 --- a/internal/conf/db.go +++ b/internal/conf/db.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/conf/db_cgo.go b/internal/conf/db_cgo.go index 3ec8a218..218512a5 100644 --- a/internal/conf/db_cgo.go +++ b/internal/conf/db_cgo.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build cgo // +build cgo diff --git a/internal/conf/db_nocgo.go b/internal/conf/db_nocgo.go index 37937484..977a6695 100644 --- a/internal/conf/db_nocgo.go +++ b/internal/conf/db_nocgo.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !cgo // +build !cgo diff --git a/internal/conf/logger.go b/internal/conf/logger.go index c65612dc..b514b375 100644 --- a/internal/conf/logger.go +++ b/internal/conf/logger.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/conf/logger_meili.go b/internal/conf/logger_meili.go index 756cc41f..2d3d439d 100644 --- a/internal/conf/logger_meili.go +++ b/internal/conf/logger_meili.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/conf/logger_zinc.go b/internal/conf/logger_zinc.go index 211270c0..4f804cf8 100644 --- a/internal/conf/logger_zinc.go +++ b/internal/conf/logger_zinc.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/conf/settting.go b/internal/conf/settting.go index 116fdf95..da3d97b6 100644 --- a/internal/conf/settting.go +++ b/internal/conf/settting.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/core/authority.go b/internal/core/authority.go index c016c840..05e3742a 100644 --- a/internal/core/authority.go +++ b/internal/core/authority.go @@ -1,7 +1,10 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/types" ) @@ -33,23 +36,17 @@ const ( ActCreateActivationCode ) -type act uint8 - -type FriendFilter map[int64]types.Empty -type FriendSet map[string]types.Empty +type ( + act uint8 -type Action struct { - Act act - UserId int64 -} + FriendFilter map[int64]types.Empty + FriendSet map[string]types.Empty -// AuthorizationManageService 授权管理服务 -type AuthorizationManageService interface { - IsAllow(user *model.User, action *Action) bool - BeFriendFilter(userId int64) FriendFilter - BeFriendIds(userId int64) ([]int64, error) - MyFriendSet(userId int64) FriendSet -} + Action struct { + Act act + UserId int64 + } +) func (f FriendFilter) IsFriend(userId int64) bool { _, yeah := f[userId] @@ -57,7 +54,7 @@ func (f FriendFilter) IsFriend(userId int64) bool { } // IsAllow default true if user is admin -func (a act) IsAllow(user *model.User, userId int64, isFriend bool, isActivation bool) bool { +func (a act) IsAllow(user *User, userId int64, isFriend bool, isActivation bool) bool { if user.IsAdmin { return true } @@ -116,3 +113,11 @@ func (a act) IsAllow(user *model.User, userId int64, isFriend bool, isActivation return false } + +// AuthorizationManageService 授权管理服务 +type AuthorizationManageService interface { + IsAllow(user *User, action *Action) bool + BeFriendFilter(userId int64) FriendFilter + BeFriendIds(userId int64) ([]int64, error) + MyFriendSet(userId int64) FriendSet +} diff --git a/internal/core/cache.go b/internal/core/cache.go index e4cf4cd9..d8b8cd10 100644 --- a/internal/core/cache.go +++ b/internal/core/cache.go @@ -1,6 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core -import "github.com/rocboss/paopao-ce/internal/model" +import ( + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) const ( IdxActNop IdxAct = iota + 1 @@ -15,7 +21,7 @@ type IdxAct uint8 type IndexAction struct { Act IdxAct - Post *model.Post + Post *dbr.Post } func (a IdxAct) String() string { @@ -37,7 +43,7 @@ func (a IdxAct) String() string { } } -func NewIndexAction(act IdxAct, post *model.Post) *IndexAction { +func NewIndexAction(act IdxAct, post *dbr.Post) *IndexAction { return &IndexAction{ Act: act, Post: post, @@ -48,5 +54,5 @@ func NewIndexAction(act IdxAct, post *model.Post) *IndexAction { type CacheIndexService interface { IndexPostsService - SendAction(act IdxAct, post *model.Post) + SendAction(act IdxAct, post *dbr.Post) } diff --git a/internal/core/comments.go b/internal/core/comments.go index 9be29ed3..c5501b4b 100644 --- a/internal/core/comments.go +++ b/internal/core/comments.go @@ -1,24 +1,36 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +type ( + Comment = dbr.Comment + CommentFormated = dbr.CommentFormated + CommentReply = dbr.CommentReply + CommentContent = dbr.CommentContent + CommentReplyFormated = dbr.CommentReplyFormated ) // CommentService 评论检索服务 type CommentService interface { - GetComments(conditions *model.ConditionsT, offset, limit int) ([]*model.Comment, error) - GetCommentByID(id int64) (*model.Comment, error) - GetCommentCount(conditions *model.ConditionsT) (int64, error) - GetCommentReplyByID(id int64) (*model.CommentReply, error) - GetCommentContentsByIDs(ids []int64) ([]*model.CommentContent, error) - GetCommentRepliesByID(ids []int64) ([]*model.CommentReplyFormated, error) + GetComments(conditions *ConditionsT, offset, limit int) ([]*Comment, error) + GetCommentByID(id int64) (*Comment, error) + GetCommentCount(conditions *ConditionsT) (int64, error) + GetCommentReplyByID(id int64) (*CommentReply, error) + GetCommentContentsByIDs(ids []int64) ([]*CommentContent, error) + GetCommentRepliesByID(ids []int64) ([]*CommentReplyFormated, error) } // CommentManageService 评论管理服务 type CommentManageService interface { - DeleteComment(comment *model.Comment) error - CreateComment(comment *model.Comment) (*model.Comment, error) - CreateCommentReply(reply *model.CommentReply) (*model.CommentReply, error) - DeleteCommentReply(reply *model.CommentReply) error - CreateCommentContent(content *model.CommentContent) (*model.CommentContent, error) + DeleteComment(comment *Comment) error + CreateComment(comment *Comment) (*Comment, error) + CreateCommentReply(reply *CommentReply) (*CommentReply, error) + DeleteCommentReply(reply *CommentReply) error + CreateCommentContent(content *CommentContent) (*CommentContent, error) } diff --git a/internal/core/core.go b/internal/core/core.go index f0c158b1..9a8eb26f 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core // DataService 数据服务集成 diff --git a/internal/core/messages.go b/internal/core/messages.go index aa08a1f8..57816480 100644 --- a/internal/core/messages.go +++ b/internal/core/messages.go @@ -1,15 +1,36 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +const ( + MsgTypePost = dbr.MsgTypePost + MsgtypeComment = dbr.MsgtypeComment + MsgTypeReply = dbr.MsgTypeReply + MsgTypeWhisper = dbr.MsgTypeWhisper + MsgTypeRequestingFriend = dbr.MsgTypeRequestingFriend + MsgTypeSystem = dbr.MsgTypeSystem + + MsgStatusUnread = dbr.MsgStatusUnread + MsgStatusReaded = dbr.MsgStatusReaded +) + +type ( + Message = dbr.Message + MessageFormated = dbr.MessageFormated ) // MessageService 消息服务 type MessageService interface { - CreateMessage(msg *model.Message) (*model.Message, error) + CreateMessage(msg *Message) (*Message, error) GetUnreadCount(userID int64) (int64, error) - GetMessageByID(id int64) (*model.Message, error) - ReadMessage(message *model.Message) error - GetMessages(conditions *model.ConditionsT, offset, limit int) ([]*model.MessageFormated, error) - GetMessageCount(conditions *model.ConditionsT) (int64, error) + GetMessageByID(id int64) (*Message, error) + ReadMessage(message *Message) error + GetMessages(conditions *ConditionsT, offset, limit int) ([]*MessageFormated, error) + GetMessageCount(conditions *ConditionsT) (int64, error) } diff --git a/internal/core/search.go b/internal/core/search.go index 3ac90288..74d6e029 100644 --- a/internal/core/search.go +++ b/internal/core/search.go @@ -1,7 +1,11 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" ) const ( @@ -9,28 +13,39 @@ const ( SearchTypeTag SearchType = "tag" ) -type SearchType string +const ( + PostVisitPublic = dbr.PostVisitPublic + PostVisitPrivate = dbr.PostVisitPrivate + PostVisitFriend = dbr.PostVisitFriend + PostVisitInvalid = dbr.PostVisitInvalid +) -type QueryReq struct { - Query string - Visibility []model.PostVisibleT - Type SearchType -} +type ( + PostVisibleT = dbr.PostVisibleT -type QueryResp struct { - Items []*model.PostFormated - Total int64 -} + SearchType string -type TsDocItem struct { - Post *model.Post - Content string -} + QueryReq struct { + Query string + Visibility []PostVisibleT + Type SearchType + } + + QueryResp struct { + Items []*PostFormated + Total int64 + } + + TsDocItem struct { + Post *Post + Content string + } +) // TweetSearchService tweet search service interface type TweetSearchService interface { IndexName() string AddDocuments(data []TsDocItem, primaryKey ...string) (bool, error) DeleteDocuments(identifiers []string) error - Search(user *model.User, q *QueryReq, offset, limit int) (*QueryResp, error) + Search(user *User, q *QueryReq, offset, limit int) (*QueryResp, error) } diff --git a/internal/core/security.go b/internal/core/security.go index 63a7ac21..81a428af 100644 --- a/internal/core/security.go +++ b/internal/core/security.go @@ -1,13 +1,21 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +type ( + Captcha = dbr.Captcha ) // SecurityService 安全相关服务 type SecurityService interface { - GetLatestPhoneCaptcha(phone string) (*model.Captcha, error) - UsePhoneCaptcha(captcha *model.Captcha) error + GetLatestPhoneCaptcha(phone string) (*Captcha, error) + UsePhoneCaptcha(captcha *Captcha) error SendPhoneCaptcha(phone string) error } diff --git a/internal/core/storage.go b/internal/core/storage.go index 2a241bca..310edf29 100644 --- a/internal/core/storage.go +++ b/internal/core/storage.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( diff --git a/internal/core/topics.go b/internal/core/topics.go index a894f9b2..138cc151 100644 --- a/internal/core/topics.go +++ b/internal/core/topics.go @@ -1,13 +1,22 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +type ( + Tag = dbr.Tag + TagFormated = dbr.TagFormated ) // TopicService 话题服务 type TopicService interface { - CreateTag(tag *model.Tag) (*model.Tag, error) - DeleteTag(tag *model.Tag) error - GetTags(conditions *model.ConditionsT, offset, limit int) ([]*model.Tag, error) - GetTagsByKeyword(keyword string) ([]*model.Tag, error) + CreateTag(tag *Tag) (*Tag, error) + DeleteTag(tag *Tag) error + GetTags(conditions *ConditionsT, offset, limit int) ([]*Tag, error) + GetTagsByKeyword(keyword string) ([]*Tag, error) } diff --git a/internal/core/tweets.go b/internal/core/tweets.go index 1b454c6d..682cbd65 100644 --- a/internal/core/tweets.go +++ b/internal/core/tweets.go @@ -1,49 +1,83 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +const ( + AttachmentTypeImage = dbr.AttachmentTypeImage + AttachmentTypeVideo = dbr.AttachmentTypeVideo + AttachmentTypeOther = dbr.AttachmentTypeOther + + // 类型,1标题,2文字段落,3图片地址,4视频地址,5语音地址,6链接地址,7附件资源 + ContentTypeTitle = dbr.ContentTypeTitle + ContentTypeText = dbr.ContentTypeText + ContentTypeImage = dbr.ContentTypeImage + ContentTypeVideo = dbr.ContentTypeVideo + ContentTypeAudio = dbr.ContentTypeAudio + ContentTypeLink = dbr.ContentTypeLink + ContentTypeAttachment = dbr.ContentTypeAttachment + ContentTypeChargeAttachment = dbr.ContentTypeChargeAttachment +) + +type ( + PostStar = dbr.PostStar + PostCollection = dbr.PostCollection + PostAttachmentBill = dbr.PostAttachmentBill + PostContent = dbr.PostContent + Attachment = dbr.Attachment + AttachmentType = dbr.AttachmentType + PostContentT = dbr.PostContentT + + IndexTweetList struct { + Tweets []*PostFormated + Total int64 + } ) // TweetService 推文检索服务 type TweetService interface { - GetPostByID(id int64) (*model.Post, error) - GetPosts(conditions *model.ConditionsT, offset, limit int) ([]*model.Post, error) - GetPostCount(conditions *model.ConditionsT) (int64, error) - GetUserPostStar(postID, userID int64) (*model.PostStar, error) - GetUserPostStars(userID int64, offset, limit int) ([]*model.PostStar, error) + GetPostByID(id int64) (*Post, error) + GetPosts(conditions *ConditionsT, offset, limit int) ([]*Post, error) + GetPostCount(conditions *ConditionsT) (int64, error) + GetUserPostStar(postID, userID int64) (*PostStar, error) + GetUserPostStars(userID int64, offset, limit int) ([]*PostStar, error) GetUserPostStarCount(userID int64) (int64, error) - GetUserPostCollection(postID, userID int64) (*model.PostCollection, error) - GetUserPostCollections(userID int64, offset, limit int) ([]*model.PostCollection, error) + GetUserPostCollection(postID, userID int64) (*PostCollection, error) + GetUserPostCollections(userID int64, offset, limit int) ([]*PostCollection, error) GetUserPostCollectionCount(userID int64) (int64, error) - GetPostAttatchmentBill(postID, userID int64) (*model.PostAttachmentBill, error) - GetPostContentsByIDs(ids []int64) ([]*model.PostContent, error) - GetPostContentByID(id int64) (*model.PostContent, error) + GetPostAttatchmentBill(postID, userID int64) (*PostAttachmentBill, error) + GetPostContentsByIDs(ids []int64) ([]*PostContent, error) + GetPostContentByID(id int64) (*PostContent, error) } // TweetManageService 推文管理服务,包括创建/删除/更新推文 type TweetManageService interface { - CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) - CreatePost(post *model.Post) (*model.Post, error) - DeletePost(post *model.Post) ([]string, error) - LockPost(post *model.Post) error - StickPost(post *model.Post) error - VisiblePost(post *model.Post, visibility model.PostVisibleT) error - UpdatePost(post *model.Post) error - CreatePostStar(postID, userID int64) (*model.PostStar, error) - DeletePostStar(p *model.PostStar) error - CreatePostCollection(postID, userID int64) (*model.PostCollection, error) - DeletePostCollection(p *model.PostCollection) error - CreatePostContent(content *model.PostContent) (*model.PostContent, error) + CreateAttachment(attachment *Attachment) (*Attachment, error) + CreatePost(post *Post) (*Post, error) + DeletePost(post *Post) ([]string, error) + LockPost(post *Post) error + StickPost(post *Post) error + VisiblePost(post *Post, visibility PostVisibleT) error + UpdatePost(post *Post) error + CreatePostStar(postID, userID int64) (*PostStar, error) + DeletePostStar(p *PostStar) error + CreatePostCollection(postID, userID int64) (*PostCollection, error) + DeletePostCollection(p *PostCollection) error + CreatePostContent(content *PostContent) (*PostContent, error) } // TweetHelpService 推文辅助服务 type TweetHelpService interface { - RevampPosts(posts []*model.PostFormated) ([]*model.PostFormated, error) - MergePosts(posts []*model.Post) ([]*model.PostFormated, error) + RevampPosts(posts []*PostFormated) ([]*PostFormated, error) + MergePosts(posts []*Post) ([]*PostFormated, error) } // IndexPostsService 广场首页推文列表服务 type IndexPostsService interface { - IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) + IndexPosts(user *User, offset int, limit int) (*IndexTweetList, error) } diff --git a/internal/core/types.go b/internal/core/types.go new file mode 100644 index 00000000..6ca95893 --- /dev/null +++ b/internal/core/types.go @@ -0,0 +1,24 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package core + +import ( + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +const ( + UserStatusNormal = dbr.UserStatusNormal + UserStatusClosed = dbr.UserStatusClosed +) + +type ( + User = dbr.User + Post = dbr.Post + ConditionsT = dbr.ConditionsT + PostFormated = dbr.PostFormated + UserFormated = dbr.UserFormated + PostContentFormated = dbr.PostContentFormated + Model = dbr.Model +) diff --git a/internal/core/user.go b/internal/core/user.go index cf0ebaa8..ed132dd3 100644 --- a/internal/core/user.go +++ b/internal/core/user.go @@ -1,19 +1,33 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core -import ( - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" +type ( + ContactItem struct { + UserId int64 `json:"user_id"` + UserName string `json:"username"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` + Phone string `json:"phone"` + } + + ContactList struct { + Contacts []ContactItem `json:"contacts"` + Total int64 `json:"total"` + } ) // UserManageService 用户管理服务 type UserManageService interface { - GetUserByID(id int64) (*model.User, error) - GetUserByUsername(username string) (*model.User, error) - GetUserByPhone(phone string) (*model.User, error) - GetUsersByIDs(ids []int64) ([]*model.User, error) - GetUsersByKeyword(keyword string) ([]*model.User, error) - CreateUser(user *model.User) (*model.User, error) - UpdateUser(user *model.User) error + GetUserByID(id int64) (*User, error) + GetUserByUsername(username string) (*User, error) + GetUserByPhone(phone string) (*User, error) + GetUsersByIDs(ids []int64) ([]*User, error) + GetUsersByKeyword(keyword string) ([]*User, error) + CreateUser(user *User) (*User, error) + UpdateUser(user *User) error } // ContactManageService 联系人管理服务 @@ -22,6 +36,6 @@ type ContactManageService interface { AddFriend(userId int64, friendId int64) error RejectFriend(userId int64, friendId int64) error DeleteFriend(userId int64, friendId int64) error - GetContacts(userId int64, offset int, limit int) (*rest.ContactsResp, error) + GetContacts(userId int64, offset int, limit int) (*ContactList, error) IsFriend(userID int64, friendID int64) bool } diff --git a/internal/core/version.go b/internal/core/version.go index e603c0a5..07376c39 100644 --- a/internal/core/version.go +++ b/internal/core/version.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( diff --git a/internal/core/wallet.go b/internal/core/wallet.go index 5b3a3391..c4792d3b 100644 --- a/internal/core/wallet.go +++ b/internal/core/wallet.go @@ -1,15 +1,24 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +type ( + WalletStatement = dbr.WalletStatement + WalletRecharge = dbr.WalletRecharge ) // WalletService wallet service interface type WalletService interface { - GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, error) + GetUserWalletBills(userID int64, offset, limit int) ([]*WalletStatement, error) GetUserWalletBillCount(userID int64) (int64, error) - GetRechargeByID(id int64) (*model.WalletRecharge, error) - CreateRecharge(userId, amount int64) (*model.WalletRecharge, error) - HandleRechargeSuccess(recharge *model.WalletRecharge, tradeNo string) error - HandlePostAttachmentBought(post *model.Post, user *model.User) error + GetRechargeByID(id int64) (*WalletRecharge, error) + CreateRecharge(userId, amount int64) (*WalletRecharge, error) + HandleRechargeSuccess(recharge *WalletRecharge, tradeNo string) error + HandlePostAttachmentBought(post *Post, user *User) error } diff --git a/internal/dao/cache/bigcache.go b/internal/dao/cache/bigcache.go index 4fce26de..8ec83c38 100644 --- a/internal/dao/cache/bigcache.go +++ b/internal/dao/cache/bigcache.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cache import ( @@ -11,8 +15,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/allegro/bigcache/v3" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" "github.com/rocboss/paopao-ce/pkg/types" "github.com/sirupsen/logrus" ) @@ -24,7 +26,7 @@ var ( type postsEntry struct { key string - tweets *rest.IndexTweetsResp + tweets *core.IndexTweetList } type bigCacheIndexServant struct { @@ -38,7 +40,7 @@ type bigCacheIndexServant struct { preventDuration time.Duration } -func (s *bigCacheIndexServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { +func (s *bigCacheIndexServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { key := s.keyFrom(user, offset, limit) posts, err := s.getPosts(key) if err == nil { @@ -54,7 +56,7 @@ func (s *bigCacheIndexServant) IndexPosts(user *model.User, offset int, limit in return posts, nil } -func (s *bigCacheIndexServant) getPosts(key string) (*rest.IndexTweetsResp, error) { +func (s *bigCacheIndexServant) getPosts(key string) (*core.IndexTweetList, error) { data, err := s.cache.Get(key) if err != nil { logrus.Debugf("bigCacheIndexServant.getPosts get posts by key: %s from cache err: %v", key, err) @@ -62,7 +64,7 @@ func (s *bigCacheIndexServant) getPosts(key string) (*rest.IndexTweetsResp, erro } buf := bytes.NewBuffer(data) dec := gob.NewDecoder(buf) - var resp rest.IndexTweetsResp + var resp core.IndexTweetList if err := dec.Decode(&resp); err != nil { logrus.Debugf("bigCacheIndexServant.getPosts get posts from cache in decode err: %v", err) return nil, err @@ -70,7 +72,7 @@ func (s *bigCacheIndexServant) getPosts(key string) (*rest.IndexTweetsResp, erro return &resp, nil } -func (s *bigCacheIndexServant) cachePosts(key string, tweets *rest.IndexTweetsResp) { +func (s *bigCacheIndexServant) cachePosts(key string, tweets *core.IndexTweetList) { entry := &postsEntry{key: key, tweets: tweets} select { case s.cachePostsCh <- entry: @@ -96,7 +98,7 @@ func (s *bigCacheIndexServant) setPosts(entry *postsEntry) { logrus.Debugf("bigCacheIndexServant.setPosts setPosts set cache by key: %s", entry.key) } -func (s *bigCacheIndexServant) keyFrom(user *model.User, offset int, limit int) string { +func (s *bigCacheIndexServant) keyFrom(user *core.User, offset int, limit int) string { var userId int64 = -1 if user != nil { userId = user.ID @@ -104,7 +106,7 @@ func (s *bigCacheIndexServant) keyFrom(user *model.User, offset int, limit int) return fmt.Sprintf("index:%d:%d:%d", userId, offset, limit) } -func (s *bigCacheIndexServant) SendAction(act core.IdxAct, post *model.Post) { +func (s *bigCacheIndexServant) SendAction(act core.IdxAct, post *core.Post) { action := core.NewIndexAction(act, post) select { case s.indexActionCh <- action: @@ -134,7 +136,7 @@ func (s *bigCacheIndexServant) handleIndexAction(action *core.IndexAction) { // 创建/删除 私密推文特殊处理 switch act { case core.IdxActCreatePost, core.IdxActDeletePost: - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { s.deleteCacheByUserId(post.UserID, true) return } diff --git a/internal/dao/cache/cache.go b/internal/dao/cache/cache.go index 1b12ad88..773c9a2f 100644 --- a/internal/dao/cache/cache.go +++ b/internal/dao/cache/cache.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cache import ( diff --git a/internal/dao/cache/none.go b/internal/dao/cache/none.go index 79705280..ce6e1caf 100644 --- a/internal/dao/cache/none.go +++ b/internal/dao/cache/none.go @@ -1,10 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cache import ( "github.com/Masterminds/semver/v3" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" ) var ( @@ -16,11 +18,11 @@ type noneCacheIndexServant struct { ips core.IndexPostsService } -func (s *noneCacheIndexServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { +func (s *noneCacheIndexServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { return s.ips.IndexPosts(user, offset, limit) } -func (s *noneCacheIndexServant) SendAction(_act core.IdxAct, _post *model.Post) { +func (s *noneCacheIndexServant) SendAction(_act core.IdxAct, _post *core.Post) { // empty } diff --git a/internal/dao/cache/simple.go b/internal/dao/cache/simple.go index afdea1be..ba674d1b 100644 --- a/internal/dao/cache/simple.go +++ b/internal/dao/cache/simple.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cache import ( @@ -6,8 +10,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" "github.com/sirupsen/logrus" ) @@ -20,21 +22,21 @@ type simpleCacheIndexServant struct { ips core.IndexPostsService indexActionCh chan core.IdxAct - indexPosts *rest.IndexTweetsResp + indexPosts *core.IndexTweetList atomicIndex atomic.Value maxIndexSize int checkTick *time.Ticker expireIndexTick *time.Ticker } -func (s *simpleCacheIndexServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { - cacheResp := s.atomicIndex.Load().(*rest.IndexTweetsResp) +func (s *simpleCacheIndexServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { + cacheResp := s.atomicIndex.Load().(*core.IndexTweetList) end := offset + limit if cacheResp != nil { size := len(cacheResp.Tweets) logrus.Debugf("simpleCacheIndexServant.IndexPosts get index posts from cache posts: %d offset:%d limit:%d start:%d, end:%d", size, offset, limit, offset, end) if size >= end { - return &rest.IndexTweetsResp{ + return &core.IndexTweetList{ Tweets: cacheResp.Tweets[offset:end], Total: cacheResp.Total, }, nil @@ -45,7 +47,7 @@ func (s *simpleCacheIndexServant) IndexPosts(user *model.User, offset int, limit return s.ips.IndexPosts(user, offset, limit) } -func (s *simpleCacheIndexServant) SendAction(act core.IdxAct, _post *model.Post) { +func (s *simpleCacheIndexServant) SendAction(act core.IdxAct, _post *core.Post) { select { case s.indexActionCh <- act: logrus.Debugf("simpleCacheIndexServant.SendAction send indexAction by chan: %s", act) diff --git a/internal/dao/dao.go b/internal/dao/dao.go index 6f4a776a..e4b2ea6a 100644 --- a/internal/dao/dao.go +++ b/internal/dao/dao.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package dao import ( diff --git a/internal/dao/jinzhu/authority.go b/internal/dao/jinzhu/authority.go index c0f59556..5932fa24 100644 --- a/internal/dao/jinzhu/authority.go +++ b/internal/dao/jinzhu/authority.go @@ -1,8 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "github.com/rocboss/paopao-ce/pkg/types" "gorm.io/gorm" ) @@ -21,7 +25,7 @@ func newAuthorizationManageService(db *gorm.DB) core.AuthorizationManageService } } -func (s *authorizationManageServant) IsAllow(user *model.User, action *core.Action) bool { +func (s *authorizationManageServant) IsAllow(user *core.User, action *core.Action) bool { // user is activation if had bind phone isActivation := (len(user.Phone) != 0) isFriend := s.isFriend(user.ID, action.UserId) @@ -30,7 +34,7 @@ func (s *authorizationManageServant) IsAllow(user *model.User, action *core.Acti } func (s *authorizationManageServant) MyFriendSet(userId int64) core.FriendSet { - ids, err := (&model.Contact{UserId: userId}).MyFriendIds(s.db) + ids, err := (&dbr.Contact{UserId: userId}).MyFriendIds(s.db) if err != nil { return core.FriendSet{} } @@ -43,7 +47,7 @@ func (s *authorizationManageServant) MyFriendSet(userId int64) core.FriendSet { } func (s *authorizationManageServant) BeFriendFilter(userId int64) core.FriendFilter { - ids, err := (&model.Contact{FriendId: userId}).BeFriendIds(s.db) + ids, err := (&dbr.Contact{FriendId: userId}).BeFriendIds(s.db) if err != nil { return core.FriendFilter{} } @@ -56,12 +60,12 @@ func (s *authorizationManageServant) BeFriendFilter(userId int64) core.FriendFil } func (s *authorizationManageServant) BeFriendIds(userId int64) ([]int64, error) { - return (&model.Contact{FriendId: userId}).BeFriendIds(s.db) + return (&dbr.Contact{FriendId: userId}).BeFriendIds(s.db) } func (s *authorizationManageServant) isFriend(userId int64, friendId int64) bool { - contact, err := (&model.Contact{UserId: friendId, FriendId: userId}).GetByUserFriend(s.db) - if err == nil || contact.Status == model.ContactStatusAgree { + contact, err := (&dbr.Contact{UserId: friendId, FriendId: userId}).GetByUserFriend(s.db) + if err == nil || contact.Status == dbr.ContactStatusAgree { return true } return false diff --git a/internal/dao/jinzhu/comments.go b/internal/dao/jinzhu/comments.go index c15e74f3..1af9e5ce 100644 --- a/internal/dao/jinzhu/comments.go +++ b/internal/dao/jinzhu/comments.go @@ -1,8 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -31,42 +35,42 @@ func newCommentManageService(db *gorm.DB) core.CommentManageService { } } -func (s *commentServant) GetComments(conditions *model.ConditionsT, offset, limit int) ([]*model.Comment, error) { - return (&model.Comment{}).List(s.db, conditions, offset, limit) +func (s *commentServant) GetComments(conditions *core.ConditionsT, offset, limit int) ([]*core.Comment, error) { + return (&dbr.Comment{}).List(s.db, conditions, offset, limit) } -func (s *commentServant) GetCommentByID(id int64) (*model.Comment, error) { - comment := &model.Comment{ - Model: &model.Model{ +func (s *commentServant) GetCommentByID(id int64) (*core.Comment, error) { + comment := &dbr.Comment{ + Model: &dbr.Model{ ID: id, }, } return comment.Get(s.db) } -func (s *commentServant) GetCommentReplyByID(id int64) (*model.CommentReply, error) { - reply := &model.CommentReply{ - Model: &model.Model{ +func (s *commentServant) GetCommentReplyByID(id int64) (*core.CommentReply, error) { + reply := &dbr.CommentReply{ + Model: &dbr.Model{ ID: id, }, } return reply.Get(s.db) } -func (s *commentServant) GetCommentCount(conditions *model.ConditionsT) (int64, error) { - return (&model.Comment{}).Count(s.db, conditions) +func (s *commentServant) GetCommentCount(conditions *core.ConditionsT) (int64, error) { + return (&dbr.Comment{}).Count(s.db, conditions) } -func (s *commentServant) GetCommentContentsByIDs(ids []int64) ([]*model.CommentContent, error) { - commentContent := &model.CommentContent{} - return commentContent.List(s.db, &model.ConditionsT{ +func (s *commentServant) GetCommentContentsByIDs(ids []int64) ([]*core.CommentContent, error) { + commentContent := &dbr.CommentContent{} + return commentContent.List(s.db, &dbr.ConditionsT{ "comment_id IN ?": ids, }, 0, 0) } -func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*model.CommentReplyFormated, error) { - CommentReply := &model.CommentReply{} - replies, err := CommentReply.List(s.db, &model.ConditionsT{ +func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*core.CommentReplyFormated, error) { + CommentReply := &dbr.CommentReply{} + replies, err := CommentReply.List(s.db, &dbr.ConditionsT{ "comment_id IN ?": ids, }, 0, 0) @@ -83,7 +87,7 @@ func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*model.CommentRep if err != nil { return nil, err } - repliesFormated := []*model.CommentReplyFormated{} + repliesFormated := []*core.CommentReplyFormated{} for _, reply := range replies { replyFormated := reply.Format() for _, user := range users { @@ -101,22 +105,22 @@ func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*model.CommentRep return repliesFormated, nil } -func (s *commentManageServant) DeleteComment(comment *model.Comment) error { +func (s *commentManageServant) DeleteComment(comment *core.Comment) error { return comment.Delete(s.db) } -func (s *commentManageServant) CreateComment(comment *model.Comment) (*model.Comment, error) { +func (s *commentManageServant) CreateComment(comment *core.Comment) (*core.Comment, error) { return comment.Create(s.db) } -func (s *commentManageServant) CreateCommentReply(reply *model.CommentReply) (*model.CommentReply, error) { +func (s *commentManageServant) CreateCommentReply(reply *core.CommentReply) (*core.CommentReply, error) { return reply.Create(s.db) } -func (s *commentManageServant) DeleteCommentReply(reply *model.CommentReply) error { +func (s *commentManageServant) DeleteCommentReply(reply *core.CommentReply) error { return reply.Delete(s.db) } -func (s *commentManageServant) CreateCommentContent(content *model.CommentContent) (*model.CommentContent, error) { +func (s *commentManageServant) CreateCommentContent(content *core.CommentContent) (*core.CommentContent, error) { return content.Create(s.db) } diff --git a/internal/dao/jinzhu/contacts.go b/internal/dao/jinzhu/contacts.go index c55a94a0..c26ae4de 100644 --- a/internal/dao/jinzhu/contacts.go +++ b/internal/dao/jinzhu/contacts.go @@ -1,11 +1,14 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "time" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "github.com/sirupsen/logrus" "gorm.io/gorm" ) @@ -24,14 +27,14 @@ func newContactManageService(db *gorm.DB) core.ContactManageService { } } -func (s *contactManageServant) fetchOrNewContact(db *gorm.DB, userId int64, friendId int64, status int8) (*model.Contact, error) { - contact := &model.Contact{ +func (s *contactManageServant) fetchOrNewContact(db *gorm.DB, userId int64, friendId int64, status int8) (*dbr.Contact, error) { + contact := &dbr.Contact{ UserId: userId, FriendId: friendId, } contact, err := contact.FetchUser(db) if err != nil { - contact = &model.Contact{ + contact = &dbr.Contact{ UserId: userId, FriendId: friendId, Status: status, @@ -54,17 +57,17 @@ func (s *contactManageServant) RequestingFriend(userId int64, friendId int64, gr } }() - contact, e := s.fetchOrNewContact(db, userId, friendId, model.ContactStatusRequesting) + contact, e := s.fetchOrNewContact(db, userId, friendId, dbr.ContactStatusRequesting) if e != nil { err = e return } // 如果已经好友,啥也不干 - if contact.Status == model.ContactStatusAgree { + if contact.Status == dbr.ContactStatusAgree { return nil - } else if contact.Status == model.ContactStatusReject || contact.Status == model.ContactStatusDeleted { - contact.Status = model.ContactStatusRequesting + } else if contact.Status == dbr.ContactStatusReject || contact.Status == dbr.ContactStatusDeleted { + contact.Status = dbr.ContactStatusRequesting contact.IsDel = 0 // remove deleted flag if needed if err = contact.UpdateInUnscoped(db); err != nil { logrus.Errorf("contactManageServant.RequestingFriend update exsit contact err:%s", err) @@ -72,13 +75,13 @@ func (s *contactManageServant) RequestingFriend(userId int64, friendId int64, gr } } - msg := &model.Message{ + msg := &dbr.Message{ SenderUserID: userId, ReceiverUserID: friendId, - Type: model.MsgTypeRequestingFriend, + Type: dbr.MsgTypeRequestingFriend, Brief: "请求添加好友,并附言:", Content: greetings, - ReplyID: int64(model.ContactStatusRequesting), + ReplyID: int64(dbr.ContactStatusRequesting), } if _, err = msg.Create(db); err != nil { logrus.Errorf("contactManageServant.RequestingFriend create message err:%s", err) @@ -97,7 +100,7 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro } }() - contact := &model.Contact{ + contact := &dbr.Contact{ UserId: friendId, FriendId: userId, } @@ -105,23 +108,23 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro return } // 如果还不是请求好友,啥也不干 - if contact.Status != model.ContactStatusRequesting { + if contact.Status != dbr.ContactStatusRequesting { logrus.Debugf("contactManageServant.AddFriend not reuesting status now so skip") return nil } - contact.Status = model.ContactStatusAgree + contact.Status = dbr.ContactStatusAgree if err = contact.Update(db); err != nil { return err } - contact, err = s.fetchOrNewContact(db, userId, friendId, model.ContactStatusAgree) + contact, err = s.fetchOrNewContact(db, userId, friendId, dbr.ContactStatusAgree) if err != nil { return } // 如果已经好友,啥也不干 - if contact.Status != model.ContactStatusAgree { - contact.Status = model.ContactStatusAgree + if contact.Status != dbr.ContactStatusAgree { + contact.Status = dbr.ContactStatusAgree contact.IsDel = 0 // remove deleted flag if err = contact.UpdateInUnscoped(db); err != nil { logrus.Errorf("contactManageServant.AddFriend update contact err:%s", err) @@ -129,8 +132,8 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro } } - args := []any{userId, friendId, friendId, userId, model.MsgTypeRequestingFriend, model.ContactStatusRequesting} - msgs, e := (&model.Message{}).FetchBy(db, model.Predicates{ + args := []any{userId, friendId, friendId, userId, dbr.MsgTypeRequestingFriend, dbr.ContactStatusRequesting} + msgs, e := (&dbr.Message{}).FetchBy(db, dbr.Predicates{ "((sender_user_id = ? AND receiver_user_id = ?) OR (sender_user_id = ? AND receiver_user_id = ?)) AND type = ? AND reply_id = ?": args, }) if e != nil { @@ -138,7 +141,7 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro return } for _, msg := range msgs { - msg.ReplyID = int64(model.ContactStatusAgree) + msg.ReplyID = int64(dbr.ContactStatusAgree) if err = msg.Update(db); err != nil { return } @@ -156,7 +159,7 @@ func (s *contactManageServant) RejectFriend(userId int64, friendId int64) (err e } }() - contact := &model.Contact{ + contact := &dbr.Contact{ UserId: friendId, FriendId: userId, } @@ -164,16 +167,16 @@ func (s *contactManageServant) RejectFriend(userId int64, friendId int64) (err e return } // 如果还不是请求好友,啥也不干 - if contact.Status != model.ContactStatusRequesting { + if contact.Status != dbr.ContactStatusRequesting { return nil } - contact.Status = model.ContactStatusReject + contact.Status = dbr.ContactStatusReject if err = contact.Update(db); err != nil { return err } - args := []any{friendId, userId, model.MsgTypeRequestingFriend, model.ContactStatusRequesting} - msgs, e := (&model.Message{}).FetchBy(db, model.Predicates{ + args := []any{friendId, userId, dbr.MsgTypeRequestingFriend, dbr.ContactStatusRequesting} + msgs, e := (&dbr.Message{}).FetchBy(db, dbr.Predicates{ "sender_user_id = ? AND receiver_user_id = ? AND type = ? AND reply_id = ?": args, }) if e != nil { @@ -181,7 +184,7 @@ func (s *contactManageServant) RejectFriend(userId int64, friendId int64) (err e return } for _, msg := range msgs { - msg.ReplyID = int64(model.ContactStatusReject) + msg.ReplyID = int64(dbr.ContactStatusReject) if err = msg.Update(db); err != nil { return } @@ -199,7 +202,7 @@ func (s *contactManageServant) DeleteFriend(userId int64, friendId int64) (err e } }() - contact := &model.Contact{ + contact := &dbr.Contact{ UserId: userId, FriendId: friendId, } @@ -210,10 +213,10 @@ func (s *contactManageServant) DeleteFriend(userId int64, friendId int64) (err e for _, contact := range contacts { // 如果还不是好友,啥也不干 - if contact.Status != model.ContactStatusAgree { + if contact.Status != dbr.ContactStatusAgree { continue } - contact.Status = model.ContactStatusDeleted + contact.Status = dbr.ContactStatusDeleted contact.DeletedOn = time.Now().Unix() contact.IsDel = 1 if err = contact.Update(db); err != nil { @@ -223,11 +226,11 @@ func (s *contactManageServant) DeleteFriend(userId int64, friendId int64) (err e return nil } -func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) (*rest.ContactsResp, error) { - contact := &model.Contact{} - condition := model.ConditionsT{ +func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) (*core.ContactList, error) { + contact := &dbr.Contact{} + condition := dbr.ConditionsT{ "user_id": userId, - "status": model.ContactStatusAgree, + "status": dbr.ContactStatusAgree, } contacts, err := contact.List(s.db, condition, offset, limit) if err != nil { @@ -237,13 +240,13 @@ func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) if err != nil { return nil, err } - resp := &rest.ContactsResp{ - Contacts: make([]rest.ContactItem, 0, len(contacts)), + resp := &core.ContactList{ + Contacts: make([]core.ContactItem, 0, len(contacts)), Total: total, } for _, c := range contacts { if c.User != nil { - resp.Contacts = append(resp.Contacts, rest.ContactItem{ + resp.Contacts = append(resp.Contacts, core.ContactItem{ UserId: c.FriendId, UserName: c.User.Username, Nickname: c.User.Nickname, @@ -256,12 +259,12 @@ func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) } func (s *contactManageServant) IsFriend(userId int64, friendId int64) bool { - contact := &model.Contact{ + contact := &dbr.Contact{ UserId: friendId, FriendId: userId, } contact, err := contact.GetByUserFriend(s.db) - if err == nil && contact.Status == model.ContactStatusAgree { + if err == nil && contact.Status == dbr.ContactStatusAgree { return true } return false diff --git a/internal/dao/jinzhu/dbr/attachment.go b/internal/dao/jinzhu/dbr/attachment.go index 0c748b00..b62a5d8b 100644 --- a/internal/dao/jinzhu/dbr/attachment.go +++ b/internal/dao/jinzhu/dbr/attachment.go @@ -1,13 +1,17 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" type AttachmentType int const ( - ATTACHMENT_TYPE_IMAGE AttachmentType = iota + 1 - ATTACHMENT_TYPE_VIDEO - ATTACHMENT_TYPE_OTHER + AttachmentTypeImage AttachmentType = iota + 1 + AttachmentTypeVideo + AttachmentTypeOther ) type Attachment struct { diff --git a/internal/dao/jinzhu/dbr/captcha.go b/internal/dao/jinzhu/dbr/captcha.go index 210cc691..4567d4b3 100644 --- a/internal/dao/jinzhu/dbr/captcha.go +++ b/internal/dao/jinzhu/dbr/captcha.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/dao/jinzhu/dbr/comment.go b/internal/dao/jinzhu/dbr/comment.go index 72494b53..80192df7 100644 --- a/internal/dao/jinzhu/dbr/comment.go +++ b/internal/dao/jinzhu/dbr/comment.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/dao/jinzhu/dbr/comment_content.go b/internal/dao/jinzhu/dbr/comment_content.go index b7d42dfd..778f113a 100644 --- a/internal/dao/jinzhu/dbr/comment_content.go +++ b/internal/dao/jinzhu/dbr/comment_content.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" @@ -47,7 +51,7 @@ func (c *CommentContent) Create(db *gorm.DB) (*CommentContent, error) { } func (c *CommentContent) MediaContentsByCommentId(db *gorm.DB, commentIds []int64) (contents []string, err error) { - err = db.Model(c).Where("comment_id IN ? AND type = ?", commentIds, CONTENT_TYPE_IMAGE).Select("content").Find(&contents).Error + err = db.Model(c).Where("comment_id IN ? AND type = ?", commentIds, ContentTypeImage).Select("content").Find(&contents).Error return } diff --git a/internal/dao/jinzhu/dbr/comment_reply.go b/internal/dao/jinzhu/dbr/comment_reply.go index fd22702f..fe527be5 100644 --- a/internal/dao/jinzhu/dbr/comment_reply.go +++ b/internal/dao/jinzhu/dbr/comment_reply.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/dao/jinzhu/dbr/contact.go b/internal/dao/jinzhu/dbr/contact.go index 14049f77..e8c12bd0 100644 --- a/internal/dao/jinzhu/dbr/contact.go +++ b/internal/dao/jinzhu/dbr/contact.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "github.com/sirupsen/logrus" diff --git a/internal/dao/jinzhu/dbr/dbr.go b/internal/dao/jinzhu/dbr/dbr.go deleted file mode 100644 index 99bc8296..00000000 --- a/internal/dao/jinzhu/dbr/dbr.go +++ /dev/null @@ -1,36 +0,0 @@ -package model - -import ( - "time" - - "gorm.io/gorm" - "gorm.io/plugin/soft_delete" -) - -// Model 公共Model -type Model struct { - ID int64 `gorm:"primary_key" json:"id"` - CreatedOn int64 `json:"created_on"` - ModifiedOn int64 `json:"modified_on"` - DeletedOn int64 `json:"deleted_on"` - IsDel soft_delete.DeletedAt `gorm:"softDelete:flag" json:"is_del"` -} - -type ConditionsT map[string]any -type Predicates map[string][]any - -func (m *Model) BeforeCreate(tx *gorm.DB) (err error) { - nowTime := time.Now().Unix() - - tx.Statement.SetColumn("created_on", nowTime) - tx.Statement.SetColumn("modified_on", nowTime) - return -} - -func (m *Model) BeforeUpdate(tx *gorm.DB) (err error) { - if !tx.Statement.Changed("modified_on") { - tx.Statement.SetColumn("modified_on", time.Now().Unix()) - } - - return -} diff --git a/internal/dao/jinzhu/dbr/message.go b/internal/dao/jinzhu/dbr/message.go index c1277cf7..6c952bae 100644 --- a/internal/dao/jinzhu/dbr/message.go +++ b/internal/dao/jinzhu/dbr/message.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/model/model.go b/internal/dao/jinzhu/dbr/model.go similarity index 83% rename from internal/model/model.go rename to internal/dao/jinzhu/dbr/model.go index 99bc8296..75e66561 100644 --- a/internal/model/model.go +++ b/internal/dao/jinzhu/dbr/model.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/dao/jinzhu/dbr/post.go b/internal/dao/jinzhu/dbr/post.go index ae428a9a..a47dedfc 100644 --- a/internal/dao/jinzhu/dbr/post.go +++ b/internal/dao/jinzhu/dbr/post.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "strings" diff --git a/internal/dao/jinzhu/dbr/post_attachment_bill.go b/internal/dao/jinzhu/dbr/post_attachment_bill.go index 8ee7aae6..7bdd812f 100644 --- a/internal/dao/jinzhu/dbr/post_attachment_bill.go +++ b/internal/dao/jinzhu/dbr/post_attachment_bill.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/dao/jinzhu/dbr/post_collection.go b/internal/dao/jinzhu/dbr/post_collection.go index 0ea0cb29..04ca2647 100644 --- a/internal/dao/jinzhu/dbr/post_collection.go +++ b/internal/dao/jinzhu/dbr/post_collection.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/dao/jinzhu/dbr/post_content.go b/internal/dao/jinzhu/dbr/post_content.go index b301de62..672cc57e 100644 --- a/internal/dao/jinzhu/dbr/post_content.go +++ b/internal/dao/jinzhu/dbr/post_content.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" @@ -7,27 +11,26 @@ import ( ) // 类型,1标题,2文字段落,3图片地址,4视频地址,5语音地址,6链接地址,7附件资源 - type PostContentT int const ( - CONTENT_TYPE_TITLE PostContentT = iota + 1 - CONTENT_TYPE_TEXT - CONTENT_TYPE_IMAGE - CONTENT_TYPE_VIDEO - CONTENT_TYPE_AUDIO - CONTENT_TYPE_LINK - CONTENT_TYPE_ATTACHMENT - CONTENT_TYPE_CHARGE_ATTACHMENT + ContentTypeTitle PostContentT = iota + 1 + ContentTypeText + ContentTypeImage + ContentTypeVideo + ContentTypeAudio + ContentTypeLink + ContentTypeAttachment + ContentTypeChargeAttachment ) var ( mediaContentType = []PostContentT{ - CONTENT_TYPE_IMAGE, - CONTENT_TYPE_VIDEO, - CONTENT_TYPE_AUDIO, - CONTENT_TYPE_ATTACHMENT, - CONTENT_TYPE_CHARGE_ATTACHMENT, + ContentTypeImage, + ContentTypeVideo, + ContentTypeAudio, + ContentTypeAttachment, + ContentTypeChargeAttachment, } ) diff --git a/internal/dao/jinzhu/dbr/post_star.go b/internal/dao/jinzhu/dbr/post_star.go index 3846a9c2..45c48f45 100644 --- a/internal/dao/jinzhu/dbr/post_star.go +++ b/internal/dao/jinzhu/dbr/post_star.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/dao/jinzhu/dbr/tag.go b/internal/dao/jinzhu/dbr/tag.go index 34bb64f9..5193df26 100644 --- a/internal/dao/jinzhu/dbr/tag.go +++ b/internal/dao/jinzhu/dbr/tag.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/dao/jinzhu/dbr/user.go b/internal/dao/jinzhu/dbr/user.go index 39c52d79..a10d5432 100644 --- a/internal/dao/jinzhu/dbr/user.go +++ b/internal/dao/jinzhu/dbr/user.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/dao/jinzhu/dbr/wallet_recharge.go b/internal/dao/jinzhu/dbr/wallet_recharge.go index bfb3bc6f..14601cb0 100644 --- a/internal/dao/jinzhu/dbr/wallet_recharge.go +++ b/internal/dao/jinzhu/dbr/wallet_recharge.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/dao/jinzhu/dbr/wallet_statement.go b/internal/dao/jinzhu/dbr/wallet_statement.go index 163e2430..890e34ec 100644 --- a/internal/dao/jinzhu/dbr/wallet_statement.go +++ b/internal/dao/jinzhu/dbr/wallet_statement.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/dao/jinzhu/index.go b/internal/dao/jinzhu/index.go index 31712c61..7548de49 100644 --- a/internal/dao/jinzhu/index.go +++ b/internal/dao/jinzhu/index.go @@ -1,9 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "github.com/sirupsen/logrus" "gorm.io/gorm" ) @@ -40,20 +43,20 @@ func newSimpleIndexPostsService(db *gorm.DB) core.IndexPostsService { } // IndexPosts 根据userId查询广场推文列表,简单做到不同用户的主页都是不同的; -func (s *indexPostsServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { - predicates := model.Predicates{ +func (s *indexPostsServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { + predicates := dbr.Predicates{ "ORDER": []any{"is_top DESC, latest_replied_on DESC"}, } if user == nil { - predicates["visibility = ?"] = []any{model.PostVisitPublic} + predicates["visibility = ?"] = []any{dbr.PostVisitPublic} } else if !user.IsAdmin { friendIds, _ := s.ams.BeFriendIds(user.ID) friendIds = append(friendIds, user.ID) - args := []any{model.PostVisitPublic, model.PostVisitPrivate, user.ID, model.PostVisitFriend, friendIds} + args := []any{dbr.PostVisitPublic, dbr.PostVisitPrivate, user.ID, dbr.PostVisitFriend, friendIds} predicates["visibility = ? OR (visibility = ? AND user_id = ?) OR (visibility = ? AND user_id IN ?)"] = args } - posts, err := (&model.Post{}).Fetch(s.db, predicates, offset, limit) + posts, err := (&dbr.Post{}).Fetch(s.db, predicates, offset, limit) if err != nil { logrus.Debugf("gormIndexPostsServant.IndexPosts err: %v", err) return nil, err @@ -63,25 +66,25 @@ func (s *indexPostsServant) IndexPosts(user *model.User, offset int, limit int) return nil, err } - total, err := (&model.Post{}).CountBy(s.db, predicates) + total, err := (&dbr.Post{}).CountBy(s.db, predicates) if err != nil { return nil, err } - return &rest.IndexTweetsResp{ + return &core.IndexTweetList{ Tweets: formatPosts, Total: total, }, nil } // simpleCacheIndexGetPosts simpleCacheIndex 专属获取广场推文列表函数 -func (s *simpleIndexPostsServant) IndexPosts(_user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { - predicates := model.Predicates{ - "visibility = ?": []any{model.PostVisitPublic}, +func (s *simpleIndexPostsServant) IndexPosts(_user *core.User, offset int, limit int) (*core.IndexTweetList, error) { + predicates := dbr.Predicates{ + "visibility = ?": []any{dbr.PostVisitPublic}, "ORDER": []any{"is_top DESC, latest_replied_on DESC"}, } - posts, err := (&model.Post{}).Fetch(s.db, predicates, offset, limit) + posts, err := (&dbr.Post{}).Fetch(s.db, predicates, offset, limit) if err != nil { logrus.Debugf("gormSimpleIndexPostsServant.IndexPosts err: %v", err) return nil, err @@ -92,12 +95,12 @@ func (s *simpleIndexPostsServant) IndexPosts(_user *model.User, offset int, limi return nil, err } - total, err := (&model.Post{}).CountBy(s.db, predicates) + total, err := (&dbr.Post{}).CountBy(s.db, predicates) if err != nil { return nil, err } - return &rest.IndexTweetsResp{ + return &core.IndexTweetList{ Tweets: formatPosts, Total: total, }, nil diff --git a/internal/dao/jinzhu/jinzhu.go b/internal/dao/jinzhu/jinzhu.go index 9f5e1c66..753bb639 100644 --- a/internal/dao/jinzhu/jinzhu.go +++ b/internal/dao/jinzhu/jinzhu.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + // Core service implement base gorm+mysql/postgresql/sqlite3. // Jinzhu is the primary developer of gorm so use his name as // package name as a saluter. diff --git a/internal/dao/jinzhu/messages.go b/internal/dao/jinzhu/messages.go index 3e282776..32edaac2 100644 --- a/internal/dao/jinzhu/messages.go +++ b/internal/dao/jinzhu/messages.go @@ -1,8 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -20,37 +24,37 @@ func newMessageService(db *gorm.DB) core.MessageService { } } -func (d *messageServant) CreateMessage(msg *model.Message) (*model.Message, error) { +func (d *messageServant) CreateMessage(msg *core.Message) (*core.Message, error) { return msg.Create(d.db) } func (d *messageServant) GetUnreadCount(userID int64) (int64, error) { - return (&model.Message{}).Count(d.db, &model.ConditionsT{ + return (&dbr.Message{}).Count(d.db, &dbr.ConditionsT{ "receiver_user_id": userID, - "is_read": model.MsgStatusUnread, + "is_read": dbr.MsgStatusUnread, }) } -func (d *messageServant) GetMessageByID(id int64) (*model.Message, error) { - return (&model.Message{ - Model: &model.Model{ +func (d *messageServant) GetMessageByID(id int64) (*core.Message, error) { + return (&dbr.Message{ + Model: &dbr.Model{ ID: id, }, }).Get(d.db) } -func (d *messageServant) ReadMessage(message *model.Message) error { +func (d *messageServant) ReadMessage(message *core.Message) error { message.IsRead = 1 return message.Update(d.db) } -func (d *messageServant) GetMessages(conditions *model.ConditionsT, offset, limit int) ([]*model.MessageFormated, error) { - messages, err := (&model.Message{}).List(d.db, conditions, offset, limit) +func (d *messageServant) GetMessages(conditions *core.ConditionsT, offset, limit int) ([]*core.MessageFormated, error) { + messages, err := (&dbr.Message{}).List(d.db, conditions, offset, limit) if err != nil { return nil, err } - mfs := []*model.MessageFormated{} + mfs := []*dbr.MessageFormated{} for _, message := range messages { mf := message.Format() mfs = append(mfs, mf) @@ -59,6 +63,6 @@ func (d *messageServant) GetMessages(conditions *model.ConditionsT, offset, limi return mfs, nil } -func (d *messageServant) GetMessageCount(conditions *model.ConditionsT) (int64, error) { - return (&model.Message{}).Count(d.db, conditions) +func (d *messageServant) GetMessageCount(conditions *core.ConditionsT) (int64, error) { + return (&dbr.Message{}).Count(d.db, conditions) } diff --git a/internal/dao/jinzhu/security.go b/internal/dao/jinzhu/security.go index dfbe2c74..49f66074 100644 --- a/internal/dao/jinzhu/security.go +++ b/internal/dao/jinzhu/security.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( @@ -10,7 +14,7 @@ import ( "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "github.com/rocboss/paopao-ce/pkg/json" "gopkg.in/resty.v1" "gorm.io/gorm" @@ -36,14 +40,14 @@ type juhePhoneCaptchaRsp struct { } // 获取最新短信验证码 -func (s *securityServant) GetLatestPhoneCaptcha(phone string) (*model.Captcha, error) { - return (&model.Captcha{ +func (s *securityServant) GetLatestPhoneCaptcha(phone string) (*core.Captcha, error) { + return (&dbr.Captcha{ Phone: phone, }).Get(s.db) } // 更新短信验证码 -func (s *securityServant) UsePhoneCaptcha(captcha *model.Captcha) error { +func (s *securityServant) UsePhoneCaptcha(captcha *core.Captcha) error { captcha.UseTimes++ return captcha.Update(s.db) } @@ -82,7 +86,7 @@ func (s *securityServant) SendPhoneCaptcha(phone string) error { } // 写入表 - captchaModel := &model.Captcha{ + captchaModel := &dbr.Captcha{ Phone: phone, Captcha: strconv.Itoa(captcha), ExpiredOn: time.Now().Add(time.Minute * time.Duration(m)).Unix(), diff --git a/internal/dao/jinzhu/topics.go b/internal/dao/jinzhu/topics.go index 0524b71b..d5ce70a9 100644 --- a/internal/dao/jinzhu/topics.go +++ b/internal/dao/jinzhu/topics.go @@ -1,10 +1,14 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "strings" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -22,28 +26,28 @@ func newTopicService(db *gorm.DB) core.TopicService { } } -func (s *topicServant) CreateTag(tag *model.Tag) (*model.Tag, error) { +func (s *topicServant) CreateTag(tag *core.Tag) (*core.Tag, error) { return createTag(s.db, tag) } -func (s *topicServant) DeleteTag(tag *model.Tag) error { +func (s *topicServant) DeleteTag(tag *core.Tag) error { return deleteTag(s.db, tag) } -func (s *topicServant) GetTags(conditions *model.ConditionsT, offset, limit int) ([]*model.Tag, error) { - return (&model.Tag{}).List(s.db, conditions, offset, limit) +func (s *topicServant) GetTags(conditions *core.ConditionsT, offset, limit int) ([]*core.Tag, error) { + return (&dbr.Tag{}).List(s.db, conditions, offset, limit) } -func (s *topicServant) GetTagsByKeyword(keyword string) ([]*model.Tag, error) { - tag := &model.Tag{} +func (s *topicServant) GetTagsByKeyword(keyword string) ([]*core.Tag, error) { + tag := &dbr.Tag{} keyword = "%" + strings.Trim(keyword, " ") + "%" if keyword == "%%" { - return tag.List(s.db, &model.ConditionsT{ + return tag.List(s.db, &dbr.ConditionsT{ "ORDER": "quote_num DESC", }, 0, 6) } else { - return tag.List(s.db, &model.ConditionsT{ + return tag.List(s.db, &dbr.ConditionsT{ "tag LIKE ?": keyword, "ORDER": "quote_num DESC", }, 0, 6) diff --git a/internal/dao/jinzhu/tweets.go b/internal/dao/jinzhu/tweets.go index 12e6f21c..186b7280 100644 --- a/internal/dao/jinzhu/tweets.go +++ b/internal/dao/jinzhu/tweets.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( @@ -5,7 +9,7 @@ import ( "time" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -48,7 +52,7 @@ func newTweetHelpService(db *gorm.DB) core.TweetHelpService { } // MergePosts post数据整合 -func (s *tweetHelpServant) MergePosts(posts []*model.Post) ([]*model.PostFormated, error) { +func (s *tweetHelpServant) MergePosts(posts []*core.Post) ([]*core.PostFormated, error) { postIds := make([]int64, 0, len(posts)) userIds := make([]int64, 0, len(posts)) for _, post := range posts { @@ -66,18 +70,18 @@ func (s *tweetHelpServant) MergePosts(posts []*model.Post) ([]*model.PostFormate return nil, err } - userMap := make(map[int64]*model.UserFormated, len(users)) + userMap := make(map[int64]*dbr.UserFormated, len(users)) for _, user := range users { userMap[user.ID] = user.Format() } - contentMap := make(map[int64][]*model.PostContentFormated, len(postContents)) + contentMap := make(map[int64][]*dbr.PostContentFormated, len(postContents)) for _, content := range postContents { contentMap[content.PostID] = append(contentMap[content.PostID], content.Format()) } // 数据整合 - postsFormated := make([]*model.PostFormated, 0, len(posts)) + postsFormated := make([]*dbr.PostFormated, 0, len(posts)) for _, post := range posts { postFormated := post.Format() postFormated.User = userMap[post.UserID] @@ -88,7 +92,7 @@ func (s *tweetHelpServant) MergePosts(posts []*model.Post) ([]*model.PostFormate } // RevampPosts post数据整形修复 -func (s *tweetHelpServant) RevampPosts(posts []*model.PostFormated) ([]*model.PostFormated, error) { +func (s *tweetHelpServant) RevampPosts(posts []*core.PostFormated) ([]*core.PostFormated, error) { postIds := make([]int64, 0, len(posts)) userIds := make([]int64, 0, len(posts)) for _, post := range posts { @@ -106,12 +110,12 @@ func (s *tweetHelpServant) RevampPosts(posts []*model.PostFormated) ([]*model.Po return nil, err } - userMap := make(map[int64]*model.UserFormated, len(users)) + userMap := make(map[int64]*dbr.UserFormated, len(users)) for _, user := range users { userMap[user.ID] = user.Format() } - contentMap := make(map[int64][]*model.PostContentFormated, len(postContents)) + contentMap := make(map[int64][]*dbr.PostContentFormated, len(postContents)) for _, content := range postContents { contentMap[content.PostID] = append(contentMap[content.PostID], content.Format()) } @@ -124,23 +128,23 @@ func (s *tweetHelpServant) RevampPosts(posts []*model.PostFormated) ([]*model.Po return posts, nil } -func (s *tweetHelpServant) getPostContentsByIDs(ids []int64) ([]*model.PostContent, error) { - return (&model.PostContent{}).List(s.db, &model.ConditionsT{ +func (s *tweetHelpServant) getPostContentsByIDs(ids []int64) ([]*dbr.PostContent, error) { + return (&dbr.PostContent{}).List(s.db, &dbr.ConditionsT{ "post_id IN ?": ids, "ORDER": "sort ASC", }, 0, 0) } -func (s *tweetHelpServant) getUsersByIDs(ids []int64) ([]*model.User, error) { - user := &model.User{} +func (s *tweetHelpServant) getUsersByIDs(ids []int64) ([]*dbr.User, error) { + user := &dbr.User{} - return user.List(s.db, &model.ConditionsT{ + return user.List(s.db, &dbr.ConditionsT{ "id IN ?": ids, }, 0, 0) } -func (s *tweetManageServant) CreatePostCollection(postID, userID int64) (*model.PostCollection, error) { - collection := &model.PostCollection{ +func (s *tweetManageServant) CreatePostCollection(postID, userID int64) (*core.PostCollection, error) { + collection := &dbr.PostCollection{ PostID: postID, UserID: userID, } @@ -148,19 +152,19 @@ func (s *tweetManageServant) CreatePostCollection(postID, userID int64) (*model. return collection.Create(s.db) } -func (s *tweetManageServant) DeletePostCollection(p *model.PostCollection) error { +func (s *tweetManageServant) DeletePostCollection(p *core.PostCollection) error { return p.Delete(s.db) } -func (s *tweetManageServant) CreatePostContent(content *model.PostContent) (*model.PostContent, error) { +func (s *tweetManageServant) CreatePostContent(content *core.PostContent) (*core.PostContent, error) { return content.Create(s.db) } -func (s *tweetManageServant) CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) { +func (s *tweetManageServant) CreateAttachment(attachment *core.Attachment) (*core.Attachment, error) { return attachment.Create(s.db) } -func (s *tweetManageServant) CreatePost(post *model.Post) (*model.Post, error) { +func (s *tweetManageServant) CreatePost(post *core.Post) (*core.Post, error) { post.LatestRepliedOn = time.Now().Unix() p, err := post.Create(s.db) if err != nil { @@ -170,11 +174,11 @@ func (s *tweetManageServant) CreatePost(post *model.Post) (*model.Post, error) { return p, nil } -func (s *tweetManageServant) DeletePost(post *model.Post) ([]string, error) { +func (s *tweetManageServant) DeletePost(post *core.Post) ([]string, error) { var mediaContents []string postId := post.ID - postContent := &model.PostContent{} + postContent := &dbr.PostContent{} err := s.db.Transaction( func(tx *gorm.DB) error { if contents, err := postContent.MediaContentsByPostId(tx, postId); err == nil { @@ -218,8 +222,8 @@ func (s *tweetManageServant) DeletePost(post *model.Post) ([]string, error) { } func (s *tweetManageServant) deleteCommentByPostId(db *gorm.DB, postId int64) ([]string, error) { - comment := &model.Comment{} - commentContent := &model.CommentContent{} + comment := &dbr.Comment{} + commentContent := &dbr.CommentContent{} // 获取推文的所有评论id commentIds, err := comment.CommentIdsByPostId(db, postId) @@ -244,19 +248,19 @@ func (s *tweetManageServant) deleteCommentByPostId(db *gorm.DB, postId int64) ([ } // 删评论的评论 - if err = (&model.CommentReply{}).DeleteByCommentIds(db, commentIds); err != nil { + if err = (&dbr.CommentReply{}).DeleteByCommentIds(db, commentIds); err != nil { return nil, err } return mediaContents, nil } -func (s *tweetManageServant) LockPost(post *model.Post) error { +func (s *tweetManageServant) LockPost(post *core.Post) error { post.IsLock = 1 - post.IsLock return post.Update(s.db) } -func (s *tweetManageServant) StickPost(post *model.Post) error { +func (s *tweetManageServant) StickPost(post *core.Post) error { post.IsTop = 1 - post.IsTop if err := post.Update(s.db); err != nil { return err @@ -265,7 +269,7 @@ func (s *tweetManageServant) StickPost(post *model.Post) error { return nil } -func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.PostVisibleT) error { +func (s *tweetManageServant) VisiblePost(post *core.Post, visibility core.PostVisibleT) error { oldVisibility := post.Visibility post.Visibility = visibility // TODO: 这个判断是否可以不要呢 @@ -273,7 +277,7 @@ func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.Post return nil } // 私密推文 特殊处理 - if visibility == model.PostVisitPrivate { + if visibility == dbr.PostVisitPrivate { // 强制取消置顶 // TODO: 置顶推文用户是否有权设置成私密? 后续完善 post.IsTop = 0 @@ -288,14 +292,14 @@ func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.Post // tag处理 tags := strings.Split(post.Tags, ",") for _, t := range tags { - tag := &model.Tag{ + tag := &dbr.Tag{ Tag: t, } // TODO: 暂时宽松不处理错误,这里或许可以有优化,后续完善 - if oldVisibility == model.PostVisitPrivate { + if oldVisibility == dbr.PostVisitPrivate { // 从私密转为非私密才需要重新创建tag createTag(db, tag) - } else if visibility == model.PostVisitPrivate { + } else if visibility == dbr.PostVisitPrivate { // 从非私密转为私密才需要删除tag deleteTag(db, tag) } @@ -305,7 +309,7 @@ func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.Post return nil } -func (s *tweetManageServant) UpdatePost(post *model.Post) error { +func (s *tweetManageServant) UpdatePost(post *core.Post) error { if err := post.Update(s.db); err != nil { return err } @@ -313,104 +317,104 @@ func (s *tweetManageServant) UpdatePost(post *model.Post) error { return nil } -func (s *tweetManageServant) CreatePostStar(postID, userID int64) (*model.PostStar, error) { - star := &model.PostStar{ +func (s *tweetManageServant) CreatePostStar(postID, userID int64) (*core.PostStar, error) { + star := &dbr.PostStar{ PostID: postID, UserID: userID, } return star.Create(s.db) } -func (s *tweetManageServant) DeletePostStar(p *model.PostStar) error { +func (s *tweetManageServant) DeletePostStar(p *core.PostStar) error { return p.Delete(s.db) } -func (s *tweetServant) GetPostByID(id int64) (*model.Post, error) { - post := &model.Post{ - Model: &model.Model{ +func (s *tweetServant) GetPostByID(id int64) (*core.Post, error) { + post := &dbr.Post{ + Model: &dbr.Model{ ID: id, }, } return post.Get(s.db) } -func (s *tweetServant) GetPosts(conditions *model.ConditionsT, offset, limit int) ([]*model.Post, error) { - return (&model.Post{}).List(s.db, conditions, offset, limit) +func (s *tweetServant) GetPosts(conditions *core.ConditionsT, offset, limit int) ([]*core.Post, error) { + return (&dbr.Post{}).List(s.db, conditions, offset, limit) } -func (s *tweetServant) GetPostCount(conditions *model.ConditionsT) (int64, error) { - return (&model.Post{}).Count(s.db, conditions) +func (s *tweetServant) GetPostCount(conditions *core.ConditionsT) (int64, error) { + return (&dbr.Post{}).Count(s.db, conditions) } -func (s *tweetServant) GetUserPostStar(postID, userID int64) (*model.PostStar, error) { - star := &model.PostStar{ +func (s *tweetServant) GetUserPostStar(postID, userID int64) (*core.PostStar, error) { + star := &dbr.PostStar{ PostID: postID, UserID: userID, } return star.Get(s.db) } -func (s *tweetServant) GetUserPostStars(userID int64, offset, limit int) ([]*model.PostStar, error) { - star := &model.PostStar{ +func (s *tweetServant) GetUserPostStars(userID int64, offset, limit int) ([]*core.PostStar, error) { + star := &dbr.PostStar{ UserID: userID, } - return star.List(s.db, &model.ConditionsT{ + return star.List(s.db, &dbr.ConditionsT{ "ORDER": s.db.NamingStrategy.TableName("PostStar") + ".id DESC", }, offset, limit) } func (s *tweetServant) GetUserPostStarCount(userID int64) (int64, error) { - star := &model.PostStar{ + star := &dbr.PostStar{ UserID: userID, } - return star.Count(s.db, &model.ConditionsT{}) + return star.Count(s.db, &dbr.ConditionsT{}) } -func (s *tweetServant) GetUserPostCollection(postID, userID int64) (*model.PostCollection, error) { - star := &model.PostCollection{ +func (s *tweetServant) GetUserPostCollection(postID, userID int64) (*core.PostCollection, error) { + star := &dbr.PostCollection{ PostID: postID, UserID: userID, } return star.Get(s.db) } -func (s *tweetServant) GetUserPostCollections(userID int64, offset, limit int) ([]*model.PostCollection, error) { - collection := &model.PostCollection{ +func (s *tweetServant) GetUserPostCollections(userID int64, offset, limit int) ([]*core.PostCollection, error) { + collection := &dbr.PostCollection{ UserID: userID, } - return collection.List(s.db, &model.ConditionsT{ + return collection.List(s.db, &dbr.ConditionsT{ "ORDER": s.db.NamingStrategy.TableName("PostCollection") + ".id DESC", }, offset, limit) } func (s *tweetServant) GetUserPostCollectionCount(userID int64) (int64, error) { - collection := &model.PostCollection{ + collection := &dbr.PostCollection{ UserID: userID, } - return collection.Count(s.db, &model.ConditionsT{}) + return collection.Count(s.db, &dbr.ConditionsT{}) } -func (s *tweetServant) GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, error) { - statement := &model.WalletStatement{ +func (s *tweetServant) GetUserWalletBills(userID int64, offset, limit int) ([]*core.WalletStatement, error) { + statement := &dbr.WalletStatement{ UserID: userID, } - return statement.List(s.db, &model.ConditionsT{ + return statement.List(s.db, &dbr.ConditionsT{ "ORDER": "id DESC", }, offset, limit) } func (s *tweetServant) GetUserWalletBillCount(userID int64) (int64, error) { - statement := &model.WalletStatement{ + statement := &dbr.WalletStatement{ UserID: userID, } - return statement.Count(s.db, &model.ConditionsT{}) + return statement.Count(s.db, &dbr.ConditionsT{}) } -func (s *tweetServant) GetPostAttatchmentBill(postID, userID int64) (*model.PostAttachmentBill, error) { - bill := &model.PostAttachmentBill{ +func (s *tweetServant) GetPostAttatchmentBill(postID, userID int64) (*core.PostAttachmentBill, error) { + bill := &dbr.PostAttachmentBill{ PostID: postID, UserID: userID, } @@ -418,16 +422,16 @@ func (s *tweetServant) GetPostAttatchmentBill(postID, userID int64) (*model.Post return bill.Get(s.db) } -func (s *tweetServant) GetPostContentsByIDs(ids []int64) ([]*model.PostContent, error) { - return (&model.PostContent{}).List(s.db, &model.ConditionsT{ +func (s *tweetServant) GetPostContentsByIDs(ids []int64) ([]*core.PostContent, error) { + return (&dbr.PostContent{}).List(s.db, &dbr.ConditionsT{ "post_id IN ?": ids, "ORDER": "sort ASC", }, 0, 0) } -func (s *tweetServant) GetPostContentByID(id int64) (*model.PostContent, error) { - return (&model.PostContent{ - Model: &model.Model{ +func (s *tweetServant) GetPostContentByID(id int64) (*core.PostContent, error) { + return (&dbr.PostContent{ + Model: &dbr.Model{ ID: id, }, }).Get(s.db) diff --git a/internal/dao/jinzhu/user.go b/internal/dao/jinzhu/user.go index e1380f00..96d09fc1 100644 --- a/internal/dao/jinzhu/user.go +++ b/internal/dao/jinzhu/user.go @@ -1,10 +1,14 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "strings" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -22,69 +26,69 @@ func newUserManageService(db *gorm.DB) core.UserManageService { } } -func (s *userManageServant) GetUserByID(id int64) (*model.User, error) { - user := &model.User{ - Model: &model.Model{ +func (s *userManageServant) GetUserByID(id int64) (*core.User, error) { + user := &dbr.User{ + Model: &dbr.Model{ ID: id, }, } return user.Get(s.db) } -func (s *userManageServant) GetUserByUsername(username string) (*model.User, error) { - user := &model.User{ +func (s *userManageServant) GetUserByUsername(username string) (*core.User, error) { + user := &dbr.User{ Username: username, } return user.Get(s.db) } -func (s *userManageServant) GetUserByPhone(phone string) (*model.User, error) { - user := &model.User{ +func (s *userManageServant) GetUserByPhone(phone string) (*core.User, error) { + user := &dbr.User{ Phone: phone, } return user.Get(s.db) } -func (s *userManageServant) GetUsersByIDs(ids []int64) ([]*model.User, error) { - user := &model.User{} - return user.List(s.db, &model.ConditionsT{ +func (s *userManageServant) GetUsersByIDs(ids []int64) ([]*core.User, error) { + user := &dbr.User{} + return user.List(s.db, &dbr.ConditionsT{ "id IN ?": ids, }, 0, 0) } -func (s *userManageServant) GetUsersByKeyword(keyword string) ([]*model.User, error) { - user := &model.User{} +func (s *userManageServant) GetUsersByKeyword(keyword string) ([]*core.User, error) { + user := &dbr.User{} keyword = strings.Trim(keyword, " ") + "%" if keyword == "%" { - return user.List(s.db, &model.ConditionsT{ + return user.List(s.db, &dbr.ConditionsT{ "ORDER": "id ASC", }, 0, 6) } else { - return user.List(s.db, &model.ConditionsT{ + return user.List(s.db, &dbr.ConditionsT{ "username LIKE ?": keyword, }, 0, 6) } } -func (s *userManageServant) GetTagsByKeyword(keyword string) ([]*model.Tag, error) { - tag := &model.Tag{} +func (s *userManageServant) GetTagsByKeyword(keyword string) ([]*core.Tag, error) { + tag := &dbr.Tag{} keyword = "%" + strings.Trim(keyword, " ") + "%" if keyword == "%%" { - return tag.List(s.db, &model.ConditionsT{ + return tag.List(s.db, &dbr.ConditionsT{ "ORDER": "quote_num DESC", }, 0, 6) } else { - return tag.List(s.db, &model.ConditionsT{ + return tag.List(s.db, &dbr.ConditionsT{ "tag LIKE ?": keyword, "ORDER": "quote_num DESC", }, 0, 6) } } -func (s *userManageServant) CreateUser(user *model.User) (*model.User, error) { +func (s *userManageServant) CreateUser(user *dbr.User) (*core.User, error) { return user.Create(s.db) } -func (s *userManageServant) UpdateUser(user *model.User) error { +func (s *userManageServant) UpdateUser(user *core.User) error { return user.Update(s.db) } diff --git a/internal/dao/jinzhu/utils.go b/internal/dao/jinzhu/utils.go index 8c866027..27766397 100644 --- a/internal/dao/jinzhu/utils.go +++ b/internal/dao/jinzhu/utils.go @@ -1,11 +1,15 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) -func createTag(db *gorm.DB, tag *model.Tag) (*model.Tag, error) { +func createTag(db *gorm.DB, tag *dbr.Tag) (*dbr.Tag, error) { t, err := tag.Get(db) if err != nil { tag.QuoteNum = 1 @@ -23,7 +27,7 @@ func createTag(db *gorm.DB, tag *model.Tag) (*model.Tag, error) { return t, nil } -func deleteTag(db *gorm.DB, tag *model.Tag) error { +func deleteTag(db *gorm.DB, tag *dbr.Tag) error { tag, err := tag.Get(db) if err != nil { return err @@ -33,7 +37,7 @@ func deleteTag(db *gorm.DB, tag *model.Tag) error { } func deleteTags(db *gorm.DB, tags []string) error { - allTags, err := (&model.Tag{}).TagsFrom(db, tags) + allTags, err := (&dbr.Tag{}).TagsFrom(db, tags) if err != nil { return err } @@ -51,9 +55,9 @@ func deleteTags(db *gorm.DB, tags []string) error { } // 根据IDs获取用户列表 -func getUsersByIDs(db *gorm.DB, ids []int64) ([]*model.User, error) { - user := &model.User{} - return user.List(db, &model.ConditionsT{ +func getUsersByIDs(db *gorm.DB, ids []int64) ([]*dbr.User, error) { + user := &dbr.User{} + return user.List(db, &dbr.ConditionsT{ "id IN ?": ids, }, 0, 0) } diff --git a/internal/dao/jinzhu/wallet.go b/internal/dao/jinzhu/wallet.go index 3b4f9ea1..7b2023d7 100644 --- a/internal/dao/jinzhu/wallet.go +++ b/internal/dao/jinzhu/wallet.go @@ -1,9 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -21,17 +25,17 @@ func newWalletService(db *gorm.DB) core.WalletService { } } -func (d *walletServant) GetRechargeByID(id int64) (*model.WalletRecharge, error) { - recharge := &model.WalletRecharge{ - Model: &model.Model{ +func (d *walletServant) GetRechargeByID(id int64) (*core.WalletRecharge, error) { + recharge := &dbr.WalletRecharge{ + Model: &dbr.Model{ ID: id, }, } return recharge.Get(d.db) } -func (d *walletServant) CreateRecharge(userId, amount int64) (*model.WalletRecharge, error) { - recharge := &model.WalletRecharge{ +func (d *walletServant) CreateRecharge(userId, amount int64) (*core.WalletRecharge, error) { + recharge := &dbr.WalletRecharge{ UserID: userId, Amount: amount, } @@ -39,26 +43,26 @@ func (d *walletServant) CreateRecharge(userId, amount int64) (*model.WalletRecha return recharge.Create(d.db) } -func (d *walletServant) GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, error) { - statement := &model.WalletStatement{ +func (d *walletServant) GetUserWalletBills(userID int64, offset, limit int) ([]*core.WalletStatement, error) { + statement := &dbr.WalletStatement{ UserID: userID, } - return statement.List(d.db, &model.ConditionsT{ + return statement.List(d.db, &dbr.ConditionsT{ "ORDER": "id DESC", }, offset, limit) } func (d *walletServant) GetUserWalletBillCount(userID int64) (int64, error) { - statement := &model.WalletStatement{ + statement := &dbr.WalletStatement{ UserID: userID, } - return statement.Count(d.db, &model.ConditionsT{}) + return statement.Count(d.db, &dbr.ConditionsT{}) } -func (d *walletServant) HandleRechargeSuccess(recharge *model.WalletRecharge, tradeNo string) error { - user, _ := (&model.User{ - Model: &model.Model{ +func (d *walletServant) HandleRechargeSuccess(recharge *core.WalletRecharge, tradeNo string) error { + user, _ := (&dbr.User{ + Model: &dbr.Model{ ID: recharge.UserID, }, }).Get(d.db) @@ -71,7 +75,7 @@ func (d *walletServant) HandleRechargeSuccess(recharge *model.WalletRecharge, tr } // 新增账单 - if err := tx.Create(&model.WalletStatement{ + if err := tx.Create(&dbr.WalletStatement{ UserID: user.ID, ChangeAmount: recharge.Amount, BalanceSnapshot: user.Balance + recharge.Amount, @@ -93,7 +97,7 @@ func (d *walletServant) HandleRechargeSuccess(recharge *model.WalletRecharge, tr }) } -func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model.User) error { +func (d *walletServant) HandlePostAttachmentBought(post *core.Post, user *core.User) error { return d.db.Transaction(func(tx *gorm.DB) error { // 扣除金额 if err := tx.Model(user).Update("balance", gorm.Expr("balance - ?", post.AttachmentPrice)).Error; err != nil { @@ -102,7 +106,7 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model } // 新增账单 - if err := tx.Create(&model.WalletStatement{ + if err := tx.Create(&dbr.WalletStatement{ PostID: post.ID, UserID: user.ID, ChangeAmount: -post.AttachmentPrice, @@ -113,7 +117,7 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model } // 新增附件购买记录 - if err := tx.Create(&model.PostAttachmentBill{ + if err := tx.Create(&dbr.PostAttachmentBill{ PostID: post.ID, UserID: user.ID, PaidAmount: post.AttachmentPrice, @@ -124,8 +128,8 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model // 对附件主新增账单 income := int64(float64(post.AttachmentPrice) * conf.AppSetting.AttachmentIncomeRate) if income > 0 { - master := &model.User{ - Model: &model.Model{ + master := &dbr.User{ + Model: &dbr.Model{ ID: post.UserID, }, } @@ -137,7 +141,7 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model } // 新增账单 - if err := tx.Create(&model.WalletStatement{ + if err := tx.Create(&dbr.WalletStatement{ PostID: post.ID, UserID: master.ID, ChangeAmount: income, diff --git a/internal/dao/sakila/sakila.go b/internal/dao/sakila/sakila.go index 6efdffa6..d82a0d23 100644 --- a/internal/dao/sakila/sakila.go +++ b/internal/dao/sakila/sakila.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + // Core service implement base sqlx+mysql. All sub-service // will declare here and provide initial function. diff --git a/internal/dao/search/bridge.go b/internal/dao/search/bridge.go index 84f469a5..f23aaa25 100644 --- a/internal/dao/search/bridge.go +++ b/internal/dao/search/bridge.go @@ -1,10 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( "time" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/sirupsen/logrus" ) @@ -43,7 +46,7 @@ func (s *bridgeTweetSearchServant) DeleteDocuments(identifiers []string) error { return nil } -func (s *bridgeTweetSearchServant) Search(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *bridgeTweetSearchServant) Search(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { return s.ts.Search(user, q, offset, limit) } diff --git a/internal/dao/search/filter.go b/internal/dao/search/filter.go index 229f2482..5840e189 100644 --- a/internal/dao/search/filter.go +++ b/internal/dao/search/filter.go @@ -1,8 +1,11 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/types" ) @@ -10,19 +13,19 @@ type tweetSearchFilter struct { ams core.AuthorizationManageService } -func (s *tweetSearchFilter) filterResp(user *model.User, resp *core.QueryResp) { +func (s *tweetSearchFilter) filterResp(user *core.User, resp *core.QueryResp) { // 管理员不过滤 if user != nil && user.IsAdmin { return } - var item *model.PostFormated + var item *core.PostFormated items := resp.Items latestIndex := len(items) - 1 if user == nil { for i := 0; i <= latestIndex; i++ { item = items[i] - if item.Visibility != model.PostVisitPublic { + if item.Visibility != core.PostVisitPublic { items[i] = items[latestIndex] items = items[:latestIndex] resp.Total-- @@ -36,8 +39,8 @@ func (s *tweetSearchFilter) filterResp(user *model.User, resp *core.QueryResp) { friendFilter[user.ID] = types.Empty{} for i := 0; i <= latestIndex; i++ { item = items[i] - cutFriend = (item.Visibility == model.PostVisitFriend && !friendFilter.IsFriend(item.UserID)) - cutPrivate = (item.Visibility == model.PostVisitPrivate && user.ID != item.UserID) + cutFriend = (item.Visibility == core.PostVisitFriend && !friendFilter.IsFriend(item.UserID)) + cutPrivate = (item.Visibility == core.PostVisitPrivate && user.ID != item.UserID) if cutFriend || cutPrivate { items[i] = items[latestIndex] items = items[:latestIndex] diff --git a/internal/dao/search/meili.go b/internal/dao/search/meili.go index 321953ee..b2ee4d16 100644 --- a/internal/dao/search/meili.go +++ b/internal/dao/search/meili.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( @@ -7,7 +11,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/meilisearch/meilisearch-go" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/json" "github.com/sirupsen/logrus" ) @@ -28,20 +31,20 @@ type meiliTweetSearchServant struct { } type postInfo struct { - ID int64 `json:"id"` - UserID int64 `json:"user_id"` - CommentCount int64 `json:"comment_count"` - CollectionCount int64 `json:"collection_count"` - UpvoteCount int64 `json:"upvote_count"` - Visibility model.PostVisibleT `json:"visibility"` - IsTop int `json:"is_top"` - IsEssence int `json:"is_essence"` - IsLock int `json:"is_lock"` - LatestRepliedOn int64 `json:"latest_replied_on"` - CreatedOn int64 `json:"created_on"` - ModifiedOn int64 `json:"modified_on"` - AttachmentPrice int64 `json:"attachment_price"` - IPLoc string `json:"ip_loc"` + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + CommentCount int64 `json:"comment_count"` + CollectionCount int64 `json:"collection_count"` + UpvoteCount int64 `json:"upvote_count"` + Visibility core.PostVisibleT `json:"visibility"` + IsTop int `json:"is_top"` + IsEssence int `json:"is_essence"` + IsLock int `json:"is_lock"` + LatestRepliedOn int64 `json:"latest_replied_on"` + CreatedOn int64 `json:"created_on"` + ModifiedOn int64 `json:"modified_on"` + AttachmentPrice int64 `json:"attachment_price"` + IPLoc string `json:"ip_loc"` } func (s *meiliTweetSearchServant) Name() string { @@ -78,7 +81,7 @@ func (s *meiliTweetSearchServant) DeleteDocuments(identifiers []string) error { return nil } -func (s *meiliTweetSearchServant) Search(user *model.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) { +func (s *meiliTweetSearchServant) Search(user *core.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) { if q.Type == core.SearchTypeDefault && q.Query != "" { resp, err = s.queryByContent(user, q, offset, limit) } else if q.Type == core.SearchTypeTag && q.Query != "" { @@ -96,7 +99,7 @@ func (s *meiliTweetSearchServant) Search(user *model.User, q *core.QueryReq, off return } -func (s *meiliTweetSearchServant) queryByContent(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *meiliTweetSearchServant) queryByContent(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { request := &meilisearch.SearchRequest{ Offset: int64(offset), Limit: int64(limit), @@ -117,7 +120,7 @@ func (s *meiliTweetSearchServant) queryByContent(user *model.User, q *core.Query return s.postsFrom(resp) } -func (s *meiliTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *meiliTweetSearchServant) queryByTag(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { request := &meilisearch.SearchRequest{ Offset: int64(offset), Limit: int64(limit), @@ -141,7 +144,7 @@ func (s *meiliTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, return s.postsFrom(resp) } -func (s *meiliTweetSearchServant) queryAny(user *model.User, offset, limit int) (*core.QueryResp, error) { +func (s *meiliTweetSearchServant) queryAny(user *core.User, offset, limit int) (*core.QueryResp, error) { request := &meilisearch.SearchRequest{ Offset: int64(offset), Limit: int64(limit), @@ -161,7 +164,7 @@ func (s *meiliTweetSearchServant) queryAny(user *model.User, offset, limit int) return s.postsFrom(resp) } -func (s *meiliTweetSearchServant) filterList(user *model.User) string { +func (s *meiliTweetSearchServant) filterList(user *core.User) string { if user == nil { return s.publicFilter } @@ -174,7 +177,7 @@ func (s *meiliTweetSearchServant) filterList(user *model.User) string { } func (s *meiliTweetSearchServant) postsFrom(resp *meilisearch.SearchResponse) (*core.QueryResp, error) { - posts := make([]*model.PostFormated, 0, len(resp.Hits)) + posts := make([]*core.PostFormated, 0, len(resp.Hits)) for _, hit := range resp.Hits { raw, err := json.Marshal(hit) if err != nil { @@ -184,7 +187,7 @@ func (s *meiliTweetSearchServant) postsFrom(resp *meilisearch.SearchResponse) (* if err = json.Unmarshal(raw, p); err != nil { return nil, err } - posts = append(posts, &model.PostFormated{ + posts = append(posts, &core.PostFormated{ ID: p.ID, UserID: p.UserID, CommentCount: p.CommentCount, diff --git a/internal/dao/search/search.go b/internal/dao/search/search.go index 1dda80ef..baf0923b 100644 --- a/internal/dao/search/search.go +++ b/internal/dao/search/search.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( @@ -6,7 +10,6 @@ import ( "github.com/meilisearch/meilisearch-go" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/zinc" "github.com/sirupsen/logrus" ) @@ -40,9 +43,9 @@ func NewMeiliTweetSearchService(ams core.AuthorizationManageService) (core.Tweet }, client: client, index: client.Index(s.Index), - publicFilter: fmt.Sprintf("visibility=%d", model.PostVisitPublic), - privateFilter: fmt.Sprintf("visibility=%d AND user_id=", model.PostVisitPrivate), - friendFilter: fmt.Sprintf("visibility=%d", model.PostVisitFriend), + publicFilter: fmt.Sprintf("visibility=%d", core.PostVisitPublic), + privateFilter: fmt.Sprintf("visibility=%d AND user_id=", core.PostVisitPrivate), + friendFilter: fmt.Sprintf("visibility=%d", core.PostVisitFriend), } return mts, mts } @@ -55,9 +58,9 @@ func NewZincTweetSearchService(ams core.AuthorizationManageService) (core.TweetS }, indexName: s.Index, client: zinc.NewClient(s), - publicFilter: fmt.Sprintf("visibility:%d", model.PostVisitPublic), - privateFilter: fmt.Sprintf("visibility:%d AND user_id:%%d", model.PostVisitPrivate), - friendFilter: fmt.Sprintf("visibility:%d", model.PostVisitFriend), + publicFilter: fmt.Sprintf("visibility:%d", core.PostVisitPublic), + privateFilter: fmt.Sprintf("visibility:%d AND user_id:%%d", core.PostVisitPrivate), + friendFilter: fmt.Sprintf("visibility:%d", core.PostVisitFriend), } zts.createIndex() diff --git a/internal/dao/search/zinc.go b/internal/dao/search/zinc.go index c038cb90..ea9a7fa5 100644 --- a/internal/dao/search/zinc.go +++ b/internal/dao/search/zinc.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( @@ -5,7 +9,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/json" "github.com/rocboss/paopao-ce/pkg/zinc" "github.com/sirupsen/logrus" @@ -73,7 +76,7 @@ func (s *zincTweetSearchServant) DeleteDocuments(identifiers []string) error { return nil } -func (s *zincTweetSearchServant) Search(user *model.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) { +func (s *zincTweetSearchServant) Search(user *core.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) { if q.Type == core.SearchTypeDefault && q.Query != "" { resp, err = s.queryByContent(user, q, offset, limit) } else if q.Type == core.SearchTypeTag && q.Query != "" { @@ -91,7 +94,7 @@ func (s *zincTweetSearchServant) Search(user *model.User, q *core.QueryReq, offs return } -func (s *zincTweetSearchServant) queryByContent(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *zincTweetSearchServant) queryByContent(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { resp, err := s.client.EsQuery(s.indexName, map[string]any{ "query": map[string]any{ "match_phrase": map[string]any{ @@ -108,7 +111,7 @@ func (s *zincTweetSearchServant) queryByContent(user *model.User, q *core.QueryR return s.postsFrom(resp) } -func (s *zincTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *zincTweetSearchServant) queryByTag(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { resp, err := s.client.ApiQuery(s.indexName, map[string]any{ "search_type": "querystring", "query": map[string]any{ @@ -124,7 +127,7 @@ func (s *zincTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, return s.postsFrom(resp) } -func (s *zincTweetSearchServant) queryAny(user *model.User, offset, limit int) (*core.QueryResp, error) { +func (s *zincTweetSearchServant) queryAny(user *core.User, offset, limit int) (*core.QueryResp, error) { queryMap := map[string]any{ "query": map[string]any{ "match_all": map[string]string{}, @@ -141,9 +144,9 @@ func (s *zincTweetSearchServant) queryAny(user *model.User, offset, limit int) ( } func (s *zincTweetSearchServant) postsFrom(resp *zinc.QueryResultT) (*core.QueryResp, error) { - posts := make([]*model.PostFormated, 0, len(resp.Hits.Hits)) + posts := make([]*core.PostFormated, 0, len(resp.Hits.Hits)) for _, hit := range resp.Hits.Hits { - item := &model.PostFormated{} + item := &core.PostFormated{} raw, err := json.Marshal(hit.Source) if err != nil { return nil, err diff --git a/internal/dao/security/attachment.go b/internal/dao/security/attachment.go index 3bd79461..706621ac 100644 --- a/internal/dao/security/attachment.go +++ b/internal/dao/security/attachment.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package security import ( diff --git a/internal/dao/slonik/slonik.go b/internal/dao/slonik/slonik.go index 8cfb49c3..bb8f82ad 100644 --- a/internal/dao/slonik/slonik.go +++ b/internal/dao/slonik/slonik.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + // Core service implement base sqlx+postgresql. All sub-service // will declare here and provide initial function. diff --git a/internal/dao/storage/alioss.go b/internal/dao/storage/alioss.go index 3519cba5..e72fa44c 100644 --- a/internal/dao/storage/alioss.go +++ b/internal/dao/storage/alioss.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/cos.go b/internal/dao/storage/cos.go index f7a7ebad..3c2ea65f 100644 --- a/internal/dao/storage/cos.go +++ b/internal/dao/storage/cos.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/huaweiobs.go b/internal/dao/storage/huaweiobs.go index 31656e6c..7db9818b 100644 --- a/internal/dao/storage/huaweiobs.go +++ b/internal/dao/storage/huaweiobs.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/localoss.go b/internal/dao/storage/localoss.go index f2ba55ab..584fea91 100644 --- a/internal/dao/storage/localoss.go +++ b/internal/dao/storage/localoss.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/minio.go b/internal/dao/storage/minio.go index b4da9fed..3859a5b7 100644 --- a/internal/dao/storage/minio.go +++ b/internal/dao/storage/minio.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/storage.go b/internal/dao/storage/storage.go index 8e124047..fff9d13f 100644 --- a/internal/dao/storage/storage.go +++ b/internal/dao/storage/storage.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/internal.go b/internal/internal.go index 8d51c97a..e359af0d 100644 --- a/internal/internal.go +++ b/internal/internal.go @@ -1,9 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package internal import ( - "github.com/rocboss/paopao-ce/internal/migration" - "github.com/rocboss/paopao-ce/internal/routers/api" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/broker/migration" + wb "github.com/rocboss/paopao-ce/internal/servants/web/broker" + "github.com/rocboss/paopao-ce/internal/servants/web/routers/api" ) func Initialize() { @@ -11,6 +15,6 @@ func Initialize() { migration.Run() // initialize service - service.Initialize() + wb.Initialize() api.Initialize() } diff --git a/internal/middleware/admin.go b/internal/middleware/admin.go deleted file mode 100644 index f81b00ee..00000000 --- a/internal/middleware/admin.go +++ /dev/null @@ -1,25 +0,0 @@ -package middleware - -import ( - "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/pkg/app" - "github.com/rocboss/paopao-ce/pkg/errcode" -) - -func Admin() gin.HandlerFunc { - return func(c *gin.Context) { - if user, exist := c.Get("USER"); exist { - if userModel, ok := user.(*model.User); ok { - if userModel.Status == model.UserStatusNormal && userModel.IsAdmin { - c.Next() - return - } - } - } - - response := app.NewResponse(c) - response.ToErrorResponse(errcode.NoAdminPermission) - c.Abort() - } -} diff --git a/internal/middleware/jwt.go b/internal/middleware/jwt.go deleted file mode 100644 index 3fab7679..00000000 --- a/internal/middleware/jwt.go +++ /dev/null @@ -1,113 +0,0 @@ -package middleware - -import ( - "strings" - - "github.com/gin-gonic/gin" - "github.com/golang-jwt/jwt/v4" - "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/pkg/app" - "github.com/rocboss/paopao-ce/pkg/errcode" -) - -func JWT() gin.HandlerFunc { - // TODO: optimize get user from a simple service that provide fetch a user info interface. - db := conf.MustGormDB() - return func(c *gin.Context) { - var ( - token string - ecode = errcode.Success - ) - if s, exist := c.GetQuery("token"); exist { - token = s - } else { - token = c.GetHeader("Authorization") - - // 验证前端传过来的token格式,不为空,开头为Bearer - if token == "" || !strings.HasPrefix(token, "Bearer ") { - response := app.NewResponse(c) - response.ToErrorResponse(errcode.UnauthorizedTokenError) - c.Abort() - return - } - - // 验证通过,提取有效部分(除去Bearer) - token = token[7:] - } - if token == "" { - ecode = errcode.InvalidParams - } else { - claims, err := app.ParseToken(token) - if err != nil { - switch err.(*jwt.ValidationError).Errors { - case jwt.ValidationErrorExpired: - ecode = errcode.UnauthorizedTokenTimeout - default: - ecode = errcode.UnauthorizedTokenError - } - } else { - c.Set("UID", claims.UID) - c.Set("USERNAME", claims.Username) - - // 加载用户信息 - user := &model.User{ - Model: &model.Model{ - ID: claims.UID, - }, - } - user, _ = user.Get(db) - c.Set("USER", user) - - // 强制下线机制 - if (conf.JWTSetting.Issuer + ":" + user.Salt) != claims.Issuer { - ecode = errcode.UnauthorizedTokenTimeout - } - } - } - - if ecode != errcode.Success { - response := app.NewResponse(c) - response.ToErrorResponse(ecode) - c.Abort() - return - } - - c.Next() - } -} - -func JwtLoose() gin.HandlerFunc { - // TODO: optimize get user from a simple service that provide fetch a user info interface. - db := conf.MustGormDB() - return func(c *gin.Context) { - token, exist := c.GetQuery("token") - if !exist { - token = c.GetHeader("Authorization") - // 验证前端传过来的token格式,不为空,开头为Bearer - if strings.HasPrefix(token, "Bearer ") { - // 验证通过,提取有效部分(除去Bearer) - token = token[7:] - } else { - c.Next() - } - } - if len(token) > 0 { - if claims, err := app.ParseToken(token); err == nil { - c.Set("UID", claims.UID) - c.Set("USERNAME", claims.Username) - // 加载用户信息 - user := &model.User{ - Model: &model.Model{ - ID: claims.UID, - }, - } - user, err := user.Get(db) - if err == nil && (conf.JWTSetting.Issuer+":"+user.Salt) == claims.Issuer { - c.Set("USER", user) - } - } - } - c.Next() - } -} diff --git a/internal/middleware/priv.go b/internal/middleware/priv.go deleted file mode 100644 index fe31b008..00000000 --- a/internal/middleware/priv.go +++ /dev/null @@ -1,45 +0,0 @@ -package middleware - -import ( - "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/pkg/app" - "github.com/rocboss/paopao-ce/pkg/cfg" - "github.com/rocboss/paopao-ce/pkg/errcode" -) - -func Priv() gin.HandlerFunc { - if cfg.If("PhoneBind") { - return func(c *gin.Context) { - if u, exist := c.Get("USER"); exist { - if user, ok := u.(*model.User); ok { - if user.Status == model.UserStatusNormal { - if user.Phone == "" { - response := app.NewResponse(c) - response.ToErrorResponse(errcode.AccountNoPhoneBind) - c.Abort() - return - } - c.Next() - return - } - } - } - response := app.NewResponse(c) - response.ToErrorResponse(errcode.UserHasBeenBanned) - c.Abort() - } - } else { - return func(c *gin.Context) { - if u, exist := c.Get("USER"); exist { - if user, ok := u.(*model.User); ok && user.Status == model.UserStatusNormal { - c.Next() - return - } - } - response := app.NewResponse(c) - response.ToErrorResponse(errcode.UserHasBeenBanned) - c.Abort() - } - } -} diff --git a/internal/mirc/main.go b/internal/mirc/main.go index c2e47411..46de42d1 100644 --- a/internal/mirc/main.go +++ b/internal/mirc/main.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package main import ( diff --git a/internal/model/attachment.go b/internal/model/attachment.go deleted file mode 100644 index 0c748b00..00000000 --- a/internal/model/attachment.go +++ /dev/null @@ -1,27 +0,0 @@ -package model - -import "gorm.io/gorm" - -type AttachmentType int - -const ( - ATTACHMENT_TYPE_IMAGE AttachmentType = iota + 1 - ATTACHMENT_TYPE_VIDEO - ATTACHMENT_TYPE_OTHER -) - -type Attachment struct { - *Model - UserID int64 `json:"user_id"` - FileSize int64 `json:"file_size"` - ImgWidth int `json:"img_width"` - ImgHeight int `json:"img_height"` - Type AttachmentType `json:"type"` - Content string `json:"content"` -} - -func (a *Attachment) Create(db *gorm.DB) (*Attachment, error) { - err := db.Create(&a).Error - - return a, err -} diff --git a/internal/model/captcha.go b/internal/model/captcha.go deleted file mode 100644 index 210cc691..00000000 --- a/internal/model/captcha.go +++ /dev/null @@ -1,38 +0,0 @@ -package model - -import "gorm.io/gorm" - -type Captcha struct { - *Model - Phone string `json:"phone"` - Captcha string `json:"captcha"` - UseTimes int `json:"use_times"` - ExpiredOn int64 `json:"expired_on"` -} - -func (c *Captcha) Create(db *gorm.DB) (*Captcha, error) { - err := db.Create(&c).Error - - return c, err -} - -func (c *Captcha) Update(db *gorm.DB) error { - return db.Model(&Captcha{}).Where("id = ? AND is_del = ?", c.Model.ID, 0).Save(c).Error -} - -func (c *Captcha) Get(db *gorm.DB) (*Captcha, error) { - var captcha Captcha - if c.Model != nil && c.ID > 0 { - db = db.Where("id = ? AND is_del = ?", c.ID, 0) - } - if c.Phone != "" { - db = db.Where("phone = ?", c.Phone) - } - - err := db.Last(&captcha).Error - if err != nil { - return &captcha, err - } - - return &captcha, nil -} diff --git a/internal/model/comment.go b/internal/model/comment.go deleted file mode 100644 index 72494b53..00000000 --- a/internal/model/comment.go +++ /dev/null @@ -1,127 +0,0 @@ -package model - -import ( - "time" - - "gorm.io/gorm" -) - -type Comment struct { - *Model - PostID int64 `json:"post_id"` - UserID int64 `json:"user_id"` - IP string `json:"ip"` - IPLoc string `json:"ip_loc"` -} - -type CommentFormated struct { - ID int64 `json:"id"` - PostID int64 `json:"post_id"` - UserID int64 `json:"user_id"` - User *UserFormated `json:"user"` - Contents []*CommentContent `json:"contents"` - Replies []*CommentReplyFormated `json:"replies"` - IPLoc string `json:"ip_loc"` - CreatedOn int64 `json:"created_on"` - ModifiedOn int64 `json:"modified_on"` -} - -func (c *Comment) Format() *CommentFormated { - if c.Model == nil { - return &CommentFormated{} - } - return &CommentFormated{ - ID: c.Model.ID, - PostID: c.PostID, - UserID: c.UserID, - User: &UserFormated{}, - Contents: []*CommentContent{}, - Replies: []*CommentReplyFormated{}, - IPLoc: c.IPLoc, - CreatedOn: c.CreatedOn, - ModifiedOn: c.ModifiedOn, - } -} - -func (c *Comment) Get(db *gorm.DB) (*Comment, error) { - var comment Comment - if c.Model != nil && c.ID > 0 { - db = db.Where("id = ? AND is_del = ?", c.ID, 0) - } else { - return nil, gorm.ErrRecordNotFound - } - - err := db.First(&comment).Error - if err != nil { - return &comment, err - } - - return &comment, nil -} - -func (c *Comment) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*Comment, error) { - var comments []*Comment - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if c.PostID > 0 { - db = db.Where("id = ?", c.PostID) - } - - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(k, v) - } - } - - if err = db.Where("is_del = ?", 0).Find(&comments).Error; err != nil { - return nil, err - } - - return comments, nil -} - -func (c *Comment) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { - var count int64 - if c.PostID > 0 { - db = db.Where("post_id = ?", c.PostID) - } - for k, v := range *conditions { - if k != "ORDER" { - db = db.Where(k, v) - } - } - if err := db.Model(c).Count(&count).Error; err != nil { - return 0, err - } - - return count, nil -} - -func (c *Comment) Create(db *gorm.DB) (*Comment, error) { - err := db.Create(&c).Error - - return c, err -} - -func (c *Comment) Delete(db *gorm.DB) error { - return db.Model(c).Where("id = ?", c.Model.ID).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} - -func (c *Comment) CommentIdsByPostId(db *gorm.DB, postId int64) (ids []int64, err error) { - err = db.Model(c).Where("post_id = ?", postId).Select("id").Find(&ids).Error - return -} - -func (c *Comment) DeleteByPostId(db *gorm.DB, postId int64) error { - return db.Model(c).Where("post_id = ?", postId).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} diff --git a/internal/model/comment_content.go b/internal/model/comment_content.go deleted file mode 100644 index b7d42dfd..00000000 --- a/internal/model/comment_content.go +++ /dev/null @@ -1,59 +0,0 @@ -package model - -import ( - "time" - - "gorm.io/gorm" -) - -type CommentContent struct { - *Model - CommentID int64 `json:"comment_id"` - UserID int64 `json:"user_id"` - Content string `json:"content"` - Type PostContentT `json:"type"` - Sort int64 `json:"sort"` -} - -func (c *CommentContent) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*CommentContent, error) { - var comments []*CommentContent - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if c.CommentID > 0 { - db = db.Where("id = ?", c.CommentID) - } - - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(k, v) - } - } - - if err = db.Where("is_del = ?", 0).Find(&comments).Error; err != nil { - return nil, err - } - - return comments, nil -} - -func (c *CommentContent) Create(db *gorm.DB) (*CommentContent, error) { - err := db.Create(&c).Error - - return c, err -} - -func (c *CommentContent) MediaContentsByCommentId(db *gorm.DB, commentIds []int64) (contents []string, err error) { - err = db.Model(c).Where("comment_id IN ? AND type = ?", commentIds, CONTENT_TYPE_IMAGE).Select("content").Find(&contents).Error - return -} - -func (c *CommentContent) DeleteByCommentIds(db *gorm.DB, commentIds []int64) error { - return db.Model(c).Where("comment_id IN ?", commentIds).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} diff --git a/internal/model/comment_reply.go b/internal/model/comment_reply.go deleted file mode 100644 index fd22702f..00000000 --- a/internal/model/comment_reply.go +++ /dev/null @@ -1,110 +0,0 @@ -package model - -import ( - "time" - - "gorm.io/gorm" -) - -type CommentReply struct { - *Model - CommentID int64 `json:"comment_id"` - UserID int64 `json:"user_id"` - AtUserID int64 `json:"at_user_id"` - Content string `json:"content"` - IP string `json:"ip"` - IPLoc string `json:"ip_loc"` -} - -type CommentReplyFormated struct { - ID int64 `json:"id"` - CommentID int64 `json:"comment_id"` - UserID int64 `json:"user_id"` - User *UserFormated `json:"user"` - AtUserID int64 `json:"at_user_id"` - AtUser *UserFormated `json:"at_user"` - Content string `json:"content"` - IPLoc string `json:"ip_loc"` - CreatedOn int64 `json:"created_on"` - ModifiedOn int64 `json:"modified_on"` -} - -func (c *CommentReply) Format() *CommentReplyFormated { - if c.Model == nil { - return &CommentReplyFormated{} - } - - return &CommentReplyFormated{ - ID: c.ID, - CommentID: c.CommentID, - UserID: c.UserID, - User: &UserFormated{}, - AtUserID: c.AtUserID, - AtUser: &UserFormated{}, - Content: c.Content, - IPLoc: c.IPLoc, - CreatedOn: c.CreatedOn, - ModifiedOn: c.ModifiedOn, - } -} - -func (c *CommentReply) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*CommentReply, error) { - var comments []*CommentReply - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if c.CommentID > 0 { - db = db.Where("id = ?", c.CommentID) - } - - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(k, v) - } - } - - if err = db.Where("is_del = ?", 0).Find(&comments).Error; err != nil { - return nil, err - } - - return comments, nil -} - -func (c *CommentReply) Create(db *gorm.DB) (*CommentReply, error) { - err := db.Create(&c).Error - - return c, err -} - -func (c *CommentReply) Get(db *gorm.DB) (*CommentReply, error) { - var reply CommentReply - if c.Model != nil && c.ID > 0 { - db = db.Where("id = ? AND is_del = ?", c.ID, 0) - } else { - return nil, gorm.ErrRecordNotFound - } - - err := db.First(&reply).Error - if err != nil { - return &reply, err - } - - return &reply, nil -} - -func (c *CommentReply) Delete(db *gorm.DB) error { - return db.Model(&CommentReply{}).Where("id = ? AND is_del = ?", c.Model.ID, 0).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} - -func (c *CommentReply) DeleteByCommentIds(db *gorm.DB, commentIds []int64) error { - return db.Model(c).Where("comment_id IN ?", commentIds).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} diff --git a/internal/model/contact.go b/internal/model/contact.go deleted file mode 100644 index 14049f77..00000000 --- a/internal/model/contact.go +++ /dev/null @@ -1,119 +0,0 @@ -package model - -import ( - "github.com/sirupsen/logrus" - "gorm.io/gorm" -) - -const ( - ContactStatusRequesting int8 = iota + 1 - ContactStatusAgree - ContactStatusReject - ContactStatusDeleted -) - -type Contact struct { - *Model - User *User `json:"-" gorm:"foreignKey:ID;references:FriendId"` - UserId int64 `json:"user_id"` - FriendId int64 `json:"friend_id"` - GroupId int64 `json:"group_id"` - Remark string `json:"remark"` - Status int8 `json:"status"` // 1请求好友, 2已同意好友, 3已拒绝好友, 4已删除好友 - IsTop int8 `json:"is_top"` - IsBlack int8 `json:"is_black"` - NoticeEnable int8 `json:"notice_enable"` -} - -func (c *Contact) FetchUser(db *gorm.DB) (*Contact, error) { - var contact Contact - err := db.Omit("User").Unscoped().Where("user_id = ? AND friend_id = ?", c.UserId, c.FriendId).First(&contact).Error - if err != nil { - logrus.Debugf("Contact.FetchUser fetch user error:%s", err) - return nil, err - } - return &contact, nil -} - -func (c *Contact) GetByUserFriend(db *gorm.DB) (*Contact, error) { - var contact Contact - err := db.Omit("User").Where("user_id = ? AND friend_id = ?", c.UserId, c.FriendId).First(&contact).Error - if err != nil { - return nil, err - } - return &contact, nil -} - -func (c *Contact) FetchByUserFriendAll(db *gorm.DB) ([]*Contact, error) { - var contacts []*Contact - if err := db.Omit("User"). - Where("(user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)", - c.UserId, c.FriendId, c.FriendId, c.UserId). - Find(&contacts).Error; err != nil { - return nil, err - } - return contacts, nil -} - -func (c *Contact) List(db *gorm.DB, conditions ConditionsT, offset, limit int) ([]*Contact, error) { - var contacts []*Contact - var err error - tn := db.NamingStrategy.TableName("Contact") + "." - - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - for k, v := range conditions { - if k != "ORDER" { - db = db.Where(tn+k, v) - } - } - - db.Joins("User").Order("`User`.`nickname` ASC") - if err = db.Find(&contacts).Error; err != nil { - return nil, err - } - return contacts, nil -} - -func (c *Contact) BeFriendIds(db *gorm.DB) (ids []int64, err error) { - if err = db.Model(c).Omit("User").Select("user_id").Where("friend_id = ? AND status = ?", c.FriendId, ContactStatusAgree).Find(&ids).Error; err != nil { - return nil, err - } - return -} - -func (c *Contact) MyFriendIds(db *gorm.DB) (ids []string, err error) { - if err = db.Model(c).Omit("User").Select("friend_id").Where("user_id = ? AND status = ?", c.UserId, ContactStatusAgree).Find(&ids).Error; err != nil { - return nil, err - } - return -} - -func (m *Contact) Count(db *gorm.DB, conditions ConditionsT) (int64, error) { - var count int64 - - for k, v := range conditions { - if k != "ORDER" { - db = db.Where(k, v) - } - } - if err := db.Model(m).Omit("User").Count(&count).Error; err != nil { - return 0, err - } - - return count, nil -} - -func (c *Contact) Create(db *gorm.DB) (*Contact, error) { - err := db.Omit("User").Create(&c).Error - return c, err -} - -func (c *Contact) Update(db *gorm.DB) error { - return db.Model(&Contact{}).Omit("User").Where("id = ?", c.Model.ID).Save(c).Error -} - -func (c *Contact) UpdateInUnscoped(db *gorm.DB) error { - return db.Unscoped().Omit("User").Save(c).Error -} diff --git a/internal/model/message.go b/internal/model/message.go deleted file mode 100644 index c1277cf7..00000000 --- a/internal/model/message.go +++ /dev/null @@ -1,148 +0,0 @@ -package model - -import "gorm.io/gorm" - -type MessageT int8 - -const ( - MsgTypePost MessageT = iota + 1 - MsgtypeComment - MsgTypeReply - MsgTypeWhisper - MsgTypeRequestingFriend - MsgTypeSystem MessageT = 99 - - MsgStatusUnread = 0 - MsgStatusReaded = 1 -) - -type Message struct { - *Model - SenderUserID int64 `json:"sender_user_id"` - ReceiverUserID int64 `json:"receiver_user_id"` - Type MessageT `json:"type"` - Brief string `json:"brief"` - Content string `json:"content"` - PostID int64 `json:"post_id"` - CommentID int64 `json:"comment_id"` - ReplyID int64 `json:"reply_id"` - IsRead int8 `json:"is_read"` -} - -type MessageFormated struct { - ID int64 `json:"id"` - SenderUserID int64 `json:"sender_user_id"` - SenderUser *UserFormated `json:"sender_user"` - ReceiverUserID int64 `json:"receiver_user_id"` - Type MessageT `json:"type"` - Brief string `json:"brief"` - Content string `json:"content"` - PostID int64 `json:"post_id"` - Post *PostFormated `json:"post"` - CommentID int64 `json:"comment_id"` - Comment *Comment `json:"comment"` - ReplyID int64 `json:"reply_id"` - Reply *CommentReply `json:"reply"` - IsRead int8 `json:"is_read"` - CreatedOn int64 `json:"created_on"` - ModifiedOn int64 `json:"modified_on"` -} - -func (m *Message) Format() *MessageFormated { - if m.Model == nil || m.Model.ID == 0 { - return nil - } - mf := &MessageFormated{ - ID: m.ID, - SenderUserID: m.SenderUserID, - SenderUser: &UserFormated{}, - ReceiverUserID: m.ReceiverUserID, - Type: m.Type, - Brief: m.Brief, - Content: m.Content, - PostID: m.PostID, - Post: &PostFormated{}, - CommentID: m.CommentID, - Comment: &Comment{}, - ReplyID: m.ReplyID, - Reply: &CommentReply{}, - IsRead: m.IsRead, - CreatedOn: m.CreatedOn, - ModifiedOn: m.ModifiedOn, - } - - return mf -} - -func (m *Message) Create(db *gorm.DB) (*Message, error) { - err := db.Create(&m).Error - - return m, err -} - -func (m *Message) Update(db *gorm.DB) error { - return db.Model(&Message{}).Where("id = ? AND is_del = ?", m.Model.ID, 0).Save(m).Error -} - -func (m *Message) Get(db *gorm.DB) (*Message, error) { - var message Message - if m.Model != nil && m.ID > 0 { - db = db.Where("id = ? AND is_del = ?", m.ID, 0) - } - if m.ReceiverUserID > 0 { - db = db.Where("receiver_user_id = ?", m.ReceiverUserID) - } - if err := db.First(&message).Error; err != nil { - return nil, err - } - return &message, nil -} - -func (m *Message) FetchBy(db *gorm.DB, predicates Predicates) ([]*Message, error) { - var messages []*Message - for k, v := range predicates { - db = db.Where(k, v...) - } - db = db.Where("is_del = 0") - if err := db.Find(&messages).Error; err != nil { - return nil, err - } - return messages, nil -} - -func (c *Message) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*Message, error) { - var messages []*Message - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(k, v) - } - } - - if err = db.Where("is_del = ?", 0).Find(&messages).Error; err != nil { - return nil, err - } - - return messages, nil -} - -func (m *Message) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { - var count int64 - - for k, v := range *conditions { - if k != "ORDER" { - db = db.Where(k, v) - } - } - if err := db.Model(m).Count(&count).Error; err != nil { - return 0, err - } - - return count, nil -} diff --git a/internal/model/post.go b/internal/model/post.go deleted file mode 100644 index ae428a9a..00000000 --- a/internal/model/post.go +++ /dev/null @@ -1,208 +0,0 @@ -package model - -import ( - "strings" - "time" - - "gorm.io/gorm" -) - -// PostVisibleT 可访问类型,0公开,1私密,2好友 -type PostVisibleT uint8 - -const ( - PostVisitPublic PostVisibleT = iota - PostVisitPrivate - PostVisitFriend - PostVisitInvalid -) - -type Post struct { - *Model - UserID int64 `json:"user_id"` - CommentCount int64 `json:"comment_count"` - CollectionCount int64 `json:"collection_count"` - UpvoteCount int64 `json:"upvote_count"` - Visibility PostVisibleT `json:"visibility"` - IsTop int `json:"is_top"` - IsEssence int `json:"is_essence"` - IsLock int `json:"is_lock"` - LatestRepliedOn int64 `json:"latest_replied_on"` - Tags string `json:"tags"` - AttachmentPrice int64 `json:"attachment_price"` - IP string `json:"ip"` - IPLoc string `json:"ip_loc"` -} - -type PostFormated struct { - ID int64 `json:"id"` - UserID int64 `json:"user_id"` - User *UserFormated `json:"user"` - Contents []*PostContentFormated `json:"contents"` - CommentCount int64 `json:"comment_count"` - CollectionCount int64 `json:"collection_count"` - UpvoteCount int64 `json:"upvote_count"` - Visibility PostVisibleT `json:"visibility"` - IsTop int `json:"is_top"` - IsEssence int `json:"is_essence"` - IsLock int `json:"is_lock"` - LatestRepliedOn int64 `json:"latest_replied_on"` - CreatedOn int64 `json:"created_on"` - ModifiedOn int64 `json:"modified_on"` - Tags map[string]int8 `json:"tags"` - AttachmentPrice int64 `json:"attachment_price"` - IPLoc string `json:"ip_loc"` -} - -func (p *Post) Format() *PostFormated { - if p.Model != nil { - tagsMap := map[string]int8{} - for _, tag := range strings.Split(p.Tags, ",") { - tagsMap[tag] = 1 - } - return &PostFormated{ - ID: p.ID, - UserID: p.UserID, - User: &UserFormated{}, - Contents: []*PostContentFormated{}, - CommentCount: p.CommentCount, - CollectionCount: p.CollectionCount, - UpvoteCount: p.UpvoteCount, - Visibility: p.Visibility, - IsTop: p.IsTop, - IsEssence: p.IsEssence, - IsLock: p.IsLock, - LatestRepliedOn: p.LatestRepliedOn, - CreatedOn: p.CreatedOn, - ModifiedOn: p.ModifiedOn, - AttachmentPrice: p.AttachmentPrice, - Tags: tagsMap, - IPLoc: p.IPLoc, - } - } - - return nil -} - -func (p *Post) Create(db *gorm.DB) (*Post, error) { - err := db.Create(&p).Error - - return p, err -} - -func (s *Post) Delete(db *gorm.DB) error { - return db.Model(s).Where("id = ?", s.Model.ID).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} - -func (p *Post) Get(db *gorm.DB) (*Post, error) { - var post Post - if p.Model != nil && p.ID > 0 { - db = db.Where("id = ? AND is_del = ?", p.ID, 0) - } else { - return nil, gorm.ErrRecordNotFound - } - - err := db.First(&post).Error - if err != nil { - return &post, err - } - - return &post, nil -} - -func (p *Post) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*Post, error) { - var posts []*Post - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if p.UserID > 0 { - db = db.Where("user_id = ?", p.UserID) - } - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(k, v) - } - } - - if err = db.Where("is_del = ?", 0).Find(&posts).Error; err != nil { - return nil, err - } - - return posts, nil -} - -func (p *Post) Fetch(db *gorm.DB, predicates Predicates, offset, limit int) ([]*Post, error) { - var posts []*Post - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if p.UserID > 0 { - db = db.Where("user_id = ?", p.UserID) - } - for query, args := range predicates { - if query == "ORDER" { - db = db.Order(args[0]) - } else { - db = db.Where(query, args...) - } - } - - if err = db.Where("is_del = ?", 0).Find(&posts).Error; err != nil { - return nil, err - } - - return posts, nil -} - -func (p *Post) CountBy(db *gorm.DB, predicates Predicates) (count int64, err error) { - for query, args := range predicates { - if query != "ORDER" { - db = db.Where(query, args...) - } - } - err = db.Model(p).Count(&count).Error - return -} - -func (p *Post) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { - var count int64 - if p.UserID > 0 { - db = db.Where("user_id = ?", p.UserID) - } - for k, v := range *conditions { - if k != "ORDER" { - db = db.Where(k, v) - } - } - if err := db.Model(p).Count(&count).Error; err != nil { - return 0, err - } - - return count, nil -} - -func (p *Post) Update(db *gorm.DB) error { - return db.Model(&Post{}).Where("id = ? AND is_del = ?", p.Model.ID, 0).Save(p).Error -} - -func (p PostVisibleT) String() string { - switch p { - case PostVisitPublic: - return "public" - case PostVisitPrivate: - return "private" - case PostVisitFriend: - return "friend" - case PostVisitInvalid: - return "invalid" - default: - return "unknow" - } -} diff --git a/internal/model/post_attachment_bill.go b/internal/model/post_attachment_bill.go deleted file mode 100644 index 8ee7aae6..00000000 --- a/internal/model/post_attachment_bill.go +++ /dev/null @@ -1,36 +0,0 @@ -package model - -import "gorm.io/gorm" - -type PostAttachmentBill struct { - *Model - PostID int64 `json:"post_id"` - UserID int64 `json:"user_id"` - PaidAmount int64 `json:"paid_amount"` -} - -func (p *PostAttachmentBill) Get(db *gorm.DB) (*PostAttachmentBill, error) { - var pas PostAttachmentBill - if p.Model != nil && p.ID > 0 { - db = db.Where("id = ? AND is_del = ?", p.ID, 0) - } - if p.PostID > 0 { - db = db.Where("post_id = ?", p.PostID) - } - if p.UserID > 0 { - db = db.Where("user_id = ?", p.UserID) - } - - err := db.First(&pas).Error - if err != nil { - return &pas, err - } - - return &pas, nil -} - -func (p *PostAttachmentBill) Create(db *gorm.DB) (*PostAttachmentBill, error) { - err := db.Create(&p).Error - - return p, err -} diff --git a/internal/model/post_collection.go b/internal/model/post_collection.go deleted file mode 100644 index 0ea0cb29..00000000 --- a/internal/model/post_collection.go +++ /dev/null @@ -1,102 +0,0 @@ -package model - -import ( - "time" - - "gorm.io/gorm" -) - -type PostCollection struct { - *Model - Post *Post `json:"-"` - PostID int64 `json:"post_id"` - UserID int64 `json:"user_id"` -} - -func (p *PostCollection) Get(db *gorm.DB) (*PostCollection, error) { - var star PostCollection - tn := db.NamingStrategy.TableName("PostCollection") + "." - - if p.Model != nil && p.ID > 0 { - db = db.Where(tn+"id = ? AND "+tn+"is_del = ?", p.ID, 0) - } - if p.PostID > 0 { - db = db.Where(tn+"post_id = ?", p.PostID) - } - if p.UserID > 0 { - db = db.Where(tn+"user_id = ?", p.UserID) - } - - db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC") - err := db.First(&star).Error - if err != nil { - return &star, err - } - - return &star, nil -} - -func (p *PostCollection) Create(db *gorm.DB) (*PostCollection, error) { - err := db.Omit("Post").Create(&p).Error - - return p, err -} - -func (p *PostCollection) Delete(db *gorm.DB) error { - return db.Model(&PostCollection{}).Omit("Post").Where("id = ? AND is_del = ?", p.Model.ID, 0).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} - -func (p *PostCollection) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostCollection, error) { - var collections []*PostCollection - var err error - tn := db.NamingStrategy.TableName("PostCollection") + "." - - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if p.UserID > 0 { - db = db.Where(tn+"user_id = ?", p.UserID) - } - - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(tn+k, v) - } - } - - db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC") - if err = db.Where(tn+"is_del = ?", 0).Find(&collections).Error; err != nil { - return nil, err - } - - return collections, nil -} - -func (p *PostCollection) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { - var count int64 - tn := db.NamingStrategy.TableName("PostCollection") + "." - - if p.PostID > 0 { - db = db.Where(tn+"post_id = ?", p.PostID) - } - if p.UserID > 0 { - db = db.Where(tn+"user_id = ?", p.UserID) - } - for k, v := range *conditions { - if k != "ORDER" { - db = db.Where(tn+k, v) - } - } - - db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate) - if err := db.Model(p).Count(&count).Error; err != nil { - return 0, err - } - - return count, nil -} diff --git a/internal/model/post_content.go b/internal/model/post_content.go deleted file mode 100644 index b301de62..00000000 --- a/internal/model/post_content.go +++ /dev/null @@ -1,121 +0,0 @@ -package model - -import ( - "time" - - "gorm.io/gorm" -) - -// 类型,1标题,2文字段落,3图片地址,4视频地址,5语音地址,6链接地址,7附件资源 - -type PostContentT int - -const ( - CONTENT_TYPE_TITLE PostContentT = iota + 1 - CONTENT_TYPE_TEXT - CONTENT_TYPE_IMAGE - CONTENT_TYPE_VIDEO - CONTENT_TYPE_AUDIO - CONTENT_TYPE_LINK - CONTENT_TYPE_ATTACHMENT - CONTENT_TYPE_CHARGE_ATTACHMENT -) - -var ( - mediaContentType = []PostContentT{ - CONTENT_TYPE_IMAGE, - CONTENT_TYPE_VIDEO, - CONTENT_TYPE_AUDIO, - CONTENT_TYPE_ATTACHMENT, - CONTENT_TYPE_CHARGE_ATTACHMENT, - } -) - -type PostContent struct { - *Model - PostID int64 `json:"post_id"` - UserID int64 `json:"user_id"` - Content string `json:"content"` - Type PostContentT `json:"type"` - Sort int64 `json:"sort"` -} - -type PostContentFormated struct { - ID int64 `json:"id"` - PostID int64 `json:"post_id"` - Content string `json:"content"` - Type PostContentT `json:"type"` - Sort int64 `json:"sort"` -} - -func (p *PostContent) DeleteByPostId(db *gorm.DB, postId int64) error { - return db.Model(p).Where("post_id = ?", postId).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} - -func (p *PostContent) MediaContentsByPostId(db *gorm.DB, postId int64) (contents []string, err error) { - err = db.Model(p).Where("post_id = ? AND type IN ?", postId, mediaContentType).Select("content").Find(&contents).Error - return -} - -func (p *PostContent) Create(db *gorm.DB) (*PostContent, error) { - err := db.Create(&p).Error - - return p, err -} - -func (p *PostContent) Format() *PostContentFormated { - if p.Model == nil { - return nil - } - return &PostContentFormated{ - ID: p.ID, - PostID: p.PostID, - Content: p.Content, - Type: p.Type, - Sort: p.Sort, - } -} - -func (p *PostContent) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostContent, error) { - var contents []*PostContent - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if p.PostID > 0 { - db = db.Where("id = ?", p.PostID) - } - - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(k, v) - } - } - - if err = db.Where("is_del = ?", 0).Find(&contents).Error; err != nil { - return nil, err - } - - return contents, nil -} - -func (p *PostContent) Get(db *gorm.DB) (*PostContent, error) { - var content PostContent - if p.Model != nil && p.ID > 0 { - db = db.Where("id = ? AND is_del = ?", p.ID, 0) - } else { - return nil, gorm.ErrRecordNotFound - } - - err := db.First(&content).Error - if err != nil { - return &content, err - } - - return &content, nil -} diff --git a/internal/model/post_star.go b/internal/model/post_star.go deleted file mode 100644 index 3846a9c2..00000000 --- a/internal/model/post_star.go +++ /dev/null @@ -1,98 +0,0 @@ -package model - -import ( - "time" - - "gorm.io/gorm" -) - -type PostStar struct { - *Model - Post *Post `json:"-"` - PostID int64 `json:"post_id"` - UserID int64 `json:"user_id"` -} - -func (p *PostStar) Get(db *gorm.DB) (*PostStar, error) { - var star PostStar - tn := db.NamingStrategy.TableName("PostStar") + "." - - if p.Model != nil && p.ID > 0 { - db = db.Where(tn+"id = ? AND "+tn+"is_del = ?", p.ID, 0) - } - if p.PostID > 0 { - db = db.Where(tn+"post_id = ?", p.PostID) - } - if p.UserID > 0 { - db = db.Where(tn+"user_id = ?", p.UserID) - } - - db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC") - if err := db.First(&star).Error; err != nil { - return nil, err - } - return &star, nil -} - -func (p *PostStar) Create(db *gorm.DB) (*PostStar, error) { - err := db.Omit("Post").Create(&p).Error - - return p, err -} - -func (p *PostStar) Delete(db *gorm.DB) error { - return db.Model(&PostStar{}).Omit("Post").Where("id = ? AND is_del = ?", p.Model.ID, 0).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} - -func (p *PostStar) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostStar, error) { - var stars []*PostStar - var err error - tn := db.NamingStrategy.TableName("PostStar") + "." - - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if p.UserID > 0 { - db = db.Where(tn+"user_id = ?", p.UserID) - } - - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(tn+k, v) - } - } - - db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC") - if err = db.Find(&stars).Error; err != nil { - return nil, err - } - return stars, nil -} - -func (p *PostStar) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { - var count int64 - tn := db.NamingStrategy.TableName("PostStar") + "." - - if p.PostID > 0 { - db = db.Where(tn+"post_id = ?", p.PostID) - } - if p.UserID > 0 { - db = db.Where(tn+"user_id = ?", p.UserID) - } - for k, v := range *conditions { - if k != "ORDER" { - db = db.Where(tn+k, v) - } - } - - db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate) - if err := db.Model(p).Count(&count).Error; err != nil { - return 0, err - } - return count, nil -} diff --git a/internal/model/rest/contacts.go b/internal/model/rest/contacts.go deleted file mode 100644 index bbf31e42..00000000 --- a/internal/model/rest/contacts.go +++ /dev/null @@ -1,31 +0,0 @@ -package rest - -type RequestingFriendReq struct { - UserId int64 `json:"user_id" binding:"required"` - Greetings string `json:"greetings" binding:"required"` -} - -type AddFriendReq struct { - UserId int64 `json:"user_id" binding:"required"` -} - -type RejectFriendReq struct { - UserId int64 `json:"user_id" binding:"required"` -} - -type DeleteFriendReq struct { - UserId int64 `json:"user_id"` -} - -type ContactItem struct { - UserId int64 `json:"user_id"` - UserName string `json:"username"` - Nickname string `json:"nickname"` - Avatar string `json:"avatar"` - Phone string `json:"phone"` -} - -type ContactsResp struct { - Contacts []ContactItem `json:"contacts"` - Total int64 `json:"total"` -} diff --git a/internal/model/rest/tweets.go b/internal/model/rest/tweets.go deleted file mode 100644 index de85e179..00000000 --- a/internal/model/rest/tweets.go +++ /dev/null @@ -1,8 +0,0 @@ -package rest - -import "github.com/rocboss/paopao-ce/internal/model" - -type IndexTweetsResp struct { - Tweets []*model.PostFormated - Total int64 -} diff --git a/internal/model/rest/user.go b/internal/model/rest/user.go deleted file mode 100644 index 60ff467d..00000000 --- a/internal/model/rest/user.go +++ /dev/null @@ -1,11 +0,0 @@ -package rest - -type UserProfileResp struct { - ID int64 `json:"id"` - Nickname string `json:"nickname"` - Username string `json:"username"` - Status int `json:"status"` - Avatar string `json:"avatar"` - IsAdmin bool `json:"is_admin"` - IsFriend bool `json:"is_friend"` -} diff --git a/internal/model/tag.go b/internal/model/tag.go deleted file mode 100644 index 34bb64f9..00000000 --- a/internal/model/tag.go +++ /dev/null @@ -1,97 +0,0 @@ -package model - -import ( - "time" - - "gorm.io/gorm" -) - -type Tag struct { - *Model - UserID int64 `json:"user_id"` - Tag string `json:"tag"` - QuoteNum int64 `json:"quote_num"` -} -type TagFormated struct { - ID int64 `json:"id"` - UserID int64 `json:"user_id"` - User *UserFormated `json:"user"` - Tag string `json:"tag"` - QuoteNum int64 `json:"quote_num"` -} - -func (t *Tag) Format() *TagFormated { - if t.Model == nil { - return &TagFormated{} - } - - return &TagFormated{ - ID: t.ID, - UserID: t.UserID, - User: &UserFormated{}, - Tag: t.Tag, - QuoteNum: t.QuoteNum, - } -} - -func (t *Tag) Get(db *gorm.DB) (*Tag, error) { - var tag Tag - if t.Model != nil && t.Model.ID > 0 { - db = db.Where("id= ? AND is_del = ?", t.Model.ID, 0) - } else { - db = db.Where("tag = ? AND is_del = ?", t.Tag, 0) - } - - err := db.First(&tag).Error - if err != nil { - return &tag, err - } - - return &tag, nil -} - -func (t *Tag) Create(db *gorm.DB) (*Tag, error) { - err := db.Create(&t).Error - - return t, err -} - -func (t *Tag) Update(db *gorm.DB) error { - return db.Model(&Tag{}).Where("id = ? AND is_del = ?", t.Model.ID, 0).Save(t).Error -} - -func (t *Tag) Delete(db *gorm.DB) error { - return db.Model(t).Where("id = ?", t.Model.ID).Updates(map[string]any{ - "deleted_on": time.Now().Unix(), - "is_del": 1, - }).Error -} - -func (t *Tag) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*Tag, error) { - var tags []*Tag - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if t.UserID > 0 { - db = db.Where("user_id = ?", t.UserID) - } - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(k, v) - } - } - - if err = db.Where("is_del = ?", 0).Find(&tags).Error; err != nil { - return nil, err - } - - return tags, nil -} - -func (t *Tag) TagsFrom(db *gorm.DB, tags []string) (res []*Tag, err error) { - err = db.Where("tag IN ?", tags).Find(&res).Error - return -} diff --git a/internal/model/user.go b/internal/model/user.go deleted file mode 100644 index 39c52d79..00000000 --- a/internal/model/user.go +++ /dev/null @@ -1,94 +0,0 @@ -package model - -import "gorm.io/gorm" - -const ( - UserStatusNormal int = iota + 1 - UserStatusClosed -) - -type User struct { - *Model - Nickname string `json:"nickname"` - Username string `json:"username"` - Phone string `json:"phone"` - Password string `json:"password"` - Salt string `json:"salt"` - Status int `json:"status"` - Avatar string `json:"avatar"` - Balance int64 `json:"balance"` - IsAdmin bool `json:"is_admin"` -} - -type UserFormated struct { - ID int64 `json:"id"` - Nickname string `json:"nickname"` - Username string `json:"username"` - Status int `json:"status"` - Avatar string `json:"avatar"` - IsAdmin bool `json:"is_admin"` -} - -func (u *User) Format() *UserFormated { - if u.Model != nil { - return &UserFormated{ - ID: u.ID, - Nickname: u.Nickname, - Username: u.Username, - Status: u.Status, - Avatar: u.Avatar, - IsAdmin: u.IsAdmin, - } - } - - return nil -} - -func (u *User) Get(db *gorm.DB) (*User, error) { - var user User - if u.Model != nil && u.Model.ID > 0 { - db = db.Where("id= ? AND is_del = ?", u.Model.ID, 0) - } else if u.Phone != "" { - db = db.Where("phone = ? AND is_del = ?", u.Phone, 0) - } else { - db = db.Where("username = ? AND is_del = ?", u.Username, 0) - } - - err := db.First(&user).Error - if err != nil { - return &user, err - } - - return &user, nil -} - -func (u *User) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*User, error) { - var users []*User - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(k, v) - } - } - - if err = db.Where("is_del = ?", 0).Find(&users).Error; err != nil { - return nil, err - } - - return users, nil -} - -func (u *User) Create(db *gorm.DB) (*User, error) { - err := db.Create(&u).Error - - return u, err -} - -func (u *User) Update(db *gorm.DB) error { - return db.Model(&User{}).Where("id = ? AND is_del = ?", u.Model.ID, 0).Save(u).Error -} diff --git a/internal/model/wallet_recharge.go b/internal/model/wallet_recharge.go deleted file mode 100644 index bfb3bc6f..00000000 --- a/internal/model/wallet_recharge.go +++ /dev/null @@ -1,34 +0,0 @@ -package model - -import "gorm.io/gorm" - -type WalletRecharge struct { - *Model - UserID int64 `json:"user_id"` - Amount int64 `json:"amount"` - TradeNo string `json:"trade_no"` - TradeStatus string `json:"trade_status"` -} - -func (p *WalletRecharge) Get(db *gorm.DB) (*WalletRecharge, error) { - var pas WalletRecharge - if p.Model != nil && p.ID > 0 { - db = db.Where("id = ? AND is_del = ?", p.ID, 0) - } - if p.UserID > 0 { - db = db.Where("user_id = ?", p.UserID) - } - - err := db.First(&pas).Error - if err != nil { - return &pas, err - } - - return &pas, nil -} - -func (p *WalletRecharge) Create(db *gorm.DB) (*WalletRecharge, error) { - err := db.Create(&p).Error - - return p, err -} diff --git a/internal/model/wallet_statement.go b/internal/model/wallet_statement.go deleted file mode 100644 index 163e2430..00000000 --- a/internal/model/wallet_statement.go +++ /dev/null @@ -1,83 +0,0 @@ -package model - -import "gorm.io/gorm" - -type WalletStatement struct { - *Model - UserID int64 `json:"user_id"` - ChangeAmount int64 `json:"change_amount"` - BalanceSnapshot int64 `json:"balance_snapshot"` - Reason string `json:"reason"` - PostID int64 `json:"post_id"` -} - -func (w *WalletStatement) Get(db *gorm.DB) (*WalletStatement, error) { - var ws WalletStatement - if w.Model != nil && w.ID > 0 { - db = db.Where("id = ? AND is_del = ?", w.ID, 0) - } - if w.PostID > 0 { - db = db.Where("post_id = ?", w.PostID) - } - if w.UserID > 0 { - db = db.Where("user_id = ?", w.UserID) - } - - err := db.First(&ws).Error - if err != nil { - return &ws, err - } - - return &ws, nil -} - -func (w *WalletStatement) Create(db *gorm.DB) (*WalletStatement, error) { - err := db.Create(&w).Error - - return w, err -} - -func (w *WalletStatement) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*WalletStatement, error) { - var records []*WalletStatement - var err error - if offset >= 0 && limit > 0 { - db = db.Offset(offset).Limit(limit) - } - if w.UserID > 0 { - db = db.Where("user_id = ?", w.UserID) - } - - for k, v := range *conditions { - if k == "ORDER" { - db = db.Order(v) - } else { - db = db.Where(k, v) - } - } - - if err = db.Where("is_del = ?", 0).Find(&records).Error; err != nil { - return nil, err - } - - return records, nil -} - -func (w *WalletStatement) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { - var count int64 - if w.PostID > 0 { - db = db.Where("post_id = ?", w.PostID) - } - if w.UserID > 0 { - db = db.Where("user_id = ?", w.UserID) - } - for k, v := range *conditions { - if k != "ORDER" { - db = db.Where(k, v) - } - } - if err := db.Model(w).Count(&count).Error; err != nil { - return 0, err - } - - return count, nil -} diff --git a/internal/proto/gen.go b/internal/proto/gen.go new file mode 100644 index 00000000..adb9c8db --- /dev/null +++ b/internal/proto/gen.go @@ -0,0 +1,5 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package proto diff --git a/internal/proto/tweets.proto b/internal/proto/tweets.proto new file mode 100644 index 00000000..1fcc9364 --- /dev/null +++ b/internal/proto/tweets.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; + +package paopao; + +option go_package = "proto"; + +message Tag { + string name = 1; + int32 type = 2; +} diff --git a/internal/servants/core/core.go b/internal/servants/base/base.go similarity index 81% rename from internal/servants/core/core.go rename to internal/servants/base/base.go index 6dad41e7..6c204e7e 100644 --- a/internal/servants/core/core.go +++ b/internal/servants/base/base.go @@ -1,4 +1,8 @@ -package core +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package base import ( "net/http" @@ -6,7 +10,7 @@ import ( "github.com/alimy/mir/v3" "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/xerror" ) @@ -22,9 +26,9 @@ type BaseRender struct { // TODO } -func (BaseServant) userFrom(c *gin.Context) (*model.User, bool) { +func (BaseServant) userFrom(c *gin.Context) (*core.User, bool) { if u, exists := c.Get("USER"); exists { - user, ok := u.(*model.User) + user, ok := u.(*core.User) return user, ok } return nil, false diff --git a/internal/servants/chain/admin.go b/internal/servants/chain/admin.go index 846d6b68..35a0fbc3 100644 --- a/internal/servants/chain/admin.go +++ b/internal/servants/chain/admin.go @@ -1,8 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package chain import ( "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/errcode" ) @@ -10,8 +14,8 @@ import ( func Admin() gin.HandlerFunc { return func(c *gin.Context) { if user, exist := c.Get("USER"); exist { - if userModel, ok := user.(*model.User); ok { - if userModel.Status == model.UserStatusNormal && userModel.IsAdmin { + if userModel, ok := user.(*core.User); ok { + if userModel.Status == core.UserStatusNormal && userModel.IsAdmin { c.Next() return } diff --git a/internal/servants/chain/jwt.go b/internal/servants/chain/jwt.go index 75a4c9ad..a0396630 100644 --- a/internal/servants/chain/jwt.go +++ b/internal/servants/chain/jwt.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package chain import ( @@ -6,7 +10,7 @@ import ( "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v4" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/errcode" ) @@ -51,8 +55,8 @@ func JWT() gin.HandlerFunc { c.Set("USERNAME", claims.Username) // 加载用户信息 - user := &model.User{ - Model: &model.Model{ + user := &core.User{ + Model: &core.Model{ ID: claims.UID, }, } @@ -97,8 +101,8 @@ func JwtLoose() gin.HandlerFunc { c.Set("UID", claims.UID) c.Set("USERNAME", claims.Username) // 加载用户信息 - user := &model.User{ - Model: &model.Model{ + user := &core.User{ + Model: &core.Model{ ID: claims.UID, }, } diff --git a/internal/servants/chain/priv.go b/internal/servants/chain/priv.go index a60ebe41..f03c14b7 100644 --- a/internal/servants/chain/priv.go +++ b/internal/servants/chain/priv.go @@ -1,8 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package chain import ( "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/rocboss/paopao-ce/pkg/errcode" @@ -12,8 +16,8 @@ func Priv() gin.HandlerFunc { if cfg.If("PhoneBind") { return func(c *gin.Context) { if u, exist := c.Get("USER"); exist { - if user, ok := u.(*model.User); ok { - if user.Status == model.UserStatusNormal { + if user, ok := u.(*core.User); ok { + if user.Status == core.UserStatusNormal { if user.Phone == "" { response := app.NewResponse(c) response.ToErrorResponse(errcode.AccountNoPhoneBind) @@ -32,7 +36,7 @@ func Priv() gin.HandlerFunc { } else { return func(c *gin.Context) { if u, exist := c.Get("USER"); exist { - if user, ok := u.(*model.User); ok && user.Status == model.UserStatusNormal { + if user, ok := u.(*core.User); ok && user.Status == core.UserStatusNormal { c.Next() return } diff --git a/internal/servants/docs/docs.go b/internal/servants/docs/docs.go index ef062a47..7b6c9d36 100644 --- a/internal/servants/docs/docs.go +++ b/internal/servants/docs/docs.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !docs // +build !docs diff --git a/internal/servants/docs/docs_embed.go b/internal/servants/docs/docs_embed.go index da457e50..653e1c07 100644 --- a/internal/servants/docs/docs_embed.go +++ b/internal/servants/docs/docs_embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build docs // +build docs diff --git a/internal/servants/localoss/localoss.go b/internal/servants/localoss/localoss.go index 1435e300..828b3be2 100644 --- a/internal/servants/localoss/localoss.go +++ b/internal/servants/localoss/localoss.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package localoss import ( diff --git a/internal/servants/localoss/xerror.go b/internal/servants/localoss/xerror.go index 7b656b7d..38132d24 100644 --- a/internal/servants/localoss/xerror.go +++ b/internal/servants/localoss/xerror.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package localoss import ( diff --git a/internal/servants/servants.go b/internal/servants/servants.go index 4c36c0d6..4f1f0bcd 100644 --- a/internal/servants/servants.go +++ b/internal/servants/servants.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package servants import ( diff --git a/internal/servants/statick/statick.go b/internal/servants/statick/statick.go index a852bdfc..d4c2bfdc 100644 --- a/internal/servants/statick/statick.go +++ b/internal/servants/statick/statick.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !embed // +build !embed diff --git a/internal/servants/statick/statick_embed.go b/internal/servants/statick/statick_embed.go index 6dd4c77b..32da717f 100644 --- a/internal/servants/statick/statick_embed.go +++ b/internal/servants/statick/statick_embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build embed // +build embed diff --git a/internal/servants/web/admin.go b/internal/servants/web/admin.go index f97832ce..e4f2ef6e 100644 --- a/internal/servants/web/admin.go +++ b/internal/servants/web/admin.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web type webAdminSrv struct { diff --git a/internal/servants/web/alipay.go b/internal/servants/web/alipay.go index a4f71e9f..80cfd7b7 100644 --- a/internal/servants/web/alipay.go +++ b/internal/servants/web/alipay.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web type webAlipaySrv struct { diff --git a/internal/servants/web/broker/attachment.go b/internal/servants/web/broker/attachment.go new file mode 100644 index 00000000..e8c69447 --- /dev/null +++ b/internal/servants/web/broker/attachment.go @@ -0,0 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker + +import ( + "github.com/rocboss/paopao-ce/internal/core" +) + +func CreateAttachment(attachment *core.Attachment) (*core.Attachment, error) { + return ds.CreateAttachment(attachment) +} diff --git a/internal/service/avatar.go b/internal/servants/web/broker/avatar.go similarity index 95% rename from internal/service/avatar.go rename to internal/servants/web/broker/avatar.go index 3ac302e0..04e183f4 100644 --- a/internal/service/avatar.go +++ b/internal/servants/web/broker/avatar.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "math/rand" diff --git a/internal/servants/web/broker/broker.go b/internal/servants/web/broker/broker.go new file mode 100644 index 00000000..79423901 --- /dev/null +++ b/internal/servants/web/broker/broker.go @@ -0,0 +1,48 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker + +import ( + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/dao" + "github.com/rocboss/paopao-ce/pkg/cfg" + "github.com/sirupsen/logrus" +) + +var ( + ds core.DataService + ts core.TweetSearchService + oss core.ObjectStorageService + DisablePhoneVerify bool +) + +func Initialize() { + ds = dao.DataService() + ts = dao.TweetSearchService() + oss = dao.ObjectStorageService() + DisablePhoneVerify = !cfg.If("Sms") +} + +// persistMediaContents 获取媒体内容并持久化 +func persistMediaContents(contents []*PostContentItem) (items []string, err error) { + items = make([]string, 0, len(contents)) + for _, item := range contents { + switch item.Type { + case core.ContentTypeImage, + core.ContentTypeVideo, + core.ContentTypeAudio, + core.ContentTypeAttachment, + core.ContentTypeChargeAttachment: + items = append(items, item.Content) + if err != nil { + continue + } + if err = oss.PersistObject(oss.ObjectKey(item.Content)); err != nil { + logrus.Errorf("service.persistMediaContents failed: %s", err) + } + } + } + return +} diff --git a/internal/service/comment.go b/internal/servants/web/broker/comment.go similarity index 83% rename from internal/service/comment.go rename to internal/servants/web/broker/comment.go index f5165d71..7f9389dc 100644 --- a/internal/service/comment.go +++ b/internal/servants/web/broker/comment.go @@ -1,11 +1,15 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( + "github.com/rocboss/paopao-ce/internal/core" "time" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/util" ) @@ -28,8 +32,8 @@ type ReplyDelReq struct { ID int64 `json:"id" binding:"required"` } -func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.CommentFormated, int64, error) { - conditions := &model.ConditionsT{ +func GetPostComments(postID int64, sort string, offset, limit int) ([]*core.CommentFormated, int64, error) { + conditions := &core.ConditionsT{ "post_id": postID, "ORDER": sort, } @@ -61,7 +65,7 @@ func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.Com return nil, 0, err } - commentsFormated := []*model.CommentFormated{} + commentsFormated := []*core.CommentFormated{} for _, comment := range comments { commentFormated := comment.Format() for _, content := range contents { @@ -89,7 +93,7 @@ func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.Com return commentsFormated, totalRows, nil } -func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) (comment *model.Comment, err error) { +func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) (comment *core.Comment, err error) { var mediaContents []string defer func() { @@ -113,7 +117,7 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) return nil, errcode.MaxCommentCount } ip := ctx.ClientIP() - comment = &model.Comment{ + comment = &core.Comment{ PostID: post.ID, UserID: userID, IP: ip, @@ -126,13 +130,13 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) for _, item := range param.Contents { // 检查附件是否是本站资源 - if item.Type == model.CONTENT_TYPE_IMAGE || item.Type == model.CONTENT_TYPE_VIDEO || item.Type == model.CONTENT_TYPE_ATTACHMENT { + if item.Type == core.ContentTypeImage || item.Type == core.ContentTypeVideo || item.Type == core.ContentTypeAttachment { if err := ds.CheckAttachment(item.Content); err != nil { continue } } - postContent := &model.CommentContent{ + postContent := &core.CommentContent{ CommentID: comment.ID, UserID: userID, Content: item.Content, @@ -153,10 +157,10 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) // 创建用户消息提醒 postMaster, err := ds.GetUserByID(post.UserID) if err == nil && postMaster.ID != userID { - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: postMaster.ID, - Type: model.MsgtypeComment, + Type: core.MsgtypeComment, Brief: "在泡泡中评论了你", PostID: post.ID, CommentID: comment.ID, @@ -169,10 +173,10 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) } // 创建消息提醒 - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: user.ID, - Type: model.MsgtypeComment, + Type: core.MsgtypeComment, Brief: "在泡泡评论中@了你", PostID: post.ID, CommentID: comment.ID, @@ -182,11 +186,11 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) return comment, nil } -func GetPostComment(id int64) (*model.Comment, error) { +func GetPostComment(id int64) (*core.Comment, error) { return ds.GetCommentByID(id) } -func DeletePostComment(comment *model.Comment) error { +func DeletePostComment(comment *core.Comment) error { // 加载post post, err := ds.GetPostByID(comment.PostID) if err == nil { @@ -198,7 +202,7 @@ func DeletePostComment(comment *model.Comment) error { return ds.DeleteComment(comment) } -func createPostPreHandler(commentID int64, userID, atUserID int64) (*model.Post, *model.Comment, int64, +func createPostPreHandler(commentID int64, userID, atUserID int64) (*core.Post, *core.Comment, int64, error) { // 加载Comment comment, err := ds.GetCommentByID(commentID) @@ -231,10 +235,10 @@ func createPostPreHandler(commentID int64, userID, atUserID int64) (*model.Post, return post, comment, atUserID, nil } -func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, userID, atUserID int64) (*model.CommentReply, error) { +func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, userID, atUserID int64) (*core.CommentReply, error) { var ( - post *model.Post - comment *model.Comment + post *core.Post + comment *core.Comment err error ) if post, comment, atUserID, err = createPostPreHandler(commentID, userID, atUserID); err != nil { @@ -243,7 +247,7 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u // 创建评论 ip := ctx.ClientIP() - reply := &model.CommentReply{ + reply := &core.CommentReply{ CommentID: commentID, UserID: userID, Content: content, @@ -268,10 +272,10 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u // 创建用户消息提醒 commentMaster, err := ds.GetUserByID(comment.UserID) if err == nil && commentMaster.ID != userID { - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: commentMaster.ID, - Type: model.MsgTypeReply, + Type: core.MsgTypeReply, Brief: "在泡泡评论下回复了你", PostID: post.ID, CommentID: comment.ID, @@ -280,10 +284,10 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u } postMaster, err := ds.GetUserByID(post.UserID) if err == nil && postMaster.ID != userID && commentMaster.ID != postMaster.ID { - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: postMaster.ID, - Type: model.MsgTypeReply, + Type: core.MsgTypeReply, Brief: "在泡泡评论下发布了新回复", PostID: post.ID, CommentID: comment.ID, @@ -294,10 +298,10 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u user, err := ds.GetUserByID(atUserID) if err == nil && user.ID != userID && commentMaster.ID != user.ID && postMaster.ID != user.ID { // 创建消息提醒 - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: user.ID, - Type: model.MsgTypeReply, + Type: core.MsgTypeReply, Brief: "在泡泡评论的回复中@了你", PostID: post.ID, CommentID: comment.ID, @@ -309,11 +313,11 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u return reply, nil } -func GetPostCommentReply(id int64) (*model.CommentReply, error) { +func GetPostCommentReply(id int64) (*core.CommentReply, error) { return ds.GetCommentReplyByID(id) } -func DeletePostCommentReply(reply *model.CommentReply) error { +func DeletePostCommentReply(reply *core.CommentReply) error { err := ds.DeleteCommentReply(reply) if err != nil { return err diff --git a/internal/service/message.go b/internal/servants/web/broker/message.go similarity index 84% rename from internal/service/message.go rename to internal/servants/web/broker/message.go index a025a849..6e5dd1a1 100644 --- a/internal/service/message.go +++ b/internal/servants/web/broker/message.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "fmt" @@ -6,7 +10,7 @@ import ( "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" ) @@ -23,7 +27,7 @@ type WhisperReq struct { } // CreateWhisper 创建私信 -func CreateWhisper(c *gin.Context, msg *model.Message) (*model.Message, error) { +func CreateWhisper(c *gin.Context, msg *core.Message) (*core.Message, error) { whisperKey := fmt.Sprintf("WhisperTimes:%d", msg.SenderUserID) // 今日频次限制 @@ -65,8 +69,8 @@ func ReadMessage(id, userID int64) error { return ds.ReadMessage(message) } -func GetMessages(userID int64, offset, limit int) ([]*model.MessageFormated, int64, error) { - conditions := &model.ConditionsT{ +func GetMessages(userID int64, offset, limit int) ([]*core.MessageFormated, int64, error) { + conditions := &core.ConditionsT{ "receiver_user_id": userID, "ORDER": "id DESC", } @@ -83,7 +87,7 @@ func GetMessages(userID int64, offset, limit int) ([]*model.MessageFormated, int } // 好友申请消息不需要获取其他信息 - if mf.Type == model.MsgTypeRequestingFriend { + if mf.Type == core.MsgTypeRequestingFriend { continue } diff --git a/internal/service/post.go b/internal/servants/web/broker/post.go similarity index 76% rename from internal/service/post.go rename to internal/servants/web/broker/post.go index c8bda6b8..9a73528b 100644 --- a/internal/service/post.go +++ b/internal/servants/web/broker/post.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "errors" @@ -10,8 +14,6 @@ import ( "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/util" "github.com/sirupsen/logrus" @@ -23,7 +25,7 @@ const TagTypeHot TagType = "hot" const TagTypeNew TagType = "new" type PostListReq struct { - Conditions *model.ConditionsT + Conditions *core.ConditionsT Offset int Limit int } @@ -37,7 +39,7 @@ type PostCreationReq struct { Tags []string `json:"tags" binding:"required"` Users []string `json:"users" binding:"required"` AttachmentPrice int64 `json:"attachment_price"` - Visibility model.PostVisibleT `json:"visibility"` + Visibility core.PostVisibleT `json:"visibility"` } type PostDelReq struct { @@ -53,8 +55,8 @@ type PostStickReq struct { } type PostVisibilityReq struct { - ID int64 `json:"id" binding:"required"` - Visibility model.PostVisibleT `json:"visibility"` + ID int64 `json:"id" binding:"required"` + Visibility core.PostVisibleT `json:"visibility"` } type PostStarReq struct { @@ -66,27 +68,25 @@ type PostCollectionReq struct { } type PostContentItem struct { - Content string `json:"content" binding:"required"` - Type model.PostContentT `json:"type" binding:"required"` - Sort int64 `json:"sort" binding:"required"` + Content string `json:"content" binding:"required"` + Type core.PostContentT `json:"type" binding:"required"` + Sort int64 `json:"sort" binding:"required"` } // Check 检查PostContentItem属性 func (p *PostContentItem) Check() error { // 检查附件是否是本站资源 - if p.Type == model.CONTENT_TYPE_IMAGE || p.Type == model.CONTENT_TYPE_VIDEO || p.Type == model. - CONTENT_TYPE_ATTACHMENT { + if p.Type == core.ContentTypeImage || p.Type == core.ContentTypeVideo || p.Type == core.ContentTypeAttachment { if err := ds.CheckAttachment(p.Content); err != nil { return err } } // 检查链接是否合法 - if p.Type == model.CONTENT_TYPE_LINK { + if p.Type == core.ContentTypeLink { if strings.Index(p.Content, "http://") != 0 && strings.Index(p.Content, "https://") != 0 { return fmt.Errorf("链接不合法") } } - return nil } @@ -103,7 +103,7 @@ func tagsFrom(originTags []string) []string { // CreatePost 创建文章 // TODO: 推文+推文内容需要在一个事务中添加,后续优化 -func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.PostFormated, err error) { +func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *core.PostFormated, err error) { var mediaContents []string defer func() { @@ -118,7 +118,7 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P ip := c.ClientIP() tags := tagsFrom(param.Tags) - post := &model.Post{ + post := &core.Post{ UserID: userID, Tags: strings.Join(tags, ","), IP: ip, @@ -138,11 +138,11 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P continue } - if item.Type == model.CONTENT_TYPE_ATTACHMENT && param.AttachmentPrice > 0 { - item.Type = model.CONTENT_TYPE_CHARGE_ATTACHMENT + if item.Type == core.ContentTypeAttachment && param.AttachmentPrice > 0 { + item.Type = core.ContentTypeChargeAttachment } - postContent := &model.PostContent{ + postContent := &core.PostContent{ PostID: post.ID, UserID: userID, Content: item.Content, @@ -155,10 +155,10 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P } // 私密推文不创建标签与用户提醒 - if post.Visibility != model.PostVisitPrivate { + if post.Visibility != core.PostVisitPrivate { // 创建标签 for _, t := range tags { - tag := &model.Tag{ + tag := &core.Tag{ UserID: userID, Tag: t, } @@ -174,10 +174,10 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P // 创建消息提醒 // TODO: 优化消息提醒处理机制 - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: user.ID, - Type: model.MsgTypePost, + Type: core.MsgTypePost, Brief: "在新发布的泡泡动态中@了你", PostID: post.ID, }) @@ -187,14 +187,14 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P // 推送Search PushPostToSearch(post) - formatedPosts, err := ds.RevampPosts([]*model.PostFormated{post.Format()}) + formatedPosts, err := ds.RevampPosts([]*core.PostFormated{post.Format()}) if err != nil { return nil, err } return formatedPosts[0], nil } -func DeletePost(user *model.User, id int64) *errcode.Error { +func DeletePost(user *core.User, id int64) *errcode.Error { if user == nil { return errcode.NoPermission } @@ -261,8 +261,8 @@ func StickPost(id int64) error { return nil } -func VisiblePost(user *model.User, postId int64, visibility model.PostVisibleT) *errcode.Error { - if visibility >= model.PostVisitInvalid { +func VisiblePost(user *core.User, postId int64, visibility core.PostVisibleT) *errcode.Error { + if visibility >= core.PostVisitInvalid { return errcode.InvalidParams } @@ -287,11 +287,11 @@ func VisiblePost(user *model.User, postId int64, visibility model.PostVisibleT) return nil } -func GetPostStar(postID, userID int64) (*model.PostStar, error) { +func GetPostStar(postID, userID int64) (*core.PostStar, error) { return ds.GetUserPostStar(postID, userID) } -func CreatePostStar(postID, userID int64) (*model.PostStar, error) { +func CreatePostStar(postID, userID int64) (*core.PostStar, error) { // 加载Post post, err := ds.GetPostByID(postID) if err != nil { @@ -299,7 +299,7 @@ func CreatePostStar(postID, userID int64) (*model.PostStar, error) { } // 私密post不可操作 - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { return nil, errors.New("no permision") } @@ -318,7 +318,7 @@ func CreatePostStar(postID, userID int64) (*model.PostStar, error) { return star, nil } -func DeletePostStar(star *model.PostStar) error { +func DeletePostStar(star *core.PostStar) error { err := ds.DeletePostStar(star) if err != nil { return err @@ -330,7 +330,7 @@ func DeletePostStar(star *model.PostStar) error { } // 私密post不可操作 - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { return errors.New("no permision") } @@ -344,11 +344,11 @@ func DeletePostStar(star *model.PostStar) error { return nil } -func GetPostCollection(postID, userID int64) (*model.PostCollection, error) { +func GetPostCollection(postID, userID int64) (*core.PostCollection, error) { return ds.GetUserPostCollection(postID, userID) } -func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) { +func CreatePostCollection(postID, userID int64) (*core.PostCollection, error) { // 加载Post post, err := ds.GetPostByID(postID) if err != nil { @@ -356,7 +356,7 @@ func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) { } // 私密post不可操作 - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { return nil, errors.New("no permision") } @@ -375,7 +375,7 @@ func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) { return collection, nil } -func DeletePostCollection(collection *model.PostCollection) error { +func DeletePostCollection(collection *core.PostCollection) error { err := ds.DeletePostCollection(collection) if err != nil { return err @@ -387,7 +387,7 @@ func DeletePostCollection(collection *model.PostCollection) error { } // 私密post不可操作 - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { return errors.New("no permision") } @@ -401,7 +401,7 @@ func DeletePostCollection(collection *model.PostCollection) error { return nil } -func GetPost(id int64) (*model.PostFormated, error) { +func GetPost(id int64) (*core.PostFormated, error) { post, err := ds.GetPostByID(id) if err != nil { @@ -431,15 +431,15 @@ func GetPost(id int64) (*model.PostFormated, error) { return postFormated, nil } -func GetPostContentByID(id int64) (*model.PostContent, error) { +func GetPostContentByID(id int64) (*core.PostContent, error) { return ds.GetPostContentByID(id) } -func GetIndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { +func GetIndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { return ds.IndexPosts(user, offset, limit) } -func GetPostList(req *PostListReq) ([]*model.Post, []*model.PostFormated, error) { +func GetPostList(req *PostListReq) ([]*core.Post, []*core.PostFormated, error) { posts, err := ds.GetPosts(req.Conditions, req.Offset, req.Limit) if err != nil { return nil, nil, err @@ -448,11 +448,11 @@ func GetPostList(req *PostListReq) ([]*model.Post, []*model.PostFormated, error) return posts, postFormated, err } -func GetPostCount(conditions *model.ConditionsT) (int64, error) { +func GetPostCount(conditions *core.ConditionsT) (int64, error) { return ds.GetPostCount(conditions) } -func GetPostListFromSearch(user *model.User, q *core.QueryReq, offset, limit int) ([]*model.PostFormated, int64, error) { +func GetPostListFromSearch(user *core.User, q *core.QueryReq, offset, limit int) ([]*core.PostFormated, int64, error) { resp, err := ts.Search(user, q, offset, limit) if err != nil { return nil, 0, err @@ -464,7 +464,7 @@ func GetPostListFromSearch(user *model.User, q *core.QueryReq, offset, limit int return posts, resp.Total, nil } -func GetPostListFromSearchByQuery(user *model.User, query string, offset, limit int) ([]*model.PostFormated, int64, error) { +func GetPostListFromSearchByQuery(user *core.User, query string, offset, limit int) ([]*core.PostFormated, int64, error) { q := &core.QueryReq{ Query: query, Type: "search", @@ -472,9 +472,9 @@ func GetPostListFromSearchByQuery(user *model.User, query string, offset, limit return GetPostListFromSearch(user, q, offset, limit) } -func PushPostToSearch(post *model.Post) { +func PushPostToSearch(post *core.Post) { postFormated := post.Format() - postFormated.User = &model.UserFormated{ + postFormated.User = &core.UserFormated{ ID: post.UserID, } contents, _ := ds.GetPostContentsByIDs([]int64{post.ID}) @@ -484,7 +484,7 @@ func PushPostToSearch(post *model.Post) { contentFormated := "" for _, content := range postFormated.Contents { - if content.Type == model.CONTENT_TYPE_TEXT || content.Type == model.CONTENT_TYPE_TITLE { + if content.Type == core.ContentTypeText || content.Type == core.ContentTypeTitle { contentFormated = contentFormated + content.Content + "\n" } } @@ -496,7 +496,7 @@ func PushPostToSearch(post *model.Post) { ts.AddDocuments(docs, fmt.Sprintf("%d", post.ID)) } -func DeleteSearchPost(post *model.Post) error { +func DeleteSearchPost(post *core.Post) error { return ts.DeleteDocuments([]string{fmt.Sprintf("%d", post.ID)}) } @@ -505,8 +505,8 @@ func PushPostsToSearch(c *gin.Context) { defer conf.Redis.Del(c, "JOB_PUSH_TO_SEARCH") splitNum := 1000 - totalRows, _ := GetPostCount(&model.ConditionsT{ - "visibility IN ?": []model.PostVisibleT{model.PostVisitPublic, model.PostVisitFriend}, + totalRows, _ := GetPostCount(&core.ConditionsT{ + "visibility IN ?": []core.PostVisibleT{core.PostVisitPublic, core.PostVisitFriend}, }) pages := math.Ceil(float64(totalRows) / float64(splitNum)) @@ -514,7 +514,7 @@ func PushPostsToSearch(c *gin.Context) { for i := 0; i < nums; i++ { posts, postsFormated, err := GetPostList(&PostListReq{ - Conditions: &model.ConditionsT{}, + Conditions: &core.ConditionsT{}, Offset: i * splitNum, Limit: splitNum, }) @@ -524,7 +524,7 @@ func PushPostsToSearch(c *gin.Context) { for i, pf := range postsFormated { contentFormated := "" for _, content := range pf.Contents { - if content.Type == model.CONTENT_TYPE_TEXT || content.Type == model.CONTENT_TYPE_TITLE { + if content.Type == core.ContentTypeText || content.Type == core.ContentTypeTitle { contentFormated = contentFormated + content.Content + "\n" } } @@ -538,22 +538,22 @@ func PushPostsToSearch(c *gin.Context) { } } -func GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error) { +func GetPostTags(param *PostTagsReq) ([]*core.TagFormated, error) { num := param.Num if num > conf.AppSetting.MaxPageSize { num = conf.AppSetting.MaxPageSize } - conditions := &model.ConditionsT{} + conditions := &core.ConditionsT{} if param.Type == TagTypeHot { // 热门标签 - conditions = &model.ConditionsT{ + conditions = &core.ConditionsT{ "ORDER": "quote_num DESC", } } if param.Type == TagTypeNew { // 热门标签 - conditions = &model.ConditionsT{ + conditions = &core.ConditionsT{ "ORDER": "id DESC", } } @@ -571,7 +571,7 @@ func GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error) { users, _ := ds.GetUsersByIDs(userIds) - tagsFormated := []*model.TagFormated{} + tagsFormated := []*core.TagFormated{} for _, tag := range tags { tagFormated := tag.Format() for _, user := range users { diff --git a/internal/service/sign.go b/internal/servants/web/broker/sign.go similarity index 79% rename from internal/service/sign.go rename to internal/servants/web/broker/sign.go index d3ec373a..c8883638 100644 --- a/internal/service/sign.go +++ b/internal/servants/web/broker/sign.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "fmt" diff --git a/internal/service/user.go b/internal/servants/web/broker/user.go similarity index 76% rename from internal/service/user.go rename to internal/servants/web/broker/user.go index 7289c067..66919a99 100644 --- a/internal/service/user.go +++ b/internal/servants/web/broker/user.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "fmt" @@ -10,15 +14,14 @@ import ( "github.com/gin-gonic/gin" "github.com/gofrs/uuid" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/util" "github.com/sirupsen/logrus" ) -const MAX_CAPTCHA_TIMES = 2 +const _MaxCaptchaTimes = 2 type PhoneCaptchaReq struct { Phone string `json:"phone" form:"phone" binding:"required"` @@ -59,19 +62,48 @@ type ChangeUserStatusReq struct { Status int `json:"status" form:"status" binding:"required"` } -const LOGIN_ERR_KEY = "PaoPaoUserLoginErr" -const MAX_LOGIN_ERR_TIMES = 10 +type RequestingFriendReq struct { + UserId int64 `json:"user_id" binding:"required"` + Greetings string `json:"greetings" binding:"required"` +} + +type AddFriendReq struct { + UserId int64 `json:"user_id" binding:"required"` +} + +type RejectFriendReq struct { + UserId int64 `json:"user_id" binding:"required"` +} + +type DeleteFriendReq struct { + UserId int64 `json:"user_id"` +} + +type UserProfileResp struct { + ID int64 `json:"id"` + Nickname string `json:"nickname"` + Username string `json:"username"` + Status int `json:"status"` + Avatar string `json:"avatar"` + IsAdmin bool `json:"is_admin"` + IsFriend bool `json:"is_friend"` +} + +const ( + _LoginErrKey = "PaoPaoUserLoginErr" + _MaxLoginErrTimes = 10 +) // DoLogin 用户认证 -func DoLogin(ctx *gin.Context, param *AuthRequest) (*model.User, error) { +func DoLogin(ctx *gin.Context, param *AuthRequest) (*core.User, error) { user, err := ds.GetUserByUsername(param.Username) if err != nil { return nil, errcode.UnauthorizedAuthNotExist } if user.Model != nil && user.ID > 0 { - if errTimes, err := conf.Redis.Get(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result(); err == nil { - if convert.StrTo(errTimes).MustInt() >= MAX_LOGIN_ERR_TIMES { + if errTimes, err := conf.Redis.Get(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result(); err == nil { + if convert.StrTo(errTimes).MustInt() >= _MaxLoginErrTimes { return nil, errcode.TooManyLoginError } } @@ -79,19 +111,19 @@ func DoLogin(ctx *gin.Context, param *AuthRequest) (*model.User, error) { // 对比密码是否正确 if ValidPassword(user.Password, param.Password, user.Salt) { - if user.Status == model.UserStatusClosed { + if user.Status == core.UserStatusClosed { return nil, errcode.UserHasBeenBanned } // 清空登录计数 - conf.Redis.Del(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)) + conf.Redis.Del(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)) return user, nil } // 登录错误计数 - _, err = conf.Redis.Incr(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result() + _, err = conf.Redis.Incr(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result() if err == nil { - conf.Redis.Expire(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID), time.Hour).Result() + conf.Redis.Expire(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID), time.Hour).Result() } return nil, errcode.UnauthorizedAuthFailed @@ -106,8 +138,8 @@ func ValidPassword(dbPassword, password, salt string) bool { } // CheckStatus 检测用户权限 -func CheckStatus(user *model.User) bool { - return user.Status == model.UserStatusNormal +func CheckStatus(user *core.User) bool { + return user.Status == core.UserStatusNormal } // ValidUsername 验证用户 @@ -161,7 +193,7 @@ func CheckPhoneCaptcha(phone, captcha string) *errcode.Error { return errcode.ErrorPhoneCaptcha } - if c.UseTimes >= MAX_CAPTCHA_TIMES { + if c.UseTimes >= _MaxCaptchaTimes { return errcode.MaxPhoneCaptchaUseTimes } @@ -198,16 +230,16 @@ func EncryptPasswordAndSalt(password string) (string, string) { } // Register 用户注册 -func Register(username, password string) (*model.User, error) { +func Register(username, password string) (*core.User, error) { password, salt := EncryptPasswordAndSalt(password) - user := &model.User{ + user := &core.User{ Nickname: username, Username: username, Password: password, Avatar: GetRandomAvatar(), Salt: salt, - Status: model.UserStatusNormal, + Status: core.UserStatusNormal, } user, err := ds.CreateUser(user) @@ -218,40 +250,40 @@ func Register(username, password string) (*model.User, error) { return user, nil } -func RequestingFriend(user *model.User, param *rest.RequestingFriendReq) error { +func RequestingFriend(user *core.User, param *RequestingFriendReq) error { if _, err := ds.GetUserByID(param.UserId); err != nil { return errcode.NotExistFriendId } return ds.RequestingFriend(user.ID, param.UserId, param.Greetings) } -func AddFriend(user *model.User, param *rest.AddFriendReq) error { +func AddFriend(user *core.User, param *AddFriendReq) error { if _, err := ds.GetUserByID(param.UserId); err != nil { return errcode.NotExistFriendId } return ds.AddFriend(user.ID, param.UserId) } -func RejectFriend(user *model.User, param *rest.RejectFriendReq) error { +func RejectFriend(user *core.User, param *RejectFriendReq) error { if _, err := ds.GetUserByID(param.UserId); err != nil { return errcode.NotExistFriendId } return ds.RejectFriend(user.ID, param.UserId) } -func DeleteFriend(user *model.User, param *rest.DeleteFriendReq) error { +func DeleteFriend(user *core.User, param *DeleteFriendReq) error { if _, err := ds.GetUserByID(param.UserId); err != nil { return errcode.NotExistFriendId } return ds.DeleteFriend(user.ID, param.UserId) } -func GetContacts(user *model.User, offset int, limit int) (*rest.ContactsResp, error) { +func GetContacts(user *core.User, offset int, limit int) (*core.ContactList, error) { return ds.GetContacts(user.ID, offset, limit) } // GetUserInfo 获取用户信息 -func GetUserInfo(param *AuthRequest) (*model.User, error) { +func GetUserInfo(param *AuthRequest) (*core.User, error) { user, err := ds.GetUserByUsername(param.Username) if err != nil { @@ -265,7 +297,7 @@ func GetUserInfo(param *AuthRequest) (*model.User, error) { return nil, errcode.UnauthorizedAuthNotExist } -func GetUserByID(id int64) (*model.User, error) { +func GetUserByID(id int64) (*core.User, error) { user, err := ds.GetUserByID(id) if err != nil { @@ -279,15 +311,15 @@ func GetUserByID(id int64) (*model.User, error) { return nil, errcode.NoExistUsername } -func GetUserByUsername(user *model.User, username string) (*rest.UserProfileResp, error) { +func GetUserByUsername(user *core.User, username string) (*UserProfileResp, error) { other, err := ds.GetUserByUsername(username) if err != nil { return nil, err } - var resp *rest.UserProfileResp + var resp *UserProfileResp if other.Model != nil && other.ID > 0 { - resp = &rest.UserProfileResp{ + resp = &UserProfileResp{ ID: other.ID, Nickname: other.Nickname, Username: other.Username, @@ -307,14 +339,14 @@ func GetUserByUsername(user *model.User, username string) (*rest.UserProfileResp } // UpdateUserInfo 更新用户信息 -func UpdateUserInfo(user *model.User) *errcode.Error { +func UpdateUserInfo(user *core.User) *errcode.Error { if err := ds.UpdateUser(user); err != nil { return errcode.ServerError } return nil } -func ChangeUserAvatar(user *model.User, avatar string) (err *errcode.Error) { +func ChangeUserAvatar(user *core.User, avatar string) (err *errcode.Error) { defer func() { if err != nil { deleteOssObjects([]string{avatar}) @@ -336,7 +368,7 @@ func ChangeUserAvatar(user *model.User, avatar string) (err *errcode.Error) { } // GetUserCollections 获取用户收藏列表 -func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) { +func GetUserCollections(userID int64, offset, limit int) ([]*core.PostFormated, int64, error) { collections, err := ds.GetUserPostCollections(userID, offset, limit) if err != nil { return nil, 0, err @@ -345,7 +377,7 @@ func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated, if err != nil { return nil, 0, err } - var posts []*model.Post + var posts []*core.Post for _, collection := range collections { posts = append(posts, collection.Post) } @@ -358,7 +390,7 @@ func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated, } // GetUserStars 获取用户点赞列表 -func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) { +func GetUserStars(userID int64, offset, limit int) ([]*core.PostFormated, int64, error) { stars, err := ds.GetUserPostStars(userID, offset, limit) if err != nil { return nil, 0, err @@ -368,7 +400,7 @@ func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64 return nil, 0, err } - var posts []*model.Post + var posts []*core.Post for _, star := range stars { posts = append(posts, star.Post) } @@ -381,7 +413,7 @@ func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64 } // GetUserWalletBills 获取用户账单列表 -func GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, int64, error) { +func GetUserWalletBills(userID int64, offset, limit int) ([]*core.WalletStatement, int64, error) { bills, err := ds.GetUserWalletBills(userID, offset, limit) if err != nil { return nil, 0, err @@ -448,7 +480,7 @@ func IsFriend(userId, friendId int64) bool { } // checkPermision 检查是否拥有者或管理员 -func checkPermision(user *model.User, targetUserId int64) *errcode.Error { +func checkPermision(user *core.User, targetUserId int64) *errcode.Error { if user == nil || (user.ID != targetUserId && !user.IsAdmin) { return errcode.NoPermission } diff --git a/internal/service/wallet.go b/internal/servants/web/broker/wallet.go similarity index 69% rename from internal/service/wallet.go rename to internal/servants/web/broker/wallet.go index 0f22b23f..6f89edf8 100644 --- a/internal/service/wallet.go +++ b/internal/servants/web/broker/wallet.go @@ -1,11 +1,15 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( + "github.com/rocboss/paopao-ce/internal/core" "time" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/errcode" ) @@ -13,11 +17,11 @@ type RechargeReq struct { Amount int64 `json:"amount" form:"amount" binding:"required"` } -func GetRechargeByID(id int64) (*model.WalletRecharge, error) { +func GetRechargeByID(id int64) (*core.WalletRecharge, error) { return ds.GetRechargeByID(id) } -func CreateRecharge(userID, amount int64) (*model.WalletRecharge, error) { +func CreateRecharge(userID, amount int64) (*core.WalletRecharge, error) { return ds.CreateRecharge(userID, amount) } @@ -44,7 +48,7 @@ func FinishRecharge(ctx *gin.Context, id int64, tradeNo string) error { return nil } -func BuyPostAttachment(post *model.Post, user *model.User) error { +func BuyPostAttachment(post *core.Post, user *core.User) error { if user.Balance < post.AttachmentPrice { return errcode.InsuffientDownloadMoney } diff --git a/internal/servants/web/core.go b/internal/servants/web/core.go index 4a4ccd32..085e5bcf 100644 --- a/internal/servants/web/core.go +++ b/internal/servants/web/core.go @@ -1,8 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web import ( api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" - "github.com/rocboss/paopao-ce/internal/servants/core" + "github.com/rocboss/paopao-ce/internal/servants/base" ) var ( @@ -12,17 +16,17 @@ var ( ) type webCoreSrv struct { - core.BaseServant + base.BaseServant api.UnimplementedWebCoreServant } type webCoreBinding struct { - core.BaseBinding + base.BaseBinding *api.UnimplementedWebCoreBinding } type webCoreRender struct { - core.BaseRender + base.BaseRender *api.UnimplementedWebCoreRender } @@ -33,7 +37,7 @@ func newWebCoreSrv() api.WebCore { func newWebCoreBinding() api.WebCoreBinding { return &webCoreBinding{ UnimplementedWebCoreBinding: &api.UnimplementedWebCoreBinding{ - BindAny: core.BindAny, + BindAny: base.BindAny, }, } } @@ -41,7 +45,7 @@ func newWebCoreBinding() api.WebCoreBinding { func newWebCoreRender() api.WebCoreRender { return &webCoreRender{ UnimplementedWebCoreRender: &api.UnimplementedWebCoreRender{ - RenderAny: core.RenderAny, + RenderAny: base.RenderAny, }, } } diff --git a/internal/servants/web/followship.go b/internal/servants/web/followship.go index 6965c4a5..4158de39 100644 --- a/internal/servants/web/followship.go +++ b/internal/servants/web/followship.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web type webFollowshipSrv struct { diff --git a/internal/servants/web/friendship.go b/internal/servants/web/friendship.go index 87690037..a4fb3d59 100644 --- a/internal/servants/web/friendship.go +++ b/internal/servants/web/friendship.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web type webFriendshipSrv struct { diff --git a/internal/servants/web/loose.go b/internal/servants/web/loose.go index 051a86ef..51a309a1 100644 --- a/internal/servants/web/loose.go +++ b/internal/servants/web/loose.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web type webLooseSrv struct { diff --git a/internal/servants/web/priv.go b/internal/servants/web/priv.go index efe80d49..51f0f486 100644 --- a/internal/servants/web/priv.go +++ b/internal/servants/web/priv.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web type webPrivSrv struct { diff --git a/internal/servants/web/pub.go b/internal/servants/web/pub.go index 2b55e3ac..d7c68ec5 100644 --- a/internal/servants/web/pub.go +++ b/internal/servants/web/pub.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web type webPubSrv struct { diff --git a/internal/routers/api/api.go b/internal/servants/web/routers/api/api.go similarity index 89% rename from internal/routers/api/api.go rename to internal/servants/web/routers/api/api.go index c722ac88..39e748ab 100644 --- a/internal/routers/api/api.go +++ b/internal/servants/web/routers/api/api.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( diff --git a/internal/routers/api/assets/comic.ttf b/internal/servants/web/routers/api/assets/comic.ttf similarity index 100% rename from internal/routers/api/assets/comic.ttf rename to internal/servants/web/routers/api/assets/comic.ttf diff --git a/internal/routers/api/attachment.go b/internal/servants/web/routers/api/attachment.go similarity index 79% rename from internal/routers/api/attachment.go rename to internal/servants/web/routers/api/attachment.go index 905b2c03..143c0c12 100644 --- a/internal/routers/api/attachment.go +++ b/internal/servants/web/routers/api/attachment.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( @@ -6,19 +10,19 @@ import ( "github.com/disintegration/imaging" "github.com/gin-gonic/gin" "github.com/gofrs/uuid" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/sirupsen/logrus" ) -var uploadAttachmentTypeMap = map[string]model.AttachmentType{ - "public/image": model.ATTACHMENT_TYPE_IMAGE, - "public/avatar": model.ATTACHMENT_TYPE_IMAGE, - "public/video": model.ATTACHMENT_TYPE_VIDEO, - "attachment": model.ATTACHMENT_TYPE_OTHER, +var uploadAttachmentTypeMap = map[string]core.AttachmentType{ + "public/image": core.AttachmentTypeImage, + "public/avatar": core.AttachmentTypeImage, + "public/video": core.AttachmentTypeVideo, + "attachment": core.AttachmentTypeOther, } func GeneratePath(s string) string { @@ -110,7 +114,7 @@ func UploadAttachment(c *gin.Context) { } // 构造附件Model - attachment := &model.Attachment{ + attachment := &core.Attachment{ FileSize: fileHeader.Size, Content: objectUrl, } @@ -120,7 +124,7 @@ func UploadAttachment(c *gin.Context) { } attachment.Type = uploadAttachmentTypeMap[uploadType] - if attachment.Type == model.ATTACHMENT_TYPE_IMAGE { + if attachment.Type == core.AttachmentTypeImage { var src image.Image src, err = imaging.Decode(file) if err == nil { @@ -128,7 +132,7 @@ func UploadAttachment(c *gin.Context) { } } - attachment, err = service.CreateAttachment(attachment) + attachment, err = broker.CreateAttachment(attachment) if err != nil { logrus.Errorf("service.CreateAttachment err: %v", err) response.ToErrorResponse(errcode.FileUploadFailed) @@ -142,15 +146,15 @@ func DownloadAttachmentPrecheck(c *gin.Context) { contentID := convert.StrTo(c.Query("id")).MustInt64() // 加载content - content, err := service.GetPostContentByID(contentID) + content, err := broker.GetPostContentByID(contentID) if err != nil { logrus.Errorf("service.GetPostContentByID err: %v", err) response.ToErrorResponse(errcode.InvalidDownloadReq) } user, _ := c.Get("USER") - if content.Type == model.CONTENT_TYPE_CHARGE_ATTACHMENT { + if content.Type == core.ContentTypeChargeAttachment { // 加载post - post, err := service.GetPost(content.PostID) + post, err := broker.GetPost(content.PostID) if err != nil { logrus.Errorf("service.GetPost err: %v", err) response.ToResponse(gin.H{ @@ -160,7 +164,7 @@ func DownloadAttachmentPrecheck(c *gin.Context) { } // 发布者或管理员免费下载 - if post.UserID == user.(*model.User).ID || user.(*model.User).IsAdmin { + if post.UserID == user.(*core.User).ID || user.(*core.User).IsAdmin { response.ToResponse(gin.H{ "paid": true, }) @@ -169,7 +173,7 @@ func DownloadAttachmentPrecheck(c *gin.Context) { // 检测是否有购买记录 response.ToResponse(gin.H{ - "paid": service.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID), + "paid": broker.CheckPostAttachmentIsPaid(post.ID, user.(*core.User).ID), }) return } @@ -184,18 +188,18 @@ func DownloadAttachment(c *gin.Context) { contentID := convert.StrTo(c.Query("id")).MustInt64() // 加载content - content, err := service.GetPostContentByID(contentID) + content, err := broker.GetPostContentByID(contentID) if err != nil { logrus.Errorf("service.GetPostContentByID err: %v", err) response.ToErrorResponse(errcode.InvalidDownloadReq) } // 收费附件 - if content.Type == model.CONTENT_TYPE_CHARGE_ATTACHMENT { + if content.Type == core.ContentTypeChargeAttachment { user, _ := c.Get("USER") // 加载post - post, err := service.GetPost(content.PostID) + post, err := broker.GetPost(content.PostID) if err != nil { logrus.Errorf("service.GetPost err: %v", err) response.ToResponse(gin.H{ @@ -207,24 +211,24 @@ func DownloadAttachment(c *gin.Context) { paidFlag := false // 发布者或管理员免费下载 - if post.UserID == user.(*model.User).ID || user.(*model.User).IsAdmin { + if post.UserID == user.(*core.User).ID || user.(*core.User).IsAdmin { paidFlag = true } // 检测是否有购买记录 - if service.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID) { + if broker.CheckPostAttachmentIsPaid(post.ID, user.(*core.User).ID) { paidFlag = true } if !paidFlag { // 未购买,则尝试购买 - err := service.BuyPostAttachment(&model.Post{ - Model: &model.Model{ + err := broker.BuyPostAttachment(&core.Post{ + Model: &core.Model{ ID: post.ID, }, UserID: post.UserID, AttachmentPrice: post.AttachmentPrice, - }, user.(*model.User)) + }, user.(*core.User)) if err != nil { logrus.Errorf("service.BuyPostAttachment err: %v", err) if err == errcode.InsuffientDownloadMoney { diff --git a/internal/routers/api/comment.go b/internal/servants/web/routers/api/comment.go similarity index 75% rename from internal/routers/api/comment.go rename to internal/servants/web/routers/api/comment.go index 4b1fca36..0779eabb 100644 --- a/internal/routers/api/comment.go +++ b/internal/servants/web/routers/api/comment.go @@ -1,9 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" @@ -14,7 +18,7 @@ func GetPostComments(c *gin.Context) { postID := convert.StrTo(c.Query("id")).MustInt64() response := app.NewResponse(c) - contents, totalRows, err := service.GetPostComments(postID, "id ASC", 0, 0) + contents, totalRows, err := broker.GetPostComments(postID, "id ASC", 0, 0) if err != nil { logrus.Errorf("service.GetPostComments err: %v\n", err) @@ -26,7 +30,7 @@ func GetPostComments(c *gin.Context) { } func CreatePostComment(c *gin.Context) { - param := service.CommentCreationReq{} + param := broker.CommentCreationReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -36,7 +40,7 @@ func CreatePostComment(c *gin.Context) { } userID, _ := c.Get("UID") - comment, err := service.CreatePostComment(c, userID.(int64), param) + comment, err := broker.CreatePostComment(c, userID.(int64), param) if err != nil { if err == errcode.MaxCommentCount { @@ -52,7 +56,7 @@ func CreatePostComment(c *gin.Context) { } func DeletePostComment(c *gin.Context) { - param := service.CommentDelReq{} + param := broker.CommentDelReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -62,20 +66,20 @@ func DeletePostComment(c *gin.Context) { } user, _ := c.Get("USER") - comment, err := service.GetPostComment(param.ID) + comment, err := broker.GetPostComment(param.ID) if err != nil { logrus.Errorf("service.GetPostComment err: %v\n", err) response.ToErrorResponse(errcode.GetCommentFailed) return } - if user.(*model.User).ID != comment.UserID && !user.(*model.User).IsAdmin { + if user.(*core.User).ID != comment.UserID && !user.(*core.User).IsAdmin { response.ToErrorResponse(errcode.NoPermission) return } // 执行删除 - err = service.DeletePostComment(comment) + err = broker.DeletePostComment(comment) if err != nil { logrus.Errorf("service.DeletePostComment err: %v\n", err) response.ToErrorResponse(errcode.DeleteCommentFailed) @@ -86,7 +90,7 @@ func DeletePostComment(c *gin.Context) { } func CreatePostCommentReply(c *gin.Context) { - param := service.CommentReplyCreationReq{} + param := broker.CommentReplyCreationReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -96,7 +100,7 @@ func CreatePostCommentReply(c *gin.Context) { } user, _ := c.Get("USER") - comment, err := service.CreatePostCommentReply(c, param.CommentID, param.Content, user.(*model.User).ID, param.AtUserID) + comment, err := broker.CreatePostCommentReply(c, param.CommentID, param.Content, user.(*core.User).ID, param.AtUserID) if err != nil { logrus.Errorf("service.CreatePostCommentReply err: %v\n", err) response.ToErrorResponse(errcode.CreateReplyFailed) @@ -107,7 +111,7 @@ func CreatePostCommentReply(c *gin.Context) { } func DeletePostCommentReply(c *gin.Context) { - param := service.ReplyDelReq{} + param := broker.ReplyDelReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -118,20 +122,20 @@ func DeletePostCommentReply(c *gin.Context) { user, _ := c.Get("USER") - reply, err := service.GetPostCommentReply(param.ID) + reply, err := broker.GetPostCommentReply(param.ID) if err != nil { logrus.Errorf("service.GetPostCommentReply err: %v\n", err) response.ToErrorResponse(errcode.GetReplyFailed) return } - if user.(*model.User).ID != reply.UserID && !user.(*model.User).IsAdmin { + if user.(*core.User).ID != reply.UserID && !user.(*core.User).IsAdmin { response.ToErrorResponse(errcode.NoPermission) return } // 执行删除 - err = service.DeletePostCommentReply(reply) + err = broker.DeletePostCommentReply(reply) if err != nil { logrus.Errorf("service.DeletePostCommentReply err: %v\n", err) response.ToErrorResponse(errcode.DeleteCommentFailed) diff --git a/internal/routers/api/home.go b/internal/servants/web/routers/api/home.go similarity index 86% rename from internal/routers/api/home.go rename to internal/servants/web/routers/api/home.go index 80489978..b863b712 100644 --- a/internal/routers/api/home.go +++ b/internal/servants/web/routers/api/home.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( @@ -12,8 +16,8 @@ import ( "github.com/gin-gonic/gin" "github.com/gofrs/uuid" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/debug" @@ -39,8 +43,8 @@ func SyncSearchIndex(c *gin.Context) { user, _ := c.Get("USER") - if user.(*model.User).IsAdmin { - go service.PushPostsToSearch(c) + if user.(*core.User).IsAdmin { + go broker.PushPostsToSearch(c) } response.ToResponse(nil) @@ -74,7 +78,7 @@ func GetCaptcha(c *gin.Context) { } func PostCaptcha(c *gin.Context) { - param := service.PhoneCaptchaReq{} + param := broker.PhoneCaptchaReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -96,7 +100,7 @@ func PostCaptcha(c *gin.Context) { return } - err := service.SendPhoneCaptcha(c, param.Phone) + err := broker.SendPhoneCaptcha(c, param.Phone) if err != nil { logrus.Errorf("app.SendPhoneCaptcha errs: %v", errs) response.ToErrorResponse(errcode.GetPhoneCaptchaError) diff --git a/internal/routers/api/message.go b/internal/servants/web/routers/api/message.go similarity index 74% rename from internal/routers/api/message.go rename to internal/servants/web/routers/api/message.go index 8c24cbd2..9cc72ffd 100644 --- a/internal/routers/api/message.go +++ b/internal/servants/web/routers/api/message.go @@ -1,9 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/sirupsen/logrus" @@ -12,12 +16,12 @@ import ( func GetUnreadMsgCount(c *gin.Context) { response := app.NewResponse(c) - user := &model.User{} + user := &core.User{} if u, exists := c.Get("USER"); exists { - user = u.(*model.User) + user = u.(*core.User) } - count, _ := service.GetUnreadCount(user.ID) + count, _ := broker.GetUnreadCount(user.ID) response.ToResponse(gin.H{ "count": count, @@ -28,7 +32,7 @@ func GetMessages(c *gin.Context) { response := app.NewResponse(c) userID, _ := c.Get("UID") - messages, totalRows, err := service.GetMessages(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) + messages, totalRows, err := broker.GetMessages(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) if err != nil { logrus.Errorf("service.GetMessages err: %v\n", err) @@ -40,7 +44,7 @@ func GetMessages(c *gin.Context) { } func ReadMessage(c *gin.Context) { - param := service.ReadMessageReq{} + param := broker.ReadMessageReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -50,7 +54,7 @@ func ReadMessage(c *gin.Context) { } userID, _ := c.Get("UID") - err := service.ReadMessage(param.ID, userID.(int64)) + err := broker.ReadMessage(param.ID, userID.(int64)) if err != nil { logrus.Errorf("service.ReadMessage err: %v\n", err) response.ToErrorResponse(errcode.ReadMessageFailed) @@ -61,7 +65,7 @@ func ReadMessage(c *gin.Context) { } func SendUserWhisper(c *gin.Context) { - param := service.WhisperReq{} + param := broker.WhisperReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -78,10 +82,10 @@ func SendUserWhisper(c *gin.Context) { return } - _, err := service.CreateWhisper(c, &model.Message{ + _, err := broker.CreateWhisper(c, &core.Message{ SenderUserID: userID.(int64), ReceiverUserID: param.UserID, - Type: model.MsgTypeWhisper, + Type: core.MsgTypeWhisper, Brief: "给你发送新私信了", Content: param.Content, }) diff --git a/internal/routers/api/post.go b/internal/servants/web/routers/api/post.go similarity index 79% rename from internal/routers/api/post.go rename to internal/servants/web/routers/api/post.go index f580428f..9ca19f3f 100644 --- a/internal/routers/api/post.go +++ b/internal/servants/web/routers/api/post.go @@ -1,10 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" @@ -25,7 +28,7 @@ func GetPostList(c *gin.Context) { user, _ := userFrom(c) offset, limit := app.GetPageOffset(c) if q.Query == "" && q.Type == "search" { - resp, err := service.GetIndexPosts(user, offset, limit) + resp, err := broker.GetIndexPosts(user, offset, limit) if err != nil { logrus.Errorf("service.GetPostList err: %v\n", err) response.ToErrorResponse(errcode.GetPostsFailed) @@ -34,7 +37,7 @@ func GetPostList(c *gin.Context) { response.ToResponseList(resp.Tweets, resp.Total) } else { - posts, totalRows, err := service.GetPostListFromSearch(user, q, offset, limit) + posts, totalRows, err := broker.GetPostListFromSearch(user, q, offset, limit) if err != nil { logrus.Errorf("service.GetPostListFromSearch err: %v\n", err) @@ -49,7 +52,7 @@ func GetPost(c *gin.Context) { postID := convert.StrTo(c.Query("id")).MustInt64() response := app.NewResponse(c) - postFormated, err := service.GetPost(postID) + postFormated, err := broker.GetPost(postID) if err != nil { logrus.Errorf("service.GetPost err: %v\n", err) @@ -61,7 +64,7 @@ func GetPost(c *gin.Context) { } func CreatePost(c *gin.Context) { - param := service.PostCreationReq{} + param := broker.PostCreationReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -71,7 +74,7 @@ func CreatePost(c *gin.Context) { } userID, _ := c.Get("UID") - post, err := service.CreatePost(c, userID.(int64), param) + post, err := broker.CreatePost(c, userID.(int64), param) if err != nil { logrus.Errorf("service.CreatePost err: %v\n", err) @@ -83,7 +86,7 @@ func CreatePost(c *gin.Context) { } func DeletePost(c *gin.Context) { - param := service.PostDelReq{} + param := broker.PostDelReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -98,7 +101,7 @@ func DeletePost(c *gin.Context) { return } - err := service.DeletePost(user, param.ID) + err := broker.DeletePost(user, param.ID) if err != nil { logrus.Errorf("service.DeletePost err: %v\n", err) response.ToErrorResponse(err) @@ -114,7 +117,7 @@ func GetPostStar(c *gin.Context) { userID, _ := c.Get("UID") - _, err := service.GetPostStar(postID, userID.(int64)) + _, err := broker.GetPostStar(postID, userID.(int64)) if err != nil { response.ToResponse(gin.H{ "status": false, @@ -129,7 +132,7 @@ func GetPostStar(c *gin.Context) { } func PostStar(c *gin.Context) { - param := service.PostStarReq{} + param := broker.PostStarReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -141,14 +144,14 @@ func PostStar(c *gin.Context) { userID, _ := c.Get("UID") status := false - star, err := service.GetPostStar(param.ID, userID.(int64)) + star, err := broker.GetPostStar(param.ID, userID.(int64)) if err != nil { // 创建Star - _, err = service.CreatePostStar(param.ID, userID.(int64)) + _, err = broker.CreatePostStar(param.ID, userID.(int64)) status = true } else { // 取消Star - err = service.DeletePostStar(star) + err = broker.DeletePostStar(star) } if err != nil { @@ -167,7 +170,7 @@ func GetPostCollection(c *gin.Context) { userID, _ := c.Get("UID") - _, err := service.GetPostCollection(postID, userID.(int64)) + _, err := broker.GetPostCollection(postID, userID.(int64)) if err != nil { response.ToResponse(gin.H{ "status": false, @@ -182,7 +185,7 @@ func GetPostCollection(c *gin.Context) { } func PostCollection(c *gin.Context) { - param := service.PostCollectionReq{} + param := broker.PostCollectionReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -194,14 +197,14 @@ func PostCollection(c *gin.Context) { userID, _ := c.Get("UID") status := false - collection, err := service.GetPostCollection(param.ID, userID.(int64)) + collection, err := broker.GetPostCollection(param.ID, userID.(int64)) if err != nil { // 创建collection - _, err = service.CreatePostCollection(param.ID, userID.(int64)) + _, err = broker.CreatePostCollection(param.ID, userID.(int64)) status = true } else { // 取消Star - err = service.DeletePostCollection(collection) + err = broker.DeletePostCollection(collection) } if err != nil { @@ -215,7 +218,7 @@ func PostCollection(c *gin.Context) { } func LockPost(c *gin.Context) { - param := service.PostLockReq{} + param := broker.PostLockReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -227,18 +230,18 @@ func LockPost(c *gin.Context) { user, _ := c.Get("USER") // 获取Post - postFormated, err := service.GetPost(param.ID) + postFormated, err := broker.GetPost(param.ID) if err != nil { logrus.Errorf("service.GetPost err: %v\n", err) response.ToErrorResponse(errcode.GetPostFailed) return } - if postFormated.UserID != user.(*model.User).ID && !user.(*model.User).IsAdmin { + if postFormated.UserID != user.(*core.User).ID && !user.(*core.User).IsAdmin { response.ToErrorResponse(errcode.NoPermission) return } - err = service.LockPost(param.ID) + err = broker.LockPost(param.ID) if err != nil { logrus.Errorf("service.LockPost err: %v\n", err) response.ToErrorResponse(errcode.LockPostFailed) @@ -251,7 +254,7 @@ func LockPost(c *gin.Context) { } func StickPost(c *gin.Context) { - param := service.PostStickReq{} + param := broker.PostStickReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -263,18 +266,18 @@ func StickPost(c *gin.Context) { user, _ := c.Get("USER") // 获取Post - postFormated, err := service.GetPost(param.ID) + postFormated, err := broker.GetPost(param.ID) if err != nil { logrus.Errorf("service.GetPost err: %v\n", err) response.ToErrorResponse(errcode.GetPostFailed) return } - if !user.(*model.User).IsAdmin { + if !user.(*core.User).IsAdmin { response.ToErrorResponse(errcode.NoPermission) return } - err = service.StickPost(param.ID) + err = broker.StickPost(param.ID) if err != nil { logrus.Errorf("service.StickPost err: %v\n", err) response.ToErrorResponse(errcode.LockPostFailed) @@ -287,7 +290,7 @@ func StickPost(c *gin.Context) { } func VisiblePost(c *gin.Context) { - param := service.PostVisibilityReq{} + param := broker.PostVisibilityReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -297,7 +300,7 @@ func VisiblePost(c *gin.Context) { } user, _ := userFrom(c) - if err := service.VisiblePost(user, param.ID, param.Visibility); err != nil { + if err := broker.VisiblePost(user, param.ID, param.Visibility); err != nil { logrus.Errorf("service.VisiblePost err: %v\n", err) response.ToErrorResponse(err) return @@ -309,7 +312,7 @@ func VisiblePost(c *gin.Context) { } func GetPostTags(c *gin.Context) { - param := service.PostTagsReq{} + param := broker.PostTagsReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -318,7 +321,7 @@ func GetPostTags(c *gin.Context) { return } - tags, err := service.GetPostTags(¶m) + tags, err := broker.GetPostTags(¶m) if err != nil { logrus.Errorf("service.GetPostTags err: %v\n", err) response.ToErrorResponse(errcode.GetPostTagsFailed) diff --git a/internal/routers/api/user.go b/internal/servants/web/routers/api/user.go similarity index 80% rename from internal/routers/api/user.go rename to internal/servants/web/routers/api/user.go index 7541c54b..f45ff8ce 100644 --- a/internal/routers/api/user.go +++ b/internal/servants/web/routers/api/user.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( @@ -6,9 +10,8 @@ import ( "unicode/utf8" "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" @@ -18,7 +21,7 @@ import ( // Login 用户登录 func Login(c *gin.Context) { - param := service.AuthRequest{} + param := broker.AuthRequest{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -27,7 +30,7 @@ func Login(c *gin.Context) { return } - user, err := service.DoLogin(c, ¶m) + user, err := broker.DoLogin(c, ¶m) if err != nil { logrus.Errorf("service.DoLogin err: %v", err) response.ToErrorResponse(err.(*errcode.Error)) @@ -49,7 +52,7 @@ func Login(c *gin.Context) { // Register 用户注册 func Register(c *gin.Context) { - param := service.RegisterRequest{} + param := broker.RegisterRequest{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -59,7 +62,7 @@ func Register(c *gin.Context) { } // 用户名检查 - err := service.ValidUsername(param.Username) + err := broker.ValidUsername(param.Username) if err != nil { logrus.Errorf("service.Register err: %v", err) response.ToErrorResponse(err.(*errcode.Error)) @@ -67,14 +70,14 @@ func Register(c *gin.Context) { } // 密码检查 - err = service.CheckPassword(param.Password) + err = broker.CheckPassword(param.Password) if err != nil { logrus.Errorf("service.Register err: %v", err) response.ToErrorResponse(err.(*errcode.Error)) return } - user, err := service.Register( + user, err := broker.Register( param.Username, param.Password, ) @@ -92,7 +95,7 @@ func Register(c *gin.Context) { } func RequestingFriend(c *gin.Context) { - param := rest.RequestingFriendReq{} + param := broker.RequestingFriendReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -110,7 +113,7 @@ func RequestingFriend(c *gin.Context) { return } - if err := service.RequestingFriend(user, ¶m); err != nil { + if err := broker.RequestingFriend(user, ¶m); err != nil { logrus.Errorf("service.RequestingFriend err: %v", err) response.ToErrorResponse(errcode.SendRequestingFriendFailed) return @@ -120,7 +123,7 @@ func RequestingFriend(c *gin.Context) { } func AddFriend(c *gin.Context) { - param := rest.AddFriendReq{} + param := broker.AddFriendReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -137,7 +140,7 @@ func AddFriend(c *gin.Context) { return } - if err := service.AddFriend(user, ¶m); err != nil { + if err := broker.AddFriend(user, ¶m); err != nil { logrus.Errorf("service.AddFriend err: %v", err) response.ToErrorResponse(errcode.AddFriendFailed) return @@ -147,7 +150,7 @@ func AddFriend(c *gin.Context) { } func RejectFriend(c *gin.Context) { - param := rest.RejectFriendReq{} + param := broker.RejectFriendReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -164,7 +167,7 @@ func RejectFriend(c *gin.Context) { return } - if err := service.RejectFriend(user, ¶m); err != nil { + if err := broker.RejectFriend(user, ¶m); err != nil { logrus.Errorf("service.RejectFriend err: %v", err) response.ToErrorResponse(errcode.RejectFriendFailed) return @@ -174,7 +177,7 @@ func RejectFriend(c *gin.Context) { } func DeleteFriend(c *gin.Context) { - param := rest.DeleteFriendReq{} + param := broker.DeleteFriendReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -191,7 +194,7 @@ func DeleteFriend(c *gin.Context) { return } - if err := service.DeleteFriend(user, ¶m); err != nil { + if err := broker.DeleteFriend(user, ¶m); err != nil { logrus.Errorf("service.DeleteFriend err: %v", err) response.ToErrorResponse(errcode.DeleteFriendFailed) return @@ -208,7 +211,7 @@ func GetContacts(c *gin.Context) { } offset, limit := app.GetPageOffset(c) - resp, err := service.GetContacts(user, offset, limit) + resp, err := broker.GetContacts(user, offset, limit) if err != nil { logrus.Errorf("service.DeleteFriend err: %v", err) response.ToErrorResponse(errcode.GetContactsFailed) @@ -219,14 +222,14 @@ func GetContacts(c *gin.Context) { // 获取用户基本信息 func GetUserInfo(c *gin.Context) { - param := service.AuthRequest{} + param := broker.AuthRequest{} response := app.NewResponse(c) if username, exists := c.Get("USERNAME"); exists { param.Username = username.(string) } - user, err := service.GetUserInfo(¶m) + user, err := broker.GetUserInfo(¶m) if err != nil { response.ToErrorResponse(errcode.UnauthorizedAuthNotExist) @@ -251,7 +254,7 @@ func GetUserInfo(c *gin.Context) { // 修改密码 func ChangeUserPassword(c *gin.Context) { - param := service.ChangePasswordReq{} + param := broker.ChangePasswordReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -260,13 +263,13 @@ func ChangeUserPassword(c *gin.Context) { return } - user := &model.User{} + user := &core.User{} if u, exists := c.Get("USER"); exists { - user = u.(*model.User) + user = u.(*core.User) } // 密码检查 - err := service.CheckPassword(param.Password) + err := broker.CheckPassword(param.Password) if err != nil { logrus.Errorf("service.Register err: %v", err) response.ToErrorResponse(err.(*errcode.Error)) @@ -274,21 +277,21 @@ func ChangeUserPassword(c *gin.Context) { } // 旧密码校验 - if !service.ValidPassword(user.Password, param.OldPassword, user.Salt) { + if !broker.ValidPassword(user.Password, param.OldPassword, user.Salt) { response.ToErrorResponse(errcode.ErrorOldPassword) return } // 更新入库 - user.Password, user.Salt = service.EncryptPasswordAndSalt(param.Password) - service.UpdateUserInfo(user) + user.Password, user.Salt = broker.EncryptPasswordAndSalt(param.Password) + broker.UpdateUserInfo(user) response.ToResponse(nil) } // 修改昵称 func ChangeNickname(c *gin.Context) { - param := service.ChangeNicknameReq{} + param := broker.ChangeNicknameReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -297,9 +300,9 @@ func ChangeNickname(c *gin.Context) { return } - user := &model.User{} + user := &core.User{} if u, exists := c.Get("USER"); exists { - user = u.(*model.User) + user = u.(*core.User) } if utf8.RuneCountInString(param.Nickname) < 2 || utf8.RuneCountInString(param.Nickname) > 12 { @@ -309,14 +312,14 @@ func ChangeNickname(c *gin.Context) { // 执行绑定 user.Nickname = param.Nickname - service.UpdateUserInfo(user) + broker.UpdateUserInfo(user) response.ToResponse(nil) } // 修改头像 func ChangeAvatar(c *gin.Context) { - param := service.ChangeAvatarReq{} + param := broker.ChangeAvatarReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -331,7 +334,7 @@ func ChangeAvatar(c *gin.Context) { return } - if err := service.ChangeUserAvatar(user, param.Avatar); err != nil { + if err := broker.ChangeUserAvatar(user, param.Avatar); err != nil { response.ToErrorResponse(err) return } @@ -340,7 +343,7 @@ func ChangeAvatar(c *gin.Context) { // 用户绑定手机号 func BindUserPhone(c *gin.Context) { - param := service.UserPhoneBindReq{} + param := broker.UserPhoneBindReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -349,18 +352,18 @@ func BindUserPhone(c *gin.Context) { return } - user := &model.User{} + user := &core.User{} if u, exists := c.Get("USER"); exists { - user = u.(*model.User) + user = u.(*core.User) } // 手机重复性检查 - if service.CheckPhoneExist(user.ID, param.Phone) { + if broker.CheckPhoneExist(user.ID, param.Phone) { response.ToErrorResponse(errcode.ExistedUserPhone) return } - if err := service.CheckPhoneCaptcha(param.Phone, param.Captcha); err != nil { + if err := broker.CheckPhoneCaptcha(param.Phone, param.Captcha); err != nil { logrus.Errorf("service.CheckPhoneCaptcha err: %v\n", err) response.ToErrorResponse(err) return @@ -368,7 +371,7 @@ func BindUserPhone(c *gin.Context) { // 执行绑定 user.Phone = param.Phone - if err := service.UpdateUserInfo(user); err != nil { + if err := broker.UpdateUserInfo(user); err != nil { response.ToErrorResponse(err) return } @@ -378,7 +381,7 @@ func BindUserPhone(c *gin.Context) { // 修改用户状态 func ChangeUserStatus(c *gin.Context) { - param := service.ChangeUserStatusReq{} + param := broker.ChangeUserStatusReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -387,12 +390,12 @@ func ChangeUserStatus(c *gin.Context) { return } - if param.Status != model.UserStatusNormal && param.Status != model.UserStatusClosed { + if param.Status != core.UserStatusNormal && param.Status != core.UserStatusClosed { response.ToErrorResponse(errcode.InvalidParams) return } - user, err := service.GetUserByID(param.ID) + user, err := broker.GetUserByID(param.ID) if err != nil { logrus.Errorf("service.GetUserByID err: %v\n", err) response.ToErrorResponse(errcode.NoExistUsername) @@ -401,7 +404,7 @@ func ChangeUserStatus(c *gin.Context) { // 执行更新 user.Status = param.Status - service.UpdateUserInfo(user) + broker.UpdateUserInfo(user) response.ToResponse(nil) } @@ -411,7 +414,7 @@ func GetUserProfile(c *gin.Context) { username := c.Query("username") user, _ := userFrom(c) - resp, err := service.GetUserByUsername(user, username) + resp, err := broker.GetUserByUsername(user, username) if err != nil { logrus.Errorf("service.GetUserByUsername err: %v\n", err) response.ToErrorResponse(errcode.NoExistUsername) @@ -426,28 +429,28 @@ func GetUserPosts(c *gin.Context) { username := c.Query("username") user, exists := userFrom(c) - other, err := service.GetUserByUsername(user, username) + other, err := broker.GetUserByUsername(user, username) if err != nil { logrus.Errorf("service.GetUserByUsername err: %v\n", err) response.ToErrorResponse(errcode.NoExistUsername) return } - visibilities := []model.PostVisibleT{model.PostVisitPublic} + visibilities := []core.PostVisibleT{core.PostVisitPublic} if exists { if user.ID == other.ID || user.IsAdmin { - visibilities = append(visibilities, model.PostVisitPrivate, model.PostVisitFriend) + visibilities = append(visibilities, core.PostVisitPrivate, core.PostVisitFriend) } else if other.IsFriend { - visibilities = append(visibilities, model.PostVisitFriend) + visibilities = append(visibilities, core.PostVisitFriend) } } - conditions := model.ConditionsT{ + conditions := core.ConditionsT{ "user_id": other.ID, "visibility IN ?": visibilities, "ORDER": "latest_replied_on DESC", } - _, posts, err := service.GetPostList(&service.PostListReq{ + _, posts, err := broker.GetPostList(&broker.PostListReq{ Conditions: &conditions, Offset: (app.GetPage(c) - 1) * app.GetPageSize(c), Limit: app.GetPageSize(c), @@ -457,7 +460,7 @@ func GetUserPosts(c *gin.Context) { response.ToErrorResponse(errcode.GetPostsFailed) return } - totalRows, _ := service.GetPostCount(&conditions) + totalRows, _ := broker.GetPostCount(&conditions) response.ToResponseList(posts, totalRows) } @@ -466,7 +469,7 @@ func GetUserCollections(c *gin.Context) { response := app.NewResponse(c) userID, _ := c.Get("UID") - posts, totalRows, err := service.GetUserCollections(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) + posts, totalRows, err := broker.GetUserCollections(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) if err != nil { logrus.Errorf("service.GetUserCollections err: %v\n", err) @@ -481,7 +484,7 @@ func GetUserStars(c *gin.Context) { response := app.NewResponse(c) userID, _ := c.Get("UID") - posts, totalRows, err := service.GetUserStars(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) + posts, totalRows, err := broker.GetUserStars(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) if err != nil { logrus.Errorf("service.GetUserStars err: %v\n", err) response.ToErrorResponse(errcode.GetCollectionsFailed) @@ -495,7 +498,7 @@ func GetSuggestUsers(c *gin.Context) { keyword := c.Query("k") response := app.NewResponse(c) - usernames, err := service.GetSuggestUsers(keyword) + usernames, err := broker.GetSuggestUsers(keyword) if err != nil { logrus.Errorf("service.GetSuggestUsers err: %v\n", err) response.ToErrorResponse(errcode.GetCollectionsFailed) @@ -509,7 +512,7 @@ func GetSuggestTags(c *gin.Context) { keyword := c.Query("k") response := app.NewResponse(c) - tags, err := service.GetSuggestTags(keyword) + tags, err := broker.GetSuggestTags(keyword) if err != nil { logrus.Errorf("service.GetSuggestTags err: %v\n", err) response.ToErrorResponse(errcode.GetCollectionsFailed) @@ -520,7 +523,7 @@ func GetSuggestTags(c *gin.Context) { } func GetUserRechargeLink(c *gin.Context) { - param := service.RechargeReq{} + param := broker.RechargeReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -531,7 +534,7 @@ func GetUserRechargeLink(c *gin.Context) { // 下单 userID, _ := c.Get("UID") - recharge, err := service.CreateRecharge(userID.(int64), param.Amount) + recharge, err := broker.CreateRecharge(userID.(int64), param.Amount) if err != nil { logrus.Errorf("service.CreateRecharge err: %v\n", err) response.ToErrorResponse(errcode.RechargeReqFail) @@ -567,7 +570,7 @@ func GetUserRechargeResult(c *gin.Context) { id := c.Query("id") userID, _ := c.Get("UID") - recharge, err := service.GetRechargeByID(convert.StrTo(id).MustInt64()) + recharge, err := broker.GetRechargeByID(convert.StrTo(id).MustInt64()) if err != nil { response.ToErrorResponse(errcode.GetRechargeFailed) return @@ -601,7 +604,7 @@ func AlipayNotify(c *gin.Context) { tradeStatus := c.Request.Form.Get("trade_status") if tradeStatus == "TRADE_SUCCESS" { // 交易支付成功 - err = service.FinishRecharge(c, convert.StrTo(id).MustInt64(), tradeNo) + err = broker.FinishRecharge(c, convert.StrTo(id).MustInt64(), tradeNo) if err != nil { logrus.Errorf("service.FinishRecharge err: %v\n", err) response.ToErrorResponse(errcode.RechargeNotifyError) @@ -615,7 +618,7 @@ func GetUserWalletBills(c *gin.Context) { response := app.NewResponse(c) userID, _ := c.Get("UID") - bills, totalRows, err := service.GetUserWalletBills(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) + bills, totalRows, err := broker.GetUserWalletBills(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) if err != nil { logrus.Errorf("service.GetUserWalletBills err: %v\n", err) @@ -626,9 +629,9 @@ func GetUserWalletBills(c *gin.Context) { response.ToResponseList(bills, totalRows) } -func userFrom(c *gin.Context) (*model.User, bool) { +func userFrom(c *gin.Context) (*core.User, bool) { if u, exists := c.Get("USER"); exists { - user, ok := u.(*model.User) + user, ok := u.(*core.User) return user, ok } return nil, false diff --git a/internal/routers/docs.go b/internal/servants/web/routers/docs.go similarity index 57% rename from internal/routers/docs.go rename to internal/servants/web/routers/docs.go index fc054b08..bf5e0488 100644 --- a/internal/routers/docs.go +++ b/internal/servants/web/routers/docs.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !docs // +build !docs diff --git a/internal/routers/docs_embed.go b/internal/servants/web/routers/docs_embed.go similarity index 69% rename from internal/routers/docs_embed.go rename to internal/servants/web/routers/docs_embed.go index e9c0d17d..a636e487 100644 --- a/internal/routers/docs_embed.go +++ b/internal/servants/web/routers/docs_embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build docs // +build docs diff --git a/internal/routers/router.go b/internal/servants/web/routers/router.go similarity index 92% rename from internal/routers/router.go rename to internal/servants/web/routers/router.go index 1a2b57f6..c020cec3 100644 --- a/internal/routers/router.go +++ b/internal/servants/web/routers/router.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package routers import ( @@ -7,8 +11,8 @@ import ( "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/middleware" - "github.com/rocboss/paopao-ce/internal/routers/api" + "github.com/rocboss/paopao-ce/internal/servants/chain" + "github.com/rocboss/paopao-ce/internal/servants/web/routers/api" "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) @@ -67,7 +71,7 @@ func NewRouter() *gin.Engine { } // 宽松鉴权路由组 - looseApi := r.Group("/").Use(middleware.JwtLoose()) + looseApi := r.Group("/").Use(chain.JwtLoose()) { // 获取广场流 looseApi.GET("/posts", api.GetPostList) @@ -80,9 +84,9 @@ func NewRouter() *gin.Engine { } // 鉴权路由组 - authApi := r.Group("/").Use(middleware.JWT()) - privApi := r.Group("/").Use(middleware.JWT()).Use(middleware.Priv()) - adminApi := r.Group("/").Use(middleware.JWT()).Use(middleware.Admin()) + authApi := r.Group("/").Use(chain.JWT()) + privApi := r.Group("/").Use(chain.JWT()).Use(chain.Priv()) + adminApi := r.Group("/").Use(chain.JWT()).Use(chain.Admin()) // 核心路由注册 routeCore(authApi, privApi, adminApi) diff --git a/internal/routers/statick.go b/internal/servants/web/routers/statick.go similarity index 58% rename from internal/routers/statick.go rename to internal/servants/web/routers/statick.go index c20d5059..c1f2d1cb 100644 --- a/internal/routers/statick.go +++ b/internal/servants/web/routers/statick.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !embed // +build !embed diff --git a/internal/routers/statick_embed.go b/internal/servants/web/routers/statick_embed.go similarity index 79% rename from internal/routers/statick_embed.go rename to internal/servants/web/routers/statick_embed.go index 2ea56171..dfc729f5 100644 --- a/internal/routers/statick_embed.go +++ b/internal/servants/web/routers/statick_embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build embed // +build embed diff --git a/internal/servants/web/web.go b/internal/servants/web/web.go index 60a0aeb1..76ac9dd3 100644 --- a/internal/servants/web/web.go +++ b/internal/servants/web/web.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web import ( diff --git a/internal/servants/web/xerror.go b/internal/servants/web/xerror.go index 305d1d0c..ecc0355e 100644 --- a/internal/servants/web/xerror.go +++ b/internal/servants/web/xerror.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package web import ( diff --git a/internal/service/attachment.go b/internal/service/attachment.go deleted file mode 100644 index 432a1a2f..00000000 --- a/internal/service/attachment.go +++ /dev/null @@ -1,7 +0,0 @@ -package service - -import "github.com/rocboss/paopao-ce/internal/model" - -func CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) { - return ds.CreateAttachment(attachment) -} diff --git a/internal/service/service.go b/internal/service/service.go index 4f9434f4..84c9ec7a 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -1,72 +1,17 @@ -package service - -import ( - "net/http" +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. - "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/dao" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/servants" - "github.com/rocboss/paopao-ce/pkg/cfg" - "github.com/sirupsen/logrus" -) - -var ( - ds core.DataService - ts core.TweetSearchService - oss core.ObjectStorageService - DisablePhoneVerify bool -) +package service type Service interface { Name() string - PreStart() string - PreStop() string Start() Stop() } -func NewWebService() Service { - e := newWebEngine() - servants.RegisterWebServants(e) - - return &webService{ - server: &http.Server{ - Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort, - Handler: e, - ReadTimeout: conf.ServerSetting.ReadTimeout, - WriteTimeout: conf.ServerSetting.WriteTimeout, - MaxHeaderBytes: 1 << 20, - }, - } -} - -func Initialize() { - ds = dao.DataService() - ts = dao.TweetSearchService() - oss = dao.ObjectStorageService() - DisablePhoneVerify = !cfg.If("Sms") -} +type baseService struct{} -// persistMediaContents 获取媒体内容并持久化 -func persistMediaContents(contents []*PostContentItem) (items []string, err error) { - items = make([]string, 0, len(contents)) - for _, item := range contents { - switch item.Type { - case model.CONTENT_TYPE_IMAGE, - model.CONTENT_TYPE_VIDEO, - model.CONTENT_TYPE_AUDIO, - model.CONTENT_TYPE_ATTACHMENT, - model.CONTENT_TYPE_CHARGE_ATTACHMENT: - items = append(items, item.Content) - if err != nil { - continue - } - if err = oss.PersistObject(oss.ObjectKey(item.Content)); err != nil { - logrus.Errorf("service.persistMediaContents failed: %s", err) - } - } - } - return +func (baseService) String() string { + return "" } diff --git a/internal/service/web.go b/internal/service/web.go index d346fbd8..a64a6f73 100644 --- a/internal/service/web.go +++ b/internal/service/web.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package service import ( @@ -10,24 +14,15 @@ import ( "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/servants" ) -type baseService struct{} - type webService struct { baseService server *http.Server } -func (baseService) PreStart() string { - return "" -} - -func (baseService) PreStop() string { - return "" -} - func (s *webService) Name() string { return "WebService" } @@ -42,7 +37,7 @@ func (s *webService) Stop() { s.server.Shutdown(context.Background()) } -func (s *webService) PreStart() string { +func (s *webService) String() string { return fmt.Sprintf("PaoPao service listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)) } @@ -76,3 +71,17 @@ func newWebEngine() *gin.Engine { return e } + +func NewWebService() Service { + e := newWebEngine() + servants.RegisterWebServants(e) + return &webService{ + server: &http.Server{ + Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort, + Handler: e, + ReadTimeout: conf.ServerSetting.ReadTimeout, + WriteTimeout: conf.ServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } +} diff --git a/main.go b/main.go index 1046e97d..0d28b464 100644 --- a/main.go +++ b/main.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package main import ( @@ -11,7 +15,7 @@ import ( "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/routers" + "github.com/rocboss/paopao-ce/internal/servants/web/routers" "github.com/rocboss/paopao-ce/pkg/debug" "github.com/rocboss/paopao-ce/pkg/util" ) diff --git a/pkg/app/app.go b/pkg/app/app.go index fc860d27..a98a49a2 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package app import ( diff --git a/pkg/app/form.go b/pkg/app/form.go index 7e376104..91b116a2 100644 --- a/pkg/app/form.go +++ b/pkg/app/form.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package app import ( diff --git a/pkg/app/jwt.go b/pkg/app/jwt.go index 8033296f..b9759e07 100644 --- a/pkg/app/jwt.go +++ b/pkg/app/jwt.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package app import ( @@ -5,7 +9,7 @@ import ( "github.com/golang-jwt/jwt/v4" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" ) type Claims struct { @@ -18,7 +22,7 @@ func GetJWTSecret() []byte { return []byte(conf.JWTSetting.Secret) } -func GenerateToken(User *model.User) (string, error) { +func GenerateToken(User *core.User) (string, error) { expireTime := time.Now().Add(conf.JWTSetting.Expire) claims := Claims{ UID: User.ID, diff --git a/pkg/app/pagination.go b/pkg/app/pagination.go index 1888efb9..699d1dd2 100644 --- a/pkg/app/pagination.go +++ b/pkg/app/pagination.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package app import ( diff --git a/pkg/cfg/cfg.go b/pkg/cfg/cfg.go index 019deba9..f04dc297 100644 --- a/pkg/cfg/cfg.go +++ b/pkg/cfg/cfg.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cfg var ( diff --git a/pkg/cfg/cfg_test.go b/pkg/cfg/cfg_test.go index 0fccbce2..68a3ce74 100644 --- a/pkg/cfg/cfg_test.go +++ b/pkg/cfg/cfg_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cfg import ( diff --git a/pkg/cfg/feature.go b/pkg/cfg/feature.go index a04d07ca..32810b47 100644 --- a/pkg/cfg/feature.go +++ b/pkg/cfg/feature.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cfg import ( diff --git a/pkg/cfg/feature_test.go b/pkg/cfg/feature_test.go index 98e01ec7..21c44c72 100644 --- a/pkg/cfg/feature_test.go +++ b/pkg/cfg/feature_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cfg import ( diff --git a/pkg/convert/convert.go b/pkg/convert/convert.go index 60dacf9b..ff3be5e5 100644 --- a/pkg/convert/convert.go +++ b/pkg/convert/convert.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package convert import "strconv" diff --git a/pkg/convert/convert_test.go b/pkg/convert/convert_test.go index a746e3e7..a31d13e6 100644 --- a/pkg/convert/convert_test.go +++ b/pkg/convert/convert_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package convert import ( diff --git a/pkg/crypto/signature.go b/pkg/crypto/signature.go index 7f18959a..20a6deaa 100644 --- a/pkg/crypto/signature.go +++ b/pkg/crypto/signature.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package crypto import ( diff --git a/pkg/debug/version.go b/pkg/debug/version.go index 485e8046..68236f05 100644 --- a/pkg/debug/version.go +++ b/pkg/debug/version.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package debug import ( diff --git a/pkg/errcode/common_code.go b/pkg/errcode/common_code.go index 75b220ee..1f15f8c5 100644 --- a/pkg/errcode/common_code.go +++ b/pkg/errcode/common_code.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package errcode var ( diff --git a/pkg/errcode/errcode.go b/pkg/errcode/errcode.go index 50f04868..5143aabb 100644 --- a/pkg/errcode/errcode.go +++ b/pkg/errcode/errcode.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package errcode import ( diff --git a/pkg/errcode/module_code.go b/pkg/errcode/module_code.go index 1c5b7215..9543624b 100644 --- a/pkg/errcode/module_code.go +++ b/pkg/errcode/module_code.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package errcode var ( diff --git a/pkg/sign/sign.go b/pkg/sign/sign.go index 717b8e54..fc7c10e9 100644 --- a/pkg/sign/sign.go +++ b/pkg/sign/sign.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package sign import ( diff --git a/pkg/types/types.go b/pkg/types/types.go index 2696f8b9..830c56c6 100644 --- a/pkg/types/types.go +++ b/pkg/types/types.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package types // Empty empty alias type diff --git a/pkg/util/banner.go b/pkg/util/banner.go index d41b5ae1..31e25ba9 100644 --- a/pkg/util/banner.go +++ b/pkg/util/banner.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import "fmt" diff --git a/pkg/util/ip.go b/pkg/util/ip.go index 3aaa13c1..4561d8a6 100644 --- a/pkg/util/ip.go +++ b/pkg/util/ip.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import "github.com/rocboss/paopao-ce/pkg/util/iploc" diff --git a/pkg/util/ip_test.go b/pkg/util/ip_test.go index 82976be8..0740ffd5 100644 --- a/pkg/util/ip_test.go +++ b/pkg/util/ip_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import "testing" diff --git a/pkg/util/iploc/iploc.go b/pkg/util/iploc/iploc.go index a05f8d7e..449e52a9 100644 --- a/pkg/util/iploc/iploc.go +++ b/pkg/util/iploc/iploc.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package iploc import ( diff --git a/pkg/util/iploc/iploc_test.go b/pkg/util/iploc/iploc_test.go index 4754e86d..a38bb106 100644 --- a/pkg/util/iploc/iploc_test.go +++ b/pkg/util/iploc/iploc_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package iploc import ( diff --git a/pkg/util/md5.go b/pkg/util/md5.go index 8a00f545..477cd5ff 100644 --- a/pkg/util/md5.go +++ b/pkg/util/md5.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import ( diff --git a/pkg/util/md5_test.go b/pkg/util/md5_test.go index 0bab593f..12c14c86 100644 --- a/pkg/util/md5_test.go +++ b/pkg/util/md5_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import "testing" diff --git a/pkg/util/str.go b/pkg/util/str.go index 35e034ab..8b62217d 100644 --- a/pkg/util/str.go +++ b/pkg/util/str.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import ( diff --git a/pkg/xerror/common.go b/pkg/xerror/common.go index a59c62e8..b502840b 100644 --- a/pkg/xerror/common.go +++ b/pkg/xerror/common.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package xerror var ( diff --git a/pkg/xerror/xerror.go b/pkg/xerror/xerror.go index 5053b62f..f614d18e 100644 --- a/pkg/xerror/xerror.go +++ b/pkg/xerror/xerror.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package xerror import ( diff --git a/pkg/zinc/zinc.go b/pkg/zinc/zinc.go index ba1fb270..cc200a55 100644 --- a/pkg/zinc/zinc.go +++ b/pkg/zinc/zinc.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package zinc import ( diff --git a/scripts/migration/embed.go b/scripts/migration/embed.go index 88e633c8..3f1eacda 100644 --- a/scripts/migration/embed.go +++ b/scripts/migration/embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build migration // +build migration diff --git a/web/embed.go b/web/embed.go index 4866a53a..a16df24a 100644 --- a/web/embed.go +++ b/web/embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build embed // +build embed From 1125487bbcc6070dcaa341cf8bbbcbd79ae55cf7 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 3 Dec 2022 00:30:17 +0800 Subject: [PATCH 12/28] mir: move mirgration module to internal pkg --- internal/broker/broker.go | 5 ----- internal/internal.go | 6 +++--- internal/{broker => }/migration/migration.go | 0 internal/{broker => }/migration/migration_embed.go | 0 4 files changed, 3 insertions(+), 8 deletions(-) delete mode 100644 internal/broker/broker.go rename internal/{broker => }/migration/migration.go (100%) rename internal/{broker => }/migration/migration_embed.go (100%) diff --git a/internal/broker/broker.go b/internal/broker/broker.go deleted file mode 100644 index a47462c1..00000000 --- a/internal/broker/broker.go +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright 2022 ROC. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package broker diff --git a/internal/internal.go b/internal/internal.go index e359af0d..a8c0934f 100644 --- a/internal/internal.go +++ b/internal/internal.go @@ -5,8 +5,8 @@ package internal import ( - "github.com/rocboss/paopao-ce/internal/broker/migration" - wb "github.com/rocboss/paopao-ce/internal/servants/web/broker" + "github.com/rocboss/paopao-ce/internal/migration" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/internal/servants/web/routers/api" ) @@ -15,6 +15,6 @@ func Initialize() { migration.Run() // initialize service - wb.Initialize() + broker.Initialize() api.Initialize() } diff --git a/internal/broker/migration/migration.go b/internal/migration/migration.go similarity index 100% rename from internal/broker/migration/migration.go rename to internal/migration/migration.go diff --git a/internal/broker/migration/migration_embed.go b/internal/migration/migration_embed.go similarity index 100% rename from internal/broker/migration/migration_embed.go rename to internal/migration/migration_embed.go From 6570286a4ef40e1e3200d5f711c9cbb1a56f0a21 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Fri, 9 Dec 2022 19:27:28 +0800 Subject: [PATCH 13/28] add internal/service base logic --- .../mirc/auto/api/v1/{site.go => web_core.go} | 115 ++++++++++-------- internal/mirc/main.go | 2 +- internal/mirc/routes/v1/web_core.go | 2 +- internal/servants/servants.go | 16 +-- internal/service/http_server.go | 83 +++++++++++++ internal/service/http_service.go | 49 ++++++++ internal/service/service.go | 28 ++++- internal/service/web.go | 42 +++---- 8 files changed, 246 insertions(+), 91 deletions(-) rename internal/mirc/auto/api/v1/{site.go => web_core.go} (93%) create mode 100644 internal/service/http_server.go create mode 100644 internal/service/http_service.go diff --git a/internal/mirc/auto/api/v1/site.go b/internal/mirc/auto/api/v1/web_core.go similarity index 93% rename from internal/mirc/auto/api/v1/site.go rename to internal/mirc/auto/api/v1/web_core.go index 22e9e826..5887e010 100644 --- a/internal/mirc/auto/api/v1/site.go +++ b/internal/mirc/auto/api/v1/web_core.go @@ -6,14 +6,26 @@ import ( "net/http" "github.com/alimy/mir/v3" - "github.com/gin-gonic/gin" + gin "github.com/gin-gonic/gin" ) +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + type AgentInfo struct { Platform string `json:"platform"` UserAgent string `json:"user_agent"` } +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + type ServerInfo struct { ApiVer string `json:"api_ver"` } @@ -22,26 +34,14 @@ type UserInfo struct { Name string `json:"name"` } -type LoginReq struct { - AgentInfo AgentInfo `json:"agent_info"` - Name string `json:"name"` - Passwd string `json:"passwd"` -} - -type LoginResp struct { - UserInfo - ServerInfo ServerInfo `json:"server_info"` - JwtToken string `json:"jwt_token"` -} - type WebCore interface { // Chain provide handlers chain for gin Chain() gin.HandlersChain - Index(c *gin.Context) mir.Error - Articles(c *gin.Context) mir.Error - Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) Logout(c *gin.Context) mir.Error + Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + Articles(c *gin.Context) mir.Error + Index(c *gin.Context) mir.Error mustEmbedUnimplementedWebCoreServant() } @@ -53,10 +53,10 @@ type WebCoreBinding interface { } type WebCoreRender interface { - RenderIndex(c *gin.Context, err mir.Error) - RenderArticles(c *gin.Context, err mir.Error) - RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) RenderLogout(c *gin.Context, err mir.Error) + RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + RenderArticles(c *gin.Context, err mir.Error) + RenderIndex(c *gin.Context, err mir.Error) mustEmbedUnimplementedWebCoreRender() } @@ -69,12 +69,10 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor router.Use(middlewares...) // register routes info to router - router.Handle("GET", "/index/", func(c *gin.Context) { - r.RenderIndex(c, s.Index(c)) - }) - router.Handle("GET", "/articles/:category/", func(c *gin.Context) { - r.RenderArticles(c, s.Articles(c)) + router.Handle("POST", "/user/logout/", func(c *gin.Context) { + r.RenderLogout(c, s.Logout(c)) }) + router.Handle("POST", "/user/login/", func(c *gin.Context) { req, err := b.BindLogin(c) if err != nil { @@ -83,33 +81,30 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor resp, err := s.Login(c, req) r.RenderLogin(c, resp, err) }) - router.Handle("POST", "/user/logout/", func(c *gin.Context) { - r.RenderLogout(c, s.Logout(c)) - }) -} -// UnimplementedWebCoreServant can be embedded to have forward compatible implementations. -type UnimplementedWebCoreServant struct{} + { + h := func(c *gin.Context) { + r.RenderArticles(c, s.Articles(c)) + } + router.Handle("HEAD", "/articles/:category/", h) + router.Handle("GET", "/articles/:category/", h) + } + + router.Handle("GET", "/index/", func(c *gin.Context) { + r.RenderIndex(c, s.Index(c)) + }) -// UnimplementedWebCoreBinding can be embedded to have forward compatible implementations. -type UnimplementedWebCoreBinding struct { - BindAny func(*gin.Context, any) mir.Error } -// UnimplementedWebCoreRender can be embedded to have forward compatible implementations. -type UnimplementedWebCoreRender struct { - RenderAny func(*gin.Context, any, mir.Error) +// UnimplementedWebCoreServant can be embedded to have forward compatible implementations. +type UnimplementedWebCoreServant struct { } func (UnimplementedWebCoreServant) Chain() gin.HandlersChain { return nil } -func (UnimplementedWebCoreServant) Index(c *gin.Context) mir.Error { - return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) -} - -func (UnimplementedWebCoreServant) Articles(c *gin.Context) mir.Error { +func (UnimplementedWebCoreServant) Logout(c *gin.Context) mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } @@ -117,25 +112,22 @@ func (UnimplementedWebCoreServant) Login(c *gin.Context, req *LoginReq) (*LoginR return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedWebCoreServant) Logout(c *gin.Context) mir.Error { +func (UnimplementedWebCoreServant) Articles(c *gin.Context) mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedWebCoreServant) mustEmbedUnimplementedWebCoreServant() {} - -func (b *UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) { - obj := new(LoginReq) - err := b.BindAny(c, obj) - return obj, err +func (UnimplementedWebCoreServant) Index(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (b *UnimplementedWebCoreBinding) mustEmbedUnimplementedWebCoreBinding() {} +func (UnimplementedWebCoreServant) mustEmbedUnimplementedWebCoreServant() {} -func (r *UnimplementedWebCoreRender) RenderIndex(c *gin.Context, err mir.Error) { - r.RenderAny(c, nil, err) +// UnimplementedWebCoreRender can be embedded to have forward compatible implementations. +type UnimplementedWebCoreRender struct { + RenderAny func(*gin.Context, any, mir.Error) } -func (r *UnimplementedWebCoreRender) RenderArticles(c *gin.Context, err mir.Error) { +func (r *UnimplementedWebCoreRender) RenderLogout(c *gin.Context, err mir.Error) { r.RenderAny(c, nil, err) } @@ -143,8 +135,25 @@ func (r *UnimplementedWebCoreRender) RenderLogin(c *gin.Context, data *LoginResp r.RenderAny(c, data, err) } -func (r *UnimplementedWebCoreRender) RenderLogout(c *gin.Context, err mir.Error) { +func (r *UnimplementedWebCoreRender) RenderArticles(c *gin.Context, err mir.Error) { + r.RenderAny(c, nil, err) +} + +func (r *UnimplementedWebCoreRender) RenderIndex(c *gin.Context, err mir.Error) { r.RenderAny(c, nil, err) } func (r *UnimplementedWebCoreRender) mustEmbedUnimplementedWebCoreRender() {} + +// UnimplementedWebCoreBinding can be embedded to have forward compatible implementations. +type UnimplementedWebCoreBinding struct { + BindAny func(*gin.Context, any) mir.Error +} + +func (b *UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) { + obj := new(LoginReq) + err := b.BindAny(c, obj) + return obj, err +} + +func (b *UnimplementedWebCoreBinding) mustEmbedUnimplementedWebCoreBinding() {} diff --git a/internal/mirc/main.go b/internal/mirc/main.go index 46de42d1..bf45791f 100644 --- a/internal/mirc/main.go +++ b/internal/mirc/main.go @@ -17,7 +17,7 @@ import ( func main() { log.Println("generate code start") opts := Options{ - RunMode(InSerialMode), + RunMode(InSerialDebugMode), GeneratorName(GeneratorGin), SinkPath("auto"), } diff --git a/internal/mirc/routes/v1/web_core.go b/internal/mirc/routes/v1/web_core.go index 565fb04a..83193986 100644 --- a/internal/mirc/routes/v1/web_core.go +++ b/internal/mirc/routes/v1/web_core.go @@ -38,7 +38,7 @@ type WebCore struct { Chain Chain `mir:"-"` Group Group `mir:"v1"` Index func(Get) `mir:"/index/"` - Articles func(Get) `mir:"/articles/:category/"` + Articles func(Get, Head) `mir:"/articles/:category/"` Login func(Post, LoginReq) LoginResp `mir:"/user/login/"` Logout func(Post) `mir:"/user/logout/"` } diff --git a/internal/servants/servants.go b/internal/servants/servants.go index 4f1f0bcd..9ae3d0a7 100644 --- a/internal/servants/servants.go +++ b/internal/servants/servants.go @@ -15,16 +15,12 @@ import ( // RegisterWebServants register all the servants to gin.Engine func RegisterWebServants(e *gin.Engine) { - // 按需注册 docs、静态资源 - { - docs.RegisterDocs(e) - statick.RegisterStatick(e) - } + docs.RegisterDocs(e) + statick.RegisterStatick(e) + + cfg.Be("LocalOSS", func() { + localoss.RouteLocalOSS(e) + }) web.RouteWeb(e) - { - cfg.Be("LocalOSS", func() { - localoss.RouteLocalOSS(e) - }) - } } diff --git a/internal/service/http_server.go b/internal/service/http_server.go new file mode 100644 index 00000000..4a8fdf3b --- /dev/null +++ b/internal/service/http_server.go @@ -0,0 +1,83 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "context" + "net/http" + "sync" + + "github.com/gin-gonic/gin" +) + +var ( + httpServers = make(map[string]*httpServer) +) + +const ( + httpServerInitilized uint8 = iota + 1 + httpServerStarted + httpServerStoped +) + +// httpServer wraper for gin.engine and http.Server +type httpServer struct { + sync.RWMutex + + e *gin.Engine + server *http.Server + serverStatus uint8 +} + +func (s *httpServer) status() uint8 { + s.RLock() + defer s.RUnlock() + + return s.serverStatus +} + +func (s *httpServer) start() error { + s.Lock() + if s.serverStatus == httpServerStarted || s.serverStatus == httpServerStoped { + return nil + } + oldStatus := s.serverStatus + s.serverStatus = httpServerStarted + s.Unlock() + + if err := s.server.ListenAndServe(); err != nil { + s.Lock() + s.serverStatus = oldStatus + s.Unlock() + + return err + } + return nil +} + +func (s *httpServer) stop() error { + s.Lock() + defer s.Unlock() + + if s.serverStatus == httpServerStoped || s.serverStatus == httpServerInitilized { + return nil + } + if err := s.server.Shutdown(context.Background()); err != nil { + return err + } + s.serverStatus = httpServerStoped + return nil +} + +func httpServerFrom(addr string, newServer func() *httpServer) *httpServer { + s, exist := httpServers[addr] + if exist { + return s + } + s = newServer() + s.serverStatus = httpServerInitilized + httpServers[addr] = s + return s +} diff --git a/internal/service/http_service.go b/internal/service/http_service.go new file mode 100644 index 00000000..11ec1b98 --- /dev/null +++ b/internal/service/http_service.go @@ -0,0 +1,49 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "github.com/gin-gonic/gin" +) + +type httpService interface { + Service + + registerRoute(e *gin.Engine) +} + +type baseHttpService struct { + baseService + + server *httpServer +} + +func (s *baseHttpService) Init() error { + if s.server.status() != httpServerStarted { + s.registerRoute(s.server.e) + } + return nil +} + +func (s *baseHttpService) Start() error { + if err := s.server.start(); err != nil { + return err + } + return nil +} + +func (s *baseHttpService) Stop() error { + return s.server.stop() +} + +func (s *baseHttpService) registerRoute(e *gin.Engine) { + // default empty +} + +func newBaseHttpService(s *httpServer) httpService { + return &baseHttpService{ + server: s, + } +} diff --git a/internal/service/service.go b/internal/service/service.go index 84c9ec7a..31efbae0 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -4,14 +4,36 @@ package service +import ( + "log" + + "github.com/rocboss/paopao-ce/pkg/types" +) + type Service interface { Name() string - Start() - Stop() + Init() error + Start() error + Stop() error } -type baseService struct{} +type baseService types.Empty + +func (baseService) Name() string { + return "" +} func (baseService) String() string { return "" } + +func InitService() (ss []Service) { + ss = append(ss, newWebService()) + + for _, s := range ss { + if err := s.Init(); err != nil { + log.Fatalf("initial %s service error: %s", s.Name(), err) + } + } + return +} diff --git a/internal/service/web.go b/internal/service/web.go index a64a6f73..6ded25d3 100644 --- a/internal/service/web.go +++ b/internal/service/web.go @@ -5,9 +5,7 @@ package service import ( - "context" "fmt" - "log" "net/http" "github.com/fatih/color" @@ -18,23 +16,15 @@ import ( ) type webService struct { - baseService - - server *http.Server + httpService } func (s *webService) Name() string { return "WebService" } -func (s *webService) Start() { - if err := s.server.ListenAndServe(); err != nil { - log.Fatalf("run app failed: %s", err) - } -} - -func (s *webService) Stop() { - s.server.Shutdown(context.Background()) +func (s *webService) registerRoute(e *gin.Engine) { + servants.RegisterWebServants(e) } func (s *webService) String() string { @@ -72,16 +62,22 @@ func newWebEngine() *gin.Engine { return e } -func NewWebService() Service { - e := newWebEngine() - servants.RegisterWebServants(e) +func newWebService() Service { + addr := conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort + server := httpServerFrom(addr, func() *httpServer { + engine := newWebEngine() + return &httpServer{ + e: engine, + server: &http.Server{ + Addr: addr, + Handler: engine, + ReadTimeout: conf.ServerSetting.ReadTimeout, + WriteTimeout: conf.ServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } + }) return &webService{ - server: &http.Server{ - Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort, - Handler: e, - ReadTimeout: conf.ServerSetting.ReadTimeout, - WriteTimeout: conf.ServerSetting.WriteTimeout, - MaxHeaderBytes: 1 << 20, - }, + httpService: newBaseHttpService(server), } } From 3c47f48c429d92a6e00eccb45de7c8bc45e1d57d Mon Sep 17 00:00:00 2001 From: Michael Li Date: Fri, 9 Dec 2022 23:37:23 +0800 Subject: [PATCH 14/28] optimize main initial logic for new service init --- config.yaml.sample | 12 +++++ go.mod | 6 +-- go.sum | 2 + internal/conf/conf.go | 11 ++++ internal/conf/settting.go | 1 + internal/servants/web/routers/router.go | 72 +++++++++++++++++++++++++ internal/service/http_service.go | 21 +------- internal/service/service.go | 2 +- internal/service/web.go | 19 ++++--- internal/service/web_old.go | 53 ++++++++++++++++++ main.go | 53 ++++++++++++------ pkg/xerror/common.go | 4 -- 12 files changed, 202 insertions(+), 54 deletions(-) create mode 100644 internal/service/web_old.go diff --git a/config.yaml.sample b/config.yaml.sample index d776769b..1126bcec 100644 --- a/config.yaml.sample +++ b/config.yaml.sample @@ -1,4 +1,5 @@ App: # APP基础设置项 + RunMode: debug AttachmentIncomeRate: 0.8 MaxCommentCount: 10 DefaultContextTimeout: 60 @@ -17,8 +18,19 @@ Features: Slim: ["Base", "Sqlite3", "LocalOSS", "LoggerFile", "OSS:TempDir"] Base: ["Redis", "PhoneBind"] Docs: ["Docs:OpenAPI"] + Deprecated: ["Deprecated:OldWeb"] Option: ["SimpleCacheIndex"] Sms: "SmsJuhe" +WebServer: # Web服务 + HttpIp: 0.0.0.0 + HttpPort: 8010 + ReadTimeout: 60 + WriteTimeout: 60 +DocsServer: # 开发文档服务 + HttpIp: 0.0.0.0 + HttpPort: 8011 + ReadTimeout: 60 + WriteTimeout: 60 SmsJuhe: Gateway: https://v.juhe.cn/sms/send Key: diff --git a/go.mod b/go.mod index 8e3819e5..83348535 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.18 require ( github.com/Masterminds/semver/v3 v3.1.1 github.com/afocus/captcha v0.0.0-20191010092841-4bd1f21c8868 + github.com/alimy/mir/v3 v3.0.0-alpha.3 github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible github.com/allegro/bigcache/v3 v3.0.2 github.com/bytedance/sonic v1.5.0 @@ -39,7 +40,6 @@ require ( gorm.io/plugin/dbresolver v1.1.0 gorm.io/plugin/soft_delete v1.1.0 modernc.org/sqlite v1.17.3 - github.com/alimy/mir/v3 v3.0.0 ) require ( @@ -132,7 +132,3 @@ require ( modernc.org/strutil v1.1.1 // indirect modernc.org/token v1.0.0 // indirect ) - -replace ( - github.com/alimy/mir/v3 => ../../alimy/mir -) \ No newline at end of file diff --git a/go.sum b/go.sum index 9221a97a..84ae8631 100644 --- a/go.sum +++ b/go.sum @@ -142,6 +142,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk= +github.com/alimy/mir/v3 v3.0.0-alpha.3 h1:/GyBC0G041NIP3W62im8DtAwxRPSfSaivSQK6MV9fFc= +github.com/alimy/mir/v3 v3.0.0-alpha.3/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= diff --git a/internal/conf/conf.go b/internal/conf/conf.go index bbc8438c..1cffa824 100644 --- a/internal/conf/conf.go +++ b/internal/conf/conf.go @@ -24,6 +24,8 @@ var ( PostgresSetting *PostgresSettingS Sqlite3Setting *Sqlite3SettingS ServerSetting *ServerSettingS + WebServerSetting *ServerSettingS + DocsServerSetting *ServerSettingS AppSetting *AppSettingS CacheIndexSetting *CacheIndexSettingS SimpleCacheIndexSetting *SimpleCacheIndexSettingS @@ -60,6 +62,8 @@ func setupSetting(suite []string, noDefault bool) error { objects := map[string]any{ "App": &AppSetting, "Server": &ServerSetting, + "WebServer": &WebServerSetting, + "DocsServer": &DocsServerSetting, "CacheIndex": &CacheIndexSetting, "SimpleCacheIndex": &SimpleCacheIndexSetting, "BigCacheIndex": &BigCacheIndexSetting, @@ -138,3 +142,10 @@ func GetOssDomain() string { } return uri + AliOSSSetting.Domain + "/" } + +func RunMode() string { + if !cfg.If("Deprecated:OldWeb") { + return ServerSetting.RunMode + } + return AppSetting.RunMode +} diff --git a/internal/conf/settting.go b/internal/conf/settting.go index da3d97b6..e5841c51 100644 --- a/internal/conf/settting.go +++ b/internal/conf/settting.go @@ -54,6 +54,7 @@ type ServerSettingS struct { } type AppSettingS struct { + RunMode string MaxCommentCount int64 AttachmentIncomeRate float64 DefaultContextTimeout time.Duration diff --git a/internal/servants/web/routers/router.go b/internal/servants/web/routers/router.go index c020cec3..e46b533b 100644 --- a/internal/servants/web/routers/router.go +++ b/internal/servants/web/routers/router.go @@ -118,6 +118,78 @@ func NewRouter() *gin.Engine { return e } +func RegisterRoute(e *gin.Engine) { + // 按需注册 docs、静态资源、LocalOSS 路由 + { + registerDocs(e) + registerStatick(e) + + cfg.Be("LocalOSS", func() { + routeLocalOSS(e) + }) + } + + // v1 group api + r := e.Group("/v1") + + // 获取version + r.GET("/", api.Version) + + // 用户登录 + r.POST("/auth/login", api.Login) + + // 用户注册 + r.POST("/auth/register", api.Register) + + // 获取验证码 + r.GET("/captcha", api.GetCaptcha) + + // 发送验证码 + r.POST("/captcha", api.PostCaptcha) + + // 无鉴权路由组 + noAuthApi := r.Group("/") + { + // 获取动态详情 + noAuthApi.GET("/post", api.GetPost) + + // 获取动态评论 + noAuthApi.GET("/post/comments", api.GetPostComments) + + // 获取话题列表 + noAuthApi.GET("/tags", api.GetPostTags) + } + + // 宽松鉴权路由组 + looseApi := r.Group("/").Use(chain.JwtLoose()) + { + // 获取广场流 + looseApi.GET("/posts", api.GetPostList) + + // 获取用户动态列表 + looseApi.GET("/user/posts", api.GetUserPosts) + + // 获取用户基本信息 + looseApi.GET("/user/profile", api.GetUserProfile) + } + + // 鉴权路由组 + authApi := r.Group("/").Use(chain.JWT()) + privApi := r.Group("/").Use(chain.JWT()).Use(chain.Priv()) + adminApi := r.Group("/").Use(chain.JWT()).Use(chain.Admin()) + + // 核心路由注册 + routeCore(authApi, privApi, adminApi) + + // 支付宝路由注册 + cfg.Be("Alipay", func() { + routeAlipay(r, authApi) + }) + + // Relationship相关路由注册 + routeRelationship(authApi) +} + func routeCore(authApi gin.IRoutes, privApi gin.IRoutes, adminApi gin.IRoutes) { // 同步索引 authApi.GET("/sync/index", api.SyncSearchIndex) diff --git a/internal/service/http_service.go b/internal/service/http_service.go index 11ec1b98..fc7ce9b6 100644 --- a/internal/service/http_service.go +++ b/internal/service/http_service.go @@ -8,23 +8,16 @@ import ( "github.com/gin-gonic/gin" ) -type httpService interface { - Service - - registerRoute(e *gin.Engine) -} - type baseHttpService struct { baseService server *httpServer } -func (s *baseHttpService) Init() error { +func (s *baseHttpService) registerRoute(h func(e *gin.Engine)) { if s.server.status() != httpServerStarted { - s.registerRoute(s.server.e) + h(s.server.e) } - return nil } func (s *baseHttpService) Start() error { @@ -37,13 +30,3 @@ func (s *baseHttpService) Start() error { func (s *baseHttpService) Stop() error { return s.server.stop() } - -func (s *baseHttpService) registerRoute(e *gin.Engine) { - // default empty -} - -func newBaseHttpService(s *httpServer) httpService { - return &baseHttpService{ - server: s, - } -} diff --git a/internal/service/service.go b/internal/service/service.go index 31efbae0..9ac6446c 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -28,7 +28,7 @@ func (baseService) String() string { } func InitService() (ss []Service) { - ss = append(ss, newWebService()) + ss = append(ss, newWebService(), newOldWebService()) for _, s := range ss { if err := s.Init(); err != nil { diff --git a/internal/service/web.go b/internal/service/web.go index 6ded25d3..c8e422a1 100644 --- a/internal/service/web.go +++ b/internal/service/web.go @@ -16,19 +16,20 @@ import ( ) type webService struct { - httpService + *baseHttpService } func (s *webService) Name() string { return "WebService" } -func (s *webService) registerRoute(e *gin.Engine) { - servants.RegisterWebServants(e) +func (s *webService) Init() error { + s.registerRoute(servants.RegisterWebServants) + return nil } func (s *webService) String() string { - return fmt.Sprintf("PaoPao service listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)) + return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.WebServerSetting.HttpIp, conf.WebServerSetting.HttpPort)) } func newWebEngine() *gin.Engine { @@ -63,7 +64,7 @@ func newWebEngine() *gin.Engine { } func newWebService() Service { - addr := conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort + addr := conf.WebServerSetting.HttpIp + ":" + conf.WebServerSetting.HttpPort server := httpServerFrom(addr, func() *httpServer { engine := newWebEngine() return &httpServer{ @@ -71,13 +72,15 @@ func newWebService() Service { server: &http.Server{ Addr: addr, Handler: engine, - ReadTimeout: conf.ServerSetting.ReadTimeout, - WriteTimeout: conf.ServerSetting.WriteTimeout, + ReadTimeout: conf.WebServerSetting.ReadTimeout, + WriteTimeout: conf.WebServerSetting.WriteTimeout, MaxHeaderBytes: 1 << 20, }, } }) return &webService{ - httpService: newBaseHttpService(server), + baseHttpService: &baseHttpService{ + server: server, + }, } } diff --git a/internal/service/web_old.go b/internal/service/web_old.go new file mode 100644 index 00000000..a3c58471 --- /dev/null +++ b/internal/service/web_old.go @@ -0,0 +1,53 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "fmt" + "net/http" + + "github.com/fatih/color" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/servants/web/routers" +) + +type oldWebService struct { + *baseHttpService +} + +func (s *oldWebService) Name() string { + return "OldWebService" +} + +func (s *oldWebService) Init() error { + s.registerRoute(routers.RegisterRoute) + return nil +} + +func (s *oldWebService) String() string { + return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)) +} + +func newOldWebService() Service { + addr := conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort + server := httpServerFrom(addr, func() *httpServer { + engine := newWebEngine() + return &httpServer{ + e: engine, + server: &http.Server{ + Addr: addr, + Handler: engine, + ReadTimeout: conf.ServerSetting.ReadTimeout, + WriteTimeout: conf.ServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } + }) + return &oldWebService{ + baseHttpService: &baseHttpService{ + server: server, + }, + } +} diff --git a/main.go b/main.go index 0d28b464..63ec5f59 100644 --- a/main.go +++ b/main.go @@ -8,14 +8,16 @@ import ( "flag" "fmt" "log" - "net/http" + "os" + "os/signal" "strings" + "syscall" "github.com/fatih/color" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/servants/web/routers" + "github.com/rocboss/paopao-ce/internal/service" "github.com/rocboss/paopao-ce/pkg/debug" "github.com/rocboss/paopao-ce/pkg/util" ) @@ -51,24 +53,41 @@ func flagParse() { flag.Parse() } -func main() { - gin.SetMode(conf.ServerSetting.RunMode) - - router := routers.NewRouter() - s := &http.Server{ - Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort, - Handler: router, - ReadTimeout: conf.ServerSetting.ReadTimeout, - WriteTimeout: conf.ServerSetting.WriteTimeout, - MaxHeaderBytes: 1 << 20, +func runService(ss []service.Service) { + gin.SetMode(conf.RunMode()) + + fmt.Fprintf(color.Output, "\nstarting run service...\n\n") + for _, s := range ss { + go func(s service.Service) { + fmt.Fprintf(color.Output, "%s[start] - %s\n", s.Name(), s) + if err := s.Start(); err != nil { + log.Fatalf("%s[start] - occurs on error: %s\n", s.Name(), err) + } + }(s) } + quit := make(chan os.Signal, 1) + // kill (no param) default send syscall.SIGTERM + // kill -2 is syscall.SIGINT + // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + <-quit + fmt.Fprintf(color.Output, "\nshutting down server...\n\n") + + for _, s := range ss { + if err := s.Stop(); err != nil { + fmt.Fprintf(color.Output, "%s[stop] - occurs on error: %s\n", s.Name(), err) + } + fmt.Fprintf(color.Output, "%s[stop] - finish...\n", s.Name()) + } +} + +func main() { util.PrintHelloBanner(debug.VersionInfo()) - fmt.Fprintf(color.Output, "PaoPao service listen on %s\n", - color.GreenString(fmt.Sprintf("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)), - ) - if err := s.ListenAndServe(); err != nil { - log.Fatalf("run app failed: %s", err) + if ss := service.InitService(); len(ss) > 0 { + runService(ss) + } else { + fmt.Fprintf(color.Output, "no service need start so just exit") } } diff --git a/pkg/xerror/common.go b/pkg/xerror/common.go index b502840b..2852f6c2 100644 --- a/pkg/xerror/common.go +++ b/pkg/xerror/common.go @@ -23,8 +23,4 @@ var ( GatewayAppKeyClosed = NewError(10113, "网关请求APP KEY已停用") GatewayParamSignError = NewError(10114, "网关请求参数签名错误") GatewayTooManyRequests = NewError(10115, "网关请求频次超限") - - FileUploadFailed = NewError(10200, "文件上传失败") - FileInvalidExt = NewError(10201, "文件类型不合法") - FileInvalidSize = NewError(10202, "文件大小超限") ) From 3ad6f66a76e437cb6ef31352497e010c1db4fc47 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 10 Dec 2022 00:32:54 +0800 Subject: [PATCH 15/28] upgrade go-mir version to v3.0.0-alpha.4 --- go.mod | 2 +- go.sum | 4 ++-- internal/mirc/auto/api/v1/web_core.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 83348535..fa9ff517 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.18 require ( github.com/Masterminds/semver/v3 v3.1.1 github.com/afocus/captcha v0.0.0-20191010092841-4bd1f21c8868 - github.com/alimy/mir/v3 v3.0.0-alpha.3 + github.com/alimy/mir/v3 v3.0.0-alpha.4 github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible github.com/allegro/bigcache/v3 v3.0.2 github.com/bytedance/sonic v1.5.0 diff --git a/go.sum b/go.sum index 84ae8631..bfe083a0 100644 --- a/go.sum +++ b/go.sum @@ -142,8 +142,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk= -github.com/alimy/mir/v3 v3.0.0-alpha.3 h1:/GyBC0G041NIP3W62im8DtAwxRPSfSaivSQK6MV9fFc= -github.com/alimy/mir/v3 v3.0.0-alpha.3/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU= +github.com/alimy/mir/v3 v3.0.0-alpha.4 h1:tSmyyhgutMHjgx9TO9891ZCY4qbr3g8FGar4z+9Hhq4= +github.com/alimy/mir/v3 v3.0.0-alpha.4/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= diff --git a/internal/mirc/auto/api/v1/web_core.go b/internal/mirc/auto/api/v1/web_core.go index 5887e010..3e7d3d65 100644 --- a/internal/mirc/auto/api/v1/web_core.go +++ b/internal/mirc/auto/api/v1/web_core.go @@ -6,7 +6,7 @@ import ( "net/http" "github.com/alimy/mir/v3" - gin "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin" ) type LoginReq struct { From 6a53632b9b31b9092ddc34da365e7ec8d460badb Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 10 Dec 2022 10:23:33 +0800 Subject: [PATCH 16/28] optimize main function logic and custom service create logic --- internal/service/service.go | 17 ++++++++++++++--- main.go | 22 ++++++++++++++++------ 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/internal/service/service.go b/internal/service/service.go index 9ac6446c..a69c8c91 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -7,6 +7,7 @@ package service import ( "log" + "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/rocboss/paopao-ce/pkg/types" ) @@ -27,13 +28,23 @@ func (baseService) String() string { return "" } -func InitService() (ss []Service) { - ss = append(ss, newWebService(), newOldWebService()) - +func InitService() []Service { + ss := newService() for _, s := range ss { if err := s.Init(); err != nil { log.Fatalf("initial %s service error: %s", s.Name(), err) } } + return ss +} + +func newService() (ss []Service) { + ss = append(ss, newWebService()) + + // add oldWebService if not depredcated OldWebService + cfg.Not("Deprecated:OldWeb", func() { + ss = append(ss, newOldWebService()) + }) + return } diff --git a/main.go b/main.go index 63ec5f59..4c639a61 100644 --- a/main.go +++ b/main.go @@ -7,10 +7,10 @@ package main import ( "flag" "fmt" - "log" "os" "os/signal" "strings" + "sync" "syscall" "github.com/fatih/color" @@ -48,24 +48,27 @@ func init() { } func flagParse() { - flag.BoolVar(&noDefaultFeatures, "no-default-features", false, "whether use default features") + flag.BoolVar(&noDefaultFeatures, "no-default-features", false, "whether not use default features") flag.Var(&features, "features", "use special features") flag.Parse() } -func runService(ss []service.Service) { +func runService(wg *sync.WaitGroup, ss []service.Service) { gin.SetMode(conf.RunMode()) fmt.Fprintf(color.Output, "\nstarting run service...\n\n") for _, s := range ss { go func(s service.Service) { - fmt.Fprintf(color.Output, "%s[start] - %s\n", s.Name(), s) + fmt.Fprintf(color.Output, "%s[start] - %s", s.Name(), s) if err := s.Start(); err != nil { - log.Fatalf("%s[start] - occurs on error: %s\n", s.Name(), err) + fmt.Fprintf(color.Output, "%s[start] - occurs on error: %s\n", s.Name(), err) } + wg.Done() }(s) } +} +func runManage(wg *sync.WaitGroup, ss []service.Service) { quit := make(chan os.Signal, 1) // kill (no param) default send syscall.SIGTERM // kill -2 is syscall.SIGINT @@ -80,13 +83,20 @@ func runService(ss []service.Service) { } fmt.Fprintf(color.Output, "%s[stop] - finish...\n", s.Name()) } + wg.Done() } func main() { util.PrintHelloBanner(debug.VersionInfo()) if ss := service.InitService(); len(ss) > 0 { - runService(ss) + wg := &sync.WaitGroup{} + wg.Add(len(ss) + 1) + + runService(wg, ss) + go runManage(wg, ss) + + wg.Wait() } else { fmt.Fprintf(color.Output, "no service need start so just exit") } From 9be9eccda1d94f6bb5358b63227ec5be9155f627 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 10 Dec 2022 11:05:44 +0800 Subject: [PATCH 17/28] mir: update proposal document --- .../005-引入go-mir优化后端架构设计.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/proposal/005-引入go-mir优化后端架构设计.md b/docs/proposal/005-引入go-mir优化后端架构设计.md index 0168ed80..d42901ac 100644 --- a/docs/proposal/005-引入go-mir优化后端架构设计.md +++ b/docs/proposal/005-引入go-mir优化后端架构设计.md @@ -1,6 +1,6 @@ | 编号 | 作者 | 发表时间 | 变更时间 | 版本 | 状态 | | ----- | ----- | ----- | ----- | ----- | ----- | -| 005| 北野 | 2022-11-21 | 2022-11-21 | v0.0 | 提议 | +| 005| 北野 | 2022-11-21 | 2022-12-10 | v1.0 | 提议 | ### 引入go-mir优化后端架构设计 引入[github.com/alimy/mir/v3](https://github.com/alimy/mir)优化后端的架构设计,使得后端代码更具扩展型。 @@ -18,11 +18,18 @@ ### 疑问 1. 为什么引入go-mir? -TODO; + * [go-mir](https://github.com/alimy/mir)是一套提供类似gRPC服务开发体验的快速开发RESTful API后端开发脚手架,巧妙的借用golang语法作为DSL描述RESTful API,通过代码生成的方式自动生成相对应的API接口、HTTP服务器框架初始化代码等,提供类似gRPC的开发体验,对后端开发者非常友好。 + * 引入go-mir的另一个主要目的是加速后端服务的开发,更好的保证代码风格的一致性。 1. 为什么要兼容RESTful/gRPC服务? -RESTful API是提供给Web端使用的,包括paopao-ce web端以及后期的运维端admin; gRPC API是提供给移动端(iOS/Android)使用的服务。RESTful API天然对web端浏览器友好,而gRPC生态对后端、移动端天然友好,可以根据google-protocol-buffers DSL定义服务API自动生成服务端、客户端代码,非常利于开发,特别是移动端开发,省去了编写客户端网络数据服务相关的业务逻辑,只需要专注于页面逻辑编写,后端数据获取的网络数据访问逻辑直接调用自动生成的gRPC API客户端代码即可,大大的减轻移动端开发的心智负担。后端引入gRPC主要就是考虑到移动端(iOS/Android)开发的开发效率,在减轻移动端开发网络数据获取业务逻辑的心智负担上,gRPC生态与RESTful生态相比优势明显,因此强力引入。再一个就是[go-mir](https://github.com/alimy/mir) v3为RESTful服务的开发提供类似gRPC服务的开发体验,也为后端兼容RESTful/gRPC服务创造了很好的条件,只要代码结构组织清晰,将会有很好的后端开发体验。 + * RESTful API是提供给Web端使用的,包括paopao-ce web端以及后期的运维端admin; gRPC API是提供给移动端(iOS/Android)使用的服务。 + * RESTful API天然对web端浏览器友好,而gRPC生态对后端、移动端天然友好,可以根据google-protocol-buffers DSL定义服务API自动生成服务端、客户端代码,非常利于开发,特别是移动端开发,省去了编写客户端网络数据服务相关的业务逻辑,只需要专注于页面逻辑编写,后端数据获取的网络数据访问逻辑直接调用自动生成的gRPC API客户端代码即可,大大的减轻移动端开发的心智负担。 + * 后端引入gRPC主要就是考虑到移动端(iOS/Android)开发的开发效率,在减轻移动端开发网络数据获取业务逻辑的心智负担上,gRPC生态与RESTful生态相比优势明显,因此强力引入。 + * 再一个就是[go-mir](https://github.com/alimy/mir) v3为RESTful服务的开发提供类似gRPC服务的开发体验,也为后端兼容RESTful/gRPC服务创造了很好的条件,只要代码结构组织清晰,将会有很好的后端开发体验。 >*目前移动端 iOS/Android APP还在规划中,这里后续的后端gRPC API服务也是为此做准备,敬请期待~* ### 更新记录 #### v0.0(2022-11-21) - 北野 -* 初始文档 \ No newline at end of file +* 初始文档 + +#### v1.0(2022-12-10) - 北野 +* 添加内容 From 6650d089b8cb2ac5b5f87152f7194045d3e19a00 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 10 Dec 2022 14:36:10 +0800 Subject: [PATCH 18/28] add m/s/x RESTful API stub interface for mir --- Makefile | 9 +- ...05-引入go-mir优化后端架构设计.md | 14 +- internal/mirc/auto/api/m/v1/user.go | 127 +++++++++++++++++ internal/mirc/auto/api/s/v1/user.go | 131 ++++++++++++++++++ internal/mirc/auto/api/x/v1/user.go | 127 +++++++++++++++++ internal/mirc/main.go | 3 + internal/mirc/routes/README.md | 6 + internal/mirc/routes/m/README.md | 4 + internal/mirc/routes/m/v1/user.go | 42 ++++++ internal/mirc/routes/s/README.md | 4 + internal/mirc/routes/s/v1/user.go | 42 ++++++ internal/mirc/routes/x/README.md | 4 + internal/mirc/routes/x/v1/user.go | 42 ++++++ 13 files changed, 548 insertions(+), 7 deletions(-) create mode 100644 internal/mirc/auto/api/m/v1/user.go create mode 100644 internal/mirc/auto/api/s/v1/user.go create mode 100644 internal/mirc/auto/api/x/v1/user.go create mode 100644 internal/mirc/routes/m/README.md create mode 100644 internal/mirc/routes/m/v1/user.go create mode 100644 internal/mirc/routes/s/README.md create mode 100644 internal/mirc/routes/s/v1/user.go create mode 100644 internal/mirc/routes/x/README.md create mode 100644 internal/mirc/routes/x/v1/user.go diff --git a/Makefile b/Makefile index 700e2d29..dd26e18c 100644 --- a/Makefile +++ b/Makefile @@ -69,10 +69,17 @@ windows-x64: @CGO_ENABLED=$(CGO_ENABLED) GOOS=windows GOARCH=amd64 go build -trimpath -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -o $(RELEASE_WINDOWS_AMD64)/$(basename $(TARGET)).exe .PHONY: generate -generate: +generate: gen-mir gen-grpc + +.PHONY: gen-mir +gen-mir: @go generate internal/mirc/main.go @go fmt ./internal/mirc/... +.PHONY: gen-grpc +gen-grpc: + @go fmt ./internal/proto/... + clean: @go clean @find ./release -type f -exec rm -r {} + diff --git a/docs/proposal/005-引入go-mir优化后端架构设计.md b/docs/proposal/005-引入go-mir优化后端架构设计.md index d42901ac..24643b8c 100644 --- a/docs/proposal/005-引入go-mir优化后端架构设计.md +++ b/docs/proposal/005-引入go-mir优化后端架构设计.md @@ -4,6 +4,7 @@ ### 引入go-mir优化后端架构设计 引入[github.com/alimy/mir/v3](https://github.com/alimy/mir)优化后端的架构设计,使得后端代码更具扩展型。 +![](.assets/06-01.png) ### 需求 * 更方便添加后端功能项的实现; @@ -18,13 +19,14 @@ ### 疑问 1. 为什么引入go-mir? - * [go-mir](https://github.com/alimy/mir)是一套提供类似gRPC服务开发体验的快速开发RESTful API后端开发脚手架,巧妙的借用golang语法作为DSL描述RESTful API,通过代码生成的方式自动生成相对应的API接口、HTTP服务器框架初始化代码等,提供类似gRPC的开发体验,对后端开发者非常友好。 - * 引入go-mir的另一个主要目的是加速后端服务的开发,更好的保证代码风格的一致性。 + * [go-mir](https://github.com/alimy/mir)是一套提供类似gRPC服务开发体验的快速开发RESTful API后端开发脚手架,巧妙的借用golang语法作为DSL描述RESTful API,通过代码生成的方式自动生成相对应的API接口、HTTP服务器框架初始化代码等,提供类似gRPC的开发体验,对后端开发者非常友好; + * 引入go-mir的另一个主要目的是加速后端服务的开发,更好的保证代码风格的一致性; + * 践行 [006-关于paopao-ce的结构设计](006-关于paopao-ce的结构设计.md); 1. 为什么要兼容RESTful/gRPC服务? - * RESTful API是提供给Web端使用的,包括paopao-ce web端以及后期的运维端admin; gRPC API是提供给移动端(iOS/Android)使用的服务。 - * RESTful API天然对web端浏览器友好,而gRPC生态对后端、移动端天然友好,可以根据google-protocol-buffers DSL定义服务API自动生成服务端、客户端代码,非常利于开发,特别是移动端开发,省去了编写客户端网络数据服务相关的业务逻辑,只需要专注于页面逻辑编写,后端数据获取的网络数据访问逻辑直接调用自动生成的gRPC API客户端代码即可,大大的减轻移动端开发的心智负担。 - * 后端引入gRPC主要就是考虑到移动端(iOS/Android)开发的开发效率,在减轻移动端开发网络数据获取业务逻辑的心智负担上,gRPC生态与RESTful生态相比优势明显,因此强力引入。 - * 再一个就是[go-mir](https://github.com/alimy/mir) v3为RESTful服务的开发提供类似gRPC服务的开发体验,也为后端兼容RESTful/gRPC服务创造了很好的条件,只要代码结构组织清晰,将会有很好的后端开发体验。 + * RESTful API是提供给Web端使用的,包括paopao-ce web端以及后期的运维端admin; gRPC API是提供给移动端(iOS/Android)使用的服务; + * RESTful API天然对web端浏览器友好,而gRPC生态对后端、移动端天然友好,可以根据google-protocol-buffers DSL定义服务API自动生成服务端、客户端代码,非常利于开发,特别是移动端开发,省去了编写客户端网络数据服务相关的业务逻辑,只需要专注于页面逻辑编写,后端数据获取的网络数据访问逻辑直接调用自动生成的gRPC API客户端代码即可,大大的减轻移动端开发的心智负担; + * 后端引入gRPC主要就是考虑到移动端(iOS/Android)开发的开发效率,在减轻移动端开发网络数据获取业务逻辑的心智负担上,gRPC生态与RESTful生态相比优势明显,因此强力引入; + * 再一个就是[go-mir](https://github.com/alimy/mir) v3为RESTful服务的开发提供类似gRPC服务的开发体验,也为后端兼容RESTful/gRPC服务创造了很好的条件,只要代码结构组织清晰,将会有很好的后端开发体验; >*目前移动端 iOS/Android APP还在规划中,这里后续的后端gRPC API服务也是为此做准备,敬请期待~* ### 更新记录 diff --git a/internal/mirc/auto/api/m/v1/user.go b/internal/mirc/auto/api/m/v1/user.go new file mode 100644 index 00000000..c087ae87 --- /dev/null +++ b/internal/mirc/auto/api/m/v1/user.go @@ -0,0 +1,127 @@ +// Code generated by go-mir. DO NOT EDIT. + +package v1 + +import ( + "net/http" + + "github.com/alimy/mir/v3" + "github.com/gin-gonic/gin" +) + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type User interface { + // Chain provide handlers chain for gin + Chain() gin.HandlersChain + + Logout(c *gin.Context) mir.Error + Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + + mustEmbedUnimplementedUserServant() +} + +type UserBinding interface { + BindLogin(c *gin.Context) (*LoginReq, mir.Error) + + mustEmbedUnimplementedUserBinding() +} + +type UserRender interface { + RenderLogout(c *gin.Context, err mir.Error) + RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + + mustEmbedUnimplementedUserRender() +} + +// RegisterUserServant register User servant to gin +func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { + router := e.Group("m/v1") + // use chain for router + middlewares := s.Chain() + router.Use(middlewares...) + + // register routes info to router + router.Handle("POST", "/user/logout/", func(c *gin.Context) { + r.RenderLogout(c, s.Logout(c)) + }) + + router.Handle("POST", "/user/login/", func(c *gin.Context) { + req, err := b.BindLogin(c) + if err != nil { + r.RenderLogin(c, nil, err) + } + resp, err := s.Login(c, req) + r.RenderLogin(c, resp, err) + }) + +} + +// UnimplementedUserServant can be embedded to have forward compatible implementations. +type UnimplementedUserServant struct { +} + +func (UnimplementedUserServant) Chain() gin.HandlersChain { + return nil +} + +func (UnimplementedUserServant) Logout(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedUserServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { + return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedUserServant) mustEmbedUnimplementedUserServant() {} + +// UnimplementedUserRender can be embedded to have forward compatible implementations. +type UnimplementedUserRender struct { + RenderAny func(*gin.Context, any, mir.Error) +} + +func (r *UnimplementedUserRender) RenderLogout(c *gin.Context, err mir.Error) { + r.RenderAny(c, nil, err) +} + +func (r *UnimplementedUserRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) { + r.RenderAny(c, data, err) +} + +func (r *UnimplementedUserRender) mustEmbedUnimplementedUserRender() {} + +// UnimplementedUserBinding can be embedded to have forward compatible implementations. +type UnimplementedUserBinding struct { + BindAny func(*gin.Context, any) mir.Error +} + +func (b *UnimplementedUserBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) { + obj := new(LoginReq) + err := b.BindAny(c, obj) + return obj, err +} + +func (b *UnimplementedUserBinding) mustEmbedUnimplementedUserBinding() {} diff --git a/internal/mirc/auto/api/s/v1/user.go b/internal/mirc/auto/api/s/v1/user.go new file mode 100644 index 00000000..4751a141 --- /dev/null +++ b/internal/mirc/auto/api/s/v1/user.go @@ -0,0 +1,131 @@ +// Code generated by go-mir. DO NOT EDIT. + +package v1 + +import ( + "net/http" + + "github.com/alimy/mir/v3" + "github.com/gin-gonic/gin" +) + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type User interface { + Logout(c *gin.Context) mir.Error + Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + Index(c *gin.Context) mir.Error + + mustEmbedUnimplementedUserServant() +} + +type UserBinding interface { + BindLogin(c *gin.Context) (*LoginReq, mir.Error) + + mustEmbedUnimplementedUserBinding() +} + +type UserRender interface { + RenderLogout(c *gin.Context, err mir.Error) + RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + RenderIndex(c *gin.Context, err mir.Error) + + mustEmbedUnimplementedUserRender() +} + +// RegisterUserServant register User servant to gin +func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { + router := e.Group("s/v1") + + // register routes info to router + router.Handle("POST", "/user/logout/", func(c *gin.Context) { + r.RenderLogout(c, s.Logout(c)) + }) + + router.Handle("POST", "/user/login/", func(c *gin.Context) { + req, err := b.BindLogin(c) + if err != nil { + r.RenderLogin(c, nil, err) + } + resp, err := s.Login(c, req) + r.RenderLogin(c, resp, err) + }) + + router.Handle("GET", "/index/", func(c *gin.Context) { + r.RenderIndex(c, s.Index(c)) + }) + +} + +// UnimplementedUserServant can be embedded to have forward compatible implementations. +type UnimplementedUserServant struct { +} + +func (UnimplementedUserServant) Logout(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedUserServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { + return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedUserServant) Index(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedUserServant) mustEmbedUnimplementedUserServant() {} + +// UnimplementedUserRender can be embedded to have forward compatible implementations. +type UnimplementedUserRender struct { + RenderAny func(*gin.Context, any, mir.Error) +} + +func (r *UnimplementedUserRender) RenderLogout(c *gin.Context, err mir.Error) { + r.RenderAny(c, nil, err) +} + +func (r *UnimplementedUserRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) { + r.RenderAny(c, data, err) +} + +func (r *UnimplementedUserRender) RenderIndex(c *gin.Context, err mir.Error) { + r.RenderAny(c, nil, err) +} + +func (r *UnimplementedUserRender) mustEmbedUnimplementedUserRender() {} + +// UnimplementedUserBinding can be embedded to have forward compatible implementations. +type UnimplementedUserBinding struct { + BindAny func(*gin.Context, any) mir.Error +} + +func (b *UnimplementedUserBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) { + obj := new(LoginReq) + err := b.BindAny(c, obj) + return obj, err +} + +func (b *UnimplementedUserBinding) mustEmbedUnimplementedUserBinding() {} diff --git a/internal/mirc/auto/api/x/v1/user.go b/internal/mirc/auto/api/x/v1/user.go new file mode 100644 index 00000000..66446d03 --- /dev/null +++ b/internal/mirc/auto/api/x/v1/user.go @@ -0,0 +1,127 @@ +// Code generated by go-mir. DO NOT EDIT. + +package v1 + +import ( + "net/http" + + "github.com/alimy/mir/v3" + "github.com/gin-gonic/gin" +) + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type User interface { + // Chain provide handlers chain for gin + Chain() gin.HandlersChain + + Logout(c *gin.Context) mir.Error + Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + + mustEmbedUnimplementedUserServant() +} + +type UserBinding interface { + BindLogin(c *gin.Context) (*LoginReq, mir.Error) + + mustEmbedUnimplementedUserBinding() +} + +type UserRender interface { + RenderLogout(c *gin.Context, err mir.Error) + RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + + mustEmbedUnimplementedUserRender() +} + +// RegisterUserServant register User servant to gin +func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { + router := e.Group("x/v1") + // use chain for router + middlewares := s.Chain() + router.Use(middlewares...) + + // register routes info to router + router.Handle("POST", "/user/logout/", func(c *gin.Context) { + r.RenderLogout(c, s.Logout(c)) + }) + + router.Handle("POST", "/user/login/", func(c *gin.Context) { + req, err := b.BindLogin(c) + if err != nil { + r.RenderLogin(c, nil, err) + } + resp, err := s.Login(c, req) + r.RenderLogin(c, resp, err) + }) + +} + +// UnimplementedUserServant can be embedded to have forward compatible implementations. +type UnimplementedUserServant struct { +} + +func (UnimplementedUserServant) Chain() gin.HandlersChain { + return nil +} + +func (UnimplementedUserServant) Logout(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedUserServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { + return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedUserServant) mustEmbedUnimplementedUserServant() {} + +// UnimplementedUserRender can be embedded to have forward compatible implementations. +type UnimplementedUserRender struct { + RenderAny func(*gin.Context, any, mir.Error) +} + +func (r *UnimplementedUserRender) RenderLogout(c *gin.Context, err mir.Error) { + r.RenderAny(c, nil, err) +} + +func (r *UnimplementedUserRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) { + r.RenderAny(c, data, err) +} + +func (r *UnimplementedUserRender) mustEmbedUnimplementedUserRender() {} + +// UnimplementedUserBinding can be embedded to have forward compatible implementations. +type UnimplementedUserBinding struct { + BindAny func(*gin.Context, any) mir.Error +} + +func (b *UnimplementedUserBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) { + obj := new(LoginReq) + err := b.BindAny(c, obj) + return obj, err +} + +func (b *UnimplementedUserBinding) mustEmbedUnimplementedUserBinding() {} diff --git a/internal/mirc/main.go b/internal/mirc/main.go index bf45791f..5bef4944 100644 --- a/internal/mirc/main.go +++ b/internal/mirc/main.go @@ -10,7 +10,10 @@ import ( . "github.com/alimy/mir/v3/core" . "github.com/alimy/mir/v3/engine" + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/m/v1" + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/s/v1" _ "github.com/rocboss/paopao-ce/internal/mirc/routes/v1" + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/x/v1" ) //go:generate go run main.go diff --git a/internal/mirc/routes/README.md b/internal/mirc/routes/README.md index 0d7ac0c1..fb8728e2 100644 --- a/internal/mirc/routes/README.md +++ b/internal/mirc/routes/README.md @@ -1 +1,7 @@ ### RESTful API for paopao-ce +本目录包含所有RESTful API相关定义文件 + +* v1 - Web系列 v1版本 相关RESTful API相关定义文件 +* m - Manager系列相关RESTful API相关定义文件 +* x - SpaceX系列相关RESTful API相关定义文件 +* s - LocalOSS OBS系列RESTful API相关定义文件 diff --git a/internal/mirc/routes/m/README.md b/internal/mirc/routes/m/README.md new file mode 100644 index 00000000..2c6a4431 --- /dev/null +++ b/internal/mirc/routes/m/README.md @@ -0,0 +1,4 @@ +### Manager系列RESTful API相关定义文件 +本目录包含 Manager后台运维相关API定义文件。 + +* v1 - v1版本API diff --git a/internal/mirc/routes/m/v1/user.go b/internal/mirc/routes/m/v1/user.go new file mode 100644 index 00000000..6f0dcb79 --- /dev/null +++ b/internal/mirc/routes/m/v1/user.go @@ -0,0 +1,42 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(User)) +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type User struct { + Chain Chain `mir:"-"` + Group Group `mir:"m/v1"` + Login func(Post, LoginReq) LoginResp `mir:"/user/login/"` + Logout func(Post) `mir:"/user/logout/"` +} diff --git a/internal/mirc/routes/s/README.md b/internal/mirc/routes/s/README.md new file mode 100644 index 00000000..e1769bf5 --- /dev/null +++ b/internal/mirc/routes/s/README.md @@ -0,0 +1,4 @@ +### LocalOSS OBS系列RESTful API相关定义文件 +本目录包含 LocalOSS OBS 系列相关API定义文件。 + +* v1 - v1版本API diff --git a/internal/mirc/routes/s/v1/user.go b/internal/mirc/routes/s/v1/user.go new file mode 100644 index 00000000..555ff6d7 --- /dev/null +++ b/internal/mirc/routes/s/v1/user.go @@ -0,0 +1,42 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(User)) +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type User struct { + Group Group `mir:"s/v1"` + Index func(Get) `mir:"/index/"` + Login func(Post, LoginReq) LoginResp `mir:"/user/login/"` + Logout func(Post) `mir:"/user/logout/"` +} diff --git a/internal/mirc/routes/x/README.md b/internal/mirc/routes/x/README.md new file mode 100644 index 00000000..a4ec3303 --- /dev/null +++ b/internal/mirc/routes/x/README.md @@ -0,0 +1,4 @@ +### SpaceX系列RESTful API +本目录包含SpaceX系列RESTful API相关定义文件 + +* v1 - v1版本API diff --git a/internal/mirc/routes/x/v1/user.go b/internal/mirc/routes/x/v1/user.go new file mode 100644 index 00000000..8dd49fa5 --- /dev/null +++ b/internal/mirc/routes/x/v1/user.go @@ -0,0 +1,42 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(User)) +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type User struct { + Chain Chain `mir:"-"` + Group Group `mir:"x/v1"` + Login func(Post, LoginReq) LoginResp `mir:"/user/login/"` + Logout func(Post) `mir:"/user/logout/"` +} From 4dae86cc9c10eda116d8c732fd708db2b63d530a Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 10 Dec 2022 16:01:30 +0800 Subject: [PATCH 19/28] mir: add Admin/SpaceX/Bot/LocalOSS stub service interface and simple initial logic --- config.yaml.sample | 21 ++++ internal/conf/conf.go | 14 ++- internal/conf/settting.go | 2 +- internal/mirc/README.md | 3 +- internal/mirc/auto/api/r/v1/user.go | 127 +++++++++++++++++++++++++ internal/mirc/auto/api/v1/web_core.go | 2 +- internal/mirc/main.go | 1 + internal/mirc/routes/README.md | 3 +- internal/mirc/routes/m/README.md | 4 +- internal/mirc/routes/r/README.md | 4 + internal/mirc/routes/r/v1/user.go | 42 ++++++++ internal/servants/admin/admin.go | 15 +++ internal/servants/admin/user.go | 51 ++++++++++ internal/servants/bot/bot.go | 15 +++ internal/servants/bot/user.go | 51 ++++++++++ internal/servants/localoss/localoss.go | 10 +- internal/servants/localoss/user.go | 51 ++++++++++ internal/servants/servants.go | 23 +++++ internal/servants/space/space.go | 15 +++ internal/servants/space/user.go | 51 ++++++++++ internal/service/admin.go | 86 +++++++++++++++++ internal/service/bot.go | 86 +++++++++++++++++ internal/service/localoss.go | 61 ++++++++++++ internal/service/service.go | 15 +++ internal/service/space.go | 86 +++++++++++++++++ 25 files changed, 826 insertions(+), 13 deletions(-) create mode 100644 internal/mirc/auto/api/r/v1/user.go create mode 100644 internal/mirc/routes/r/README.md create mode 100644 internal/mirc/routes/r/v1/user.go create mode 100644 internal/servants/admin/admin.go create mode 100644 internal/servants/admin/user.go create mode 100644 internal/servants/bot/bot.go create mode 100644 internal/servants/bot/user.go create mode 100644 internal/servants/localoss/user.go create mode 100644 internal/servants/space/space.go create mode 100644 internal/servants/space/user.go create mode 100644 internal/service/admin.go create mode 100644 internal/service/bot.go create mode 100644 internal/service/localoss.go create mode 100644 internal/service/space.go diff --git a/config.yaml.sample b/config.yaml.sample index 1126bcec..2c6c1ae1 100644 --- a/config.yaml.sample +++ b/config.yaml.sample @@ -19,6 +19,7 @@ Features: Base: ["Redis", "PhoneBind"] Docs: ["Docs:OpenAPI"] Deprecated: ["Deprecated:OldWeb"] + Service: ["Admin", "SpaceX", "Bot", "LocalOSS"] Option: ["SimpleCacheIndex"] Sms: "SmsJuhe" WebServer: # Web服务 @@ -26,6 +27,26 @@ WebServer: # Web服务 HttpPort: 8010 ReadTimeout: 60 WriteTimeout: 60 +AdminServer: # Admin后台运维服务 + HttpIp: 0.0.0.0 + HttpPort: 8014 + ReadTimeout: 60 + WriteTimeout: 60 +SpaceXServer: # SpaceX服务 + HttpIp: 0.0.0.0 + HttpPort: 8012 + ReadTimeout: 60 + WriteTimeout: 60 +BotServer: # Bot服务 + HttpIp: 0.0.0.0 + HttpPort: 8016 + ReadTimeout: 60 + WriteTimeout: 60 +LocalossServer: # Localoss服务 + HttpIp: 0.0.0.0 + HttpPort: 8018 + ReadTimeout: 60 + WriteTimeout: 60 DocsServer: # 开发文档服务 HttpIp: 0.0.0.0 HttpPort: 8011 diff --git a/internal/conf/conf.go b/internal/conf/conf.go index 1cffa824..75d363e7 100644 --- a/internal/conf/conf.go +++ b/internal/conf/conf.go @@ -23,9 +23,13 @@ var ( MysqlSetting *MySQLSettingS PostgresSetting *PostgresSettingS Sqlite3Setting *Sqlite3SettingS - ServerSetting *ServerSettingS - WebServerSetting *ServerSettingS - DocsServerSetting *ServerSettingS + ServerSetting *HttpServerSettingS + WebServerSetting *HttpServerSettingS + AdminServerSetting *HttpServerSettingS + SpaceXServerSetting *HttpServerSettingS + BotServerSetting *HttpServerSettingS + LocalossServerSetting *HttpServerSettingS + DocsServerSetting *HttpServerSettingS AppSetting *AppSettingS CacheIndexSetting *CacheIndexSettingS SimpleCacheIndexSetting *SimpleCacheIndexSettingS @@ -63,6 +67,10 @@ func setupSetting(suite []string, noDefault bool) error { "App": &AppSetting, "Server": &ServerSetting, "WebServer": &WebServerSetting, + "AdminServer": &AdminServerSetting, + "SpaceXServer": &SpaceXServerSetting, + "BotServer": &BotServerSetting, + "LocalossServer": &LocalossServerSetting, "DocsServer": &DocsServerSetting, "CacheIndex": &CacheIndexSetting, "SimpleCacheIndex": &SimpleCacheIndexSetting, diff --git a/internal/conf/settting.go b/internal/conf/settting.go index e5841c51..7067d18e 100644 --- a/internal/conf/settting.go +++ b/internal/conf/settting.go @@ -45,7 +45,7 @@ type LoggerMeiliSettingS struct { MinWorker int } -type ServerSettingS struct { +type HttpServerSettingS struct { RunMode string HttpIp string HttpPort string diff --git a/internal/mirc/README.md b/internal/mirc/README.md index 5b2162a2..064cbe21 100644 --- a/internal/mirc/README.md +++ b/internal/mirc/README.md @@ -1 +1,2 @@ -### RESTful API for paopao-ce use [go-mir](https://github.com/alimy/mir) to generate service interface code automatic. +### Mirc for paopao-ce +RESTful API for paopao-ce use [go-mir](https://github.com/alimy/mir) to generate service interface code automatic. diff --git a/internal/mirc/auto/api/r/v1/user.go b/internal/mirc/auto/api/r/v1/user.go new file mode 100644 index 00000000..ae9dd9cd --- /dev/null +++ b/internal/mirc/auto/api/r/v1/user.go @@ -0,0 +1,127 @@ +// Code generated by go-mir. DO NOT EDIT. + +package v1 + +import ( + "net/http" + + "github.com/alimy/mir/v3" + "github.com/gin-gonic/gin" +) + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type User interface { + // Chain provide handlers chain for gin + Chain() gin.HandlersChain + + Logout(c *gin.Context) mir.Error + Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + + mustEmbedUnimplementedUserServant() +} + +type UserBinding interface { + BindLogin(c *gin.Context) (*LoginReq, mir.Error) + + mustEmbedUnimplementedUserBinding() +} + +type UserRender interface { + RenderLogout(c *gin.Context, err mir.Error) + RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + + mustEmbedUnimplementedUserRender() +} + +// RegisterUserServant register User servant to gin +func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { + router := e.Group("r/v1") + // use chain for router + middlewares := s.Chain() + router.Use(middlewares...) + + // register routes info to router + router.Handle("POST", "/user/logout/", func(c *gin.Context) { + r.RenderLogout(c, s.Logout(c)) + }) + + router.Handle("POST", "/user/login/", func(c *gin.Context) { + req, err := b.BindLogin(c) + if err != nil { + r.RenderLogin(c, nil, err) + } + resp, err := s.Login(c, req) + r.RenderLogin(c, resp, err) + }) + +} + +// UnimplementedUserServant can be embedded to have forward compatible implementations. +type UnimplementedUserServant struct { +} + +func (UnimplementedUserServant) Chain() gin.HandlersChain { + return nil +} + +func (UnimplementedUserServant) Logout(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedUserServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { + return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedUserServant) mustEmbedUnimplementedUserServant() {} + +// UnimplementedUserRender can be embedded to have forward compatible implementations. +type UnimplementedUserRender struct { + RenderAny func(*gin.Context, any, mir.Error) +} + +func (r *UnimplementedUserRender) RenderLogout(c *gin.Context, err mir.Error) { + r.RenderAny(c, nil, err) +} + +func (r *UnimplementedUserRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) { + r.RenderAny(c, data, err) +} + +func (r *UnimplementedUserRender) mustEmbedUnimplementedUserRender() {} + +// UnimplementedUserBinding can be embedded to have forward compatible implementations. +type UnimplementedUserBinding struct { + BindAny func(*gin.Context, any) mir.Error +} + +func (b *UnimplementedUserBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) { + obj := new(LoginReq) + err := b.BindAny(c, obj) + return obj, err +} + +func (b *UnimplementedUserBinding) mustEmbedUnimplementedUserBinding() {} diff --git a/internal/mirc/auto/api/v1/web_core.go b/internal/mirc/auto/api/v1/web_core.go index 3e7d3d65..6f1efce6 100644 --- a/internal/mirc/auto/api/v1/web_core.go +++ b/internal/mirc/auto/api/v1/web_core.go @@ -86,8 +86,8 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor h := func(c *gin.Context) { r.RenderArticles(c, s.Articles(c)) } - router.Handle("HEAD", "/articles/:category/", h) router.Handle("GET", "/articles/:category/", h) + router.Handle("HEAD", "/articles/:category/", h) } router.Handle("GET", "/index/", func(c *gin.Context) { diff --git a/internal/mirc/main.go b/internal/mirc/main.go index 5bef4944..34120f36 100644 --- a/internal/mirc/main.go +++ b/internal/mirc/main.go @@ -11,6 +11,7 @@ import ( . "github.com/alimy/mir/v3/engine" _ "github.com/rocboss/paopao-ce/internal/mirc/routes/m/v1" + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/r/v1" _ "github.com/rocboss/paopao-ce/internal/mirc/routes/s/v1" _ "github.com/rocboss/paopao-ce/internal/mirc/routes/v1" _ "github.com/rocboss/paopao-ce/internal/mirc/routes/x/v1" diff --git a/internal/mirc/routes/README.md b/internal/mirc/routes/README.md index fb8728e2..d7d0b9fb 100644 --- a/internal/mirc/routes/README.md +++ b/internal/mirc/routes/README.md @@ -2,6 +2,7 @@ 本目录包含所有RESTful API相关定义文件 * v1 - Web系列 v1版本 相关RESTful API相关定义文件 -* m - Manager系列相关RESTful API相关定义文件 +* m - Admin后台运维系列相关RESTful API相关定义文件 * x - SpaceX系列相关RESTful API相关定义文件 * s - LocalOSS OBS系列RESTful API相关定义文件 +* r - Bot系列相关RESTful API相关定义文件 diff --git a/internal/mirc/routes/m/README.md b/internal/mirc/routes/m/README.md index 2c6a4431..c9fa71b9 100644 --- a/internal/mirc/routes/m/README.md +++ b/internal/mirc/routes/m/README.md @@ -1,4 +1,4 @@ -### Manager系列RESTful API相关定义文件 -本目录包含 Manager后台运维相关API定义文件。 +### Admin系列RESTful API相关定义文件 +本目录包含 Admin后台运维相关API定义文件。 * v1 - v1版本API diff --git a/internal/mirc/routes/r/README.md b/internal/mirc/routes/r/README.md new file mode 100644 index 00000000..a1aa83ac --- /dev/null +++ b/internal/mirc/routes/r/README.md @@ -0,0 +1,4 @@ +### Bot系列RESTful API相关定义文件 +本目录包含 Bot相关API定义文件。 + +* v1 - v1版本API diff --git a/internal/mirc/routes/r/v1/user.go b/internal/mirc/routes/r/v1/user.go new file mode 100644 index 00000000..a4839673 --- /dev/null +++ b/internal/mirc/routes/r/v1/user.go @@ -0,0 +1,42 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(User)) +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type User struct { + Chain Chain `mir:"-"` + Group Group `mir:"r/v1"` + Login func(Post, LoginReq) LoginResp `mir:"/user/login/"` + Logout func(Post) `mir:"/user/logout/"` +} diff --git a/internal/servants/admin/admin.go b/internal/servants/admin/admin.go new file mode 100644 index 00000000..3fa2a7cf --- /dev/null +++ b/internal/servants/admin/admin.go @@ -0,0 +1,15 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package admin + +import ( + "github.com/gin-gonic/gin" + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/m/v1" +) + +// RouteWeb register Manager route +func RouteManager(e *gin.Engine) { + api.RegisterUserServant(e, newUserSrv(), newUserBinding(), newUserRender()) +} diff --git a/internal/servants/admin/user.go b/internal/servants/admin/user.go new file mode 100644 index 00000000..6c3f11ab --- /dev/null +++ b/internal/servants/admin/user.go @@ -0,0 +1,51 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package admin + +import ( + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/m/v1" + "github.com/rocboss/paopao-ce/internal/servants/base" +) + +var ( + _ api.User = (*userSrv)(nil) + _ api.UserBinding = (*userBinding)(nil) + _ api.UserRender = (*userRender)(nil) +) + +type userSrv struct { + base.BaseServant + api.UnimplementedUserServant +} + +type userBinding struct { + base.BaseBinding + *api.UnimplementedUserBinding +} + +type userRender struct { + base.BaseRender + *api.UnimplementedUserRender +} + +func newUserSrv() api.User { + return &userSrv{} +} + +func newUserBinding() api.UserBinding { + return &userBinding{ + UnimplementedUserBinding: &api.UnimplementedUserBinding{ + BindAny: base.BindAny, + }, + } +} + +func newUserRender() api.UserRender { + return &userRender{ + UnimplementedUserRender: &api.UnimplementedUserRender{ + RenderAny: base.RenderAny, + }, + } +} diff --git a/internal/servants/bot/bot.go b/internal/servants/bot/bot.go new file mode 100644 index 00000000..6ddd6846 --- /dev/null +++ b/internal/servants/bot/bot.go @@ -0,0 +1,15 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package bot + +import ( + "github.com/gin-gonic/gin" + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/r/v1" +) + +// RouteBot register Bot route +func RouteBot(e *gin.Engine) { + api.RegisterUserServant(e, newUserSrv(), newUserBinding(), newUserRender()) +} diff --git a/internal/servants/bot/user.go b/internal/servants/bot/user.go new file mode 100644 index 00000000..9f17a6e8 --- /dev/null +++ b/internal/servants/bot/user.go @@ -0,0 +1,51 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package bot + +import ( + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/r/v1" + "github.com/rocboss/paopao-ce/internal/servants/base" +) + +var ( + _ api.User = (*userSrv)(nil) + _ api.UserBinding = (*userBinding)(nil) + _ api.UserRender = (*userRender)(nil) +) + +type userSrv struct { + base.BaseServant + api.UnimplementedUserServant +} + +type userBinding struct { + base.BaseBinding + *api.UnimplementedUserBinding +} + +type userRender struct { + base.BaseRender + *api.UnimplementedUserRender +} + +func newUserSrv() api.User { + return &userSrv{} +} + +func newUserBinding() api.UserBinding { + return &userBinding{ + UnimplementedUserBinding: &api.UnimplementedUserBinding{ + BindAny: base.BindAny, + }, + } +} + +func newUserRender() api.UserRender { + return &userRender{ + UnimplementedUserRender: &api.UnimplementedUserRender{ + RenderAny: base.RenderAny, + }, + } +} diff --git a/internal/servants/localoss/localoss.go b/internal/servants/localoss/localoss.go index 828b3be2..721f0407 100644 --- a/internal/servants/localoss/localoss.go +++ b/internal/servants/localoss/localoss.go @@ -9,13 +9,10 @@ import ( "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/s/v1" "github.com/sirupsen/logrus" ) -type localossSrv struct { - // TODO -} - // RouteLocalOSS register LocalOSS route if needed func RouteLocalOSS(e *gin.Engine) { savePath, err := filepath.Abs(conf.LocalOSSSetting.SavePath) @@ -26,3 +23,8 @@ func RouteLocalOSS(e *gin.Engine) { logrus.Infof("register LocalOSS route in /oss on save path: %s", savePath) } + +// RouteLocaloss register LocalOSS route if needed +func RouteLocaloss(e *gin.Engine) { + api.RegisterUserServant(e, newUserSrv(), newUserBinding(), newUserRender()) +} diff --git a/internal/servants/localoss/user.go b/internal/servants/localoss/user.go new file mode 100644 index 00000000..b8d2309a --- /dev/null +++ b/internal/servants/localoss/user.go @@ -0,0 +1,51 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package localoss + +import ( + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/s/v1" + "github.com/rocboss/paopao-ce/internal/servants/base" +) + +var ( + _ api.User = (*userSrv)(nil) + _ api.UserBinding = (*userBinding)(nil) + _ api.UserRender = (*userRender)(nil) +) + +type userSrv struct { + base.BaseServant + api.UnimplementedUserServant +} + +type userBinding struct { + base.BaseBinding + *api.UnimplementedUserBinding +} + +type userRender struct { + base.BaseRender + *api.UnimplementedUserRender +} + +func newUserSrv() api.User { + return &userSrv{} +} + +func newUserBinding() api.UserBinding { + return &userBinding{ + UnimplementedUserBinding: &api.UnimplementedUserBinding{ + BindAny: base.BindAny, + }, + } +} + +func newUserRender() api.UserRender { + return &userRender{ + UnimplementedUserRender: &api.UnimplementedUserRender{ + RenderAny: base.RenderAny, + }, + } +} diff --git a/internal/servants/servants.go b/internal/servants/servants.go index 9ae3d0a7..496a60c1 100644 --- a/internal/servants/servants.go +++ b/internal/servants/servants.go @@ -6,8 +6,11 @@ package servants import ( "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/servants/admin" + "github.com/rocboss/paopao-ce/internal/servants/bot" "github.com/rocboss/paopao-ce/internal/servants/docs" "github.com/rocboss/paopao-ce/internal/servants/localoss" + "github.com/rocboss/paopao-ce/internal/servants/space" "github.com/rocboss/paopao-ce/internal/servants/statick" "github.com/rocboss/paopao-ce/internal/servants/web" "github.com/rocboss/paopao-ce/pkg/cfg" @@ -24,3 +27,23 @@ func RegisterWebServants(e *gin.Engine) { web.RouteWeb(e) } + +// RegisterAdminServants register all the servants to gin.Engine +func RegisterAdminServants(e *gin.Engine) { + admin.RouteManager(e) +} + +// RegisterSpaceXServants register all the servants to gin.Engine +func RegisterSpaceXServants(e *gin.Engine) { + space.RouteSpaceX(e) +} + +// RegisterBotServants register all the servants to gin.Engine +func RegisterBotServants(e *gin.Engine) { + bot.RouteBot(e) +} + +// RegisterLocalossServants register all the servants to gin.Engine +func RegisterLocalossServants(e *gin.Engine) { + localoss.RouteLocaloss(e) +} diff --git a/internal/servants/space/space.go b/internal/servants/space/space.go new file mode 100644 index 00000000..311f76b0 --- /dev/null +++ b/internal/servants/space/space.go @@ -0,0 +1,15 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package space + +import ( + "github.com/gin-gonic/gin" + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/x/v1" +) + +// RouteWeb register SpaceX route +func RouteSpaceX(e *gin.Engine) { + api.RegisterUserServant(e, newUserSrv(), newUserBinding(), newUserRender()) +} diff --git a/internal/servants/space/user.go b/internal/servants/space/user.go new file mode 100644 index 00000000..2e6014a0 --- /dev/null +++ b/internal/servants/space/user.go @@ -0,0 +1,51 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package space + +import ( + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/x/v1" + "github.com/rocboss/paopao-ce/internal/servants/base" +) + +var ( + _ api.User = (*userSrv)(nil) + _ api.UserBinding = (*userBinding)(nil) + _ api.UserRender = (*userRender)(nil) +) + +type userSrv struct { + base.BaseServant + api.UnimplementedUserServant +} + +type userBinding struct { + base.BaseBinding + *api.UnimplementedUserBinding +} + +type userRender struct { + base.BaseRender + *api.UnimplementedUserRender +} + +func newUserSrv() api.User { + return &userSrv{} +} + +func newUserBinding() api.UserBinding { + return &userBinding{ + UnimplementedUserBinding: &api.UnimplementedUserBinding{ + BindAny: base.BindAny, + }, + } +} + +func newUserRender() api.UserRender { + return &userRender{ + UnimplementedUserRender: &api.UnimplementedUserRender{ + RenderAny: base.RenderAny, + }, + } +} diff --git a/internal/service/admin.go b/internal/service/admin.go new file mode 100644 index 00000000..ad965e80 --- /dev/null +++ b/internal/service/admin.go @@ -0,0 +1,86 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "fmt" + "net/http" + + "github.com/fatih/color" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/servants" +) + +type adminService struct { + *baseHttpService +} + +func (s *adminService) Name() string { + return "AdminService" +} + +func (s *adminService) Init() error { + s.registerRoute(servants.RegisterAdminServants) + return nil +} + +func (s *adminService) String() string { + return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.AdminServerSetting.HttpIp, conf.AdminServerSetting.HttpPort)) +} + +func newAdminEngine() *gin.Engine { + e := gin.New() + e.HandleMethodNotAllowed = true + e.Use(gin.Logger()) + e.Use(gin.Recovery()) + + // 跨域配置 + corsConfig := cors.DefaultConfig() + corsConfig.AllowAllOrigins = true + corsConfig.AddAllowHeaders("Authorization") + e.Use(cors.New(corsConfig)) + + // 默认404 + e.NoRoute(func(c *gin.Context) { + c.JSON(http.StatusNotFound, gin.H{ + "code": 404, + "msg": "Not Found", + }) + }) + + // 默认405 + e.NoMethod(func(c *gin.Context) { + c.JSON(http.StatusMethodNotAllowed, gin.H{ + "code": 405, + "msg": "Method Not Allowed", + }) + }) + + return e +} + +func newAdminService() Service { + addr := conf.AdminServerSetting.HttpIp + ":" + conf.AdminServerSetting.HttpPort + server := httpServerFrom(addr, func() *httpServer { + engine := newAdminEngine() + return &httpServer{ + e: engine, + server: &http.Server{ + Addr: addr, + Handler: engine, + ReadTimeout: conf.AdminServerSetting.ReadTimeout, + WriteTimeout: conf.AdminServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } + }) + return &adminService{ + baseHttpService: &baseHttpService{ + server: server, + }, + } +} diff --git a/internal/service/bot.go b/internal/service/bot.go new file mode 100644 index 00000000..b9c66793 --- /dev/null +++ b/internal/service/bot.go @@ -0,0 +1,86 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "fmt" + "net/http" + + "github.com/fatih/color" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/servants" +) + +type botService struct { + *baseHttpService +} + +func (s *botService) Name() string { + return "BotService" +} + +func (s *botService) Init() error { + s.registerRoute(servants.RegisterBotServants) + return nil +} + +func (s *botService) String() string { + return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.BotServerSetting.HttpIp, conf.BotServerSetting.HttpPort)) +} + +func newBotEngine() *gin.Engine { + e := gin.New() + e.HandleMethodNotAllowed = true + e.Use(gin.Logger()) + e.Use(gin.Recovery()) + + // 跨域配置 + corsConfig := cors.DefaultConfig() + corsConfig.AllowAllOrigins = true + corsConfig.AddAllowHeaders("Authorization") + e.Use(cors.New(corsConfig)) + + // 默认404 + e.NoRoute(func(c *gin.Context) { + c.JSON(http.StatusNotFound, gin.H{ + "code": 404, + "msg": "Not Found", + }) + }) + + // 默认405 + e.NoMethod(func(c *gin.Context) { + c.JSON(http.StatusMethodNotAllowed, gin.H{ + "code": 405, + "msg": "Method Not Allowed", + }) + }) + + return e +} + +func newBotService() Service { + addr := conf.BotServerSetting.HttpIp + ":" + conf.BotServerSetting.HttpPort + server := httpServerFrom(addr, func() *httpServer { + engine := newBotEngine() + return &httpServer{ + e: engine, + server: &http.Server{ + Addr: addr, + Handler: engine, + ReadTimeout: conf.BotServerSetting.ReadTimeout, + WriteTimeout: conf.BotServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } + }) + return &botService{ + baseHttpService: &baseHttpService{ + server: server, + }, + } +} diff --git a/internal/service/localoss.go b/internal/service/localoss.go new file mode 100644 index 00000000..18dd79f9 --- /dev/null +++ b/internal/service/localoss.go @@ -0,0 +1,61 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "fmt" + "net/http" + + "github.com/fatih/color" + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/servants" +) + +type localossService struct { + *baseHttpService +} + +func (s *localossService) Name() string { + return "LocalossService" +} + +func (s *localossService) Init() error { + s.registerRoute(servants.RegisterLocalossServants) + return nil +} + +func (s *localossService) String() string { + return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.LocalossServerSetting.HttpIp, conf.LocalossServerSetting.HttpPort)) +} + +func newLocalossEngine() *gin.Engine { + e := gin.New() + e.Use(gin.Logger()) + e.Use(gin.Recovery()) + return e +} + +func newLocalossService() Service { + addr := conf.LocalossServerSetting.HttpIp + ":" + conf.LocalossServerSetting.HttpPort + server := httpServerFrom(addr, func() *httpServer { + engine := newLocalossEngine() + return &httpServer{ + e: engine, + server: &http.Server{ + Addr: addr, + Handler: engine, + ReadTimeout: conf.LocalossServerSetting.ReadTimeout, + WriteTimeout: conf.LocalossServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } + }) + return &localossService{ + baseHttpService: &baseHttpService{ + server: server, + }, + } +} diff --git a/internal/service/service.go b/internal/service/service.go index a69c8c91..549ae2f1 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -46,5 +46,20 @@ func newService() (ss []Service) { ss = append(ss, newOldWebService()) }) + cfg.In(cfg.Actions{ + "Admin": func() { + ss = append(ss, newAdminService()) + }, + "SpaceX": func() { + ss = append(ss, newSpaceXService()) + }, + "Bot": func() { + ss = append(ss, newBotService()) + }, + "LocalOSS": func() { + ss = append(ss, newLocalossService()) + }, + }) + return } diff --git a/internal/service/space.go b/internal/service/space.go new file mode 100644 index 00000000..3866c5ac --- /dev/null +++ b/internal/service/space.go @@ -0,0 +1,86 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "fmt" + "net/http" + + "github.com/fatih/color" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/servants" +) + +type spaceXService struct { + *baseHttpService +} + +func (s *spaceXService) Name() string { + return "WebService" +} + +func (s *spaceXService) Init() error { + s.registerRoute(servants.RegisterSpaceXServants) + return nil +} + +func (s *spaceXService) String() string { + return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.SpaceXServerSetting.HttpIp, conf.SpaceXServerSetting.HttpPort)) +} + +func newSpaceXEngine() *gin.Engine { + e := gin.New() + e.HandleMethodNotAllowed = true + e.Use(gin.Logger()) + e.Use(gin.Recovery()) + + // 跨域配置 + corsConfig := cors.DefaultConfig() + corsConfig.AllowAllOrigins = true + corsConfig.AddAllowHeaders("Authorization") + e.Use(cors.New(corsConfig)) + + // 默认404 + e.NoRoute(func(c *gin.Context) { + c.JSON(http.StatusNotFound, gin.H{ + "code": 404, + "msg": "Not Found", + }) + }) + + // 默认405 + e.NoMethod(func(c *gin.Context) { + c.JSON(http.StatusMethodNotAllowed, gin.H{ + "code": 405, + "msg": "Method Not Allowed", + }) + }) + + return e +} + +func newSpaceXService() Service { + addr := conf.SpaceXServerSetting.HttpIp + ":" + conf.SpaceXServerSetting.HttpPort + server := httpServerFrom(addr, func() *httpServer { + engine := newSpaceXEngine() + return &httpServer{ + e: engine, + server: &http.Server{ + Addr: addr, + Handler: engine, + ReadTimeout: conf.SpaceXServerSetting.ReadTimeout, + WriteTimeout: conf.SpaceXServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } + }) + return &spaceXService{ + baseHttpService: &baseHttpService{ + server: server, + }, + } +} From 0adfeee6aae51d6a960239e10b8888f347dc9d70 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 10 Dec 2022 16:16:28 +0800 Subject: [PATCH 20/28] mir: update mirc/README.md --- internal/mirc/auto/api/v1/web_core.go | 2 +- internal/mirc/main.go | 8 ++++---- internal/mirc/routes/README.md | 12 +++++++----- internal/mirc/routes/{m => admin}/README.md | 0 internal/mirc/routes/{m => admin}/v1/user.go | 0 internal/mirc/routes/{r => bot}/README.md | 0 internal/mirc/routes/{r => bot}/v1/user.go | 0 internal/mirc/routes/{s => localoss}/README.md | 0 internal/mirc/routes/{s => localoss}/v1/user.go | 0 internal/mirc/routes/{x => space}/README.md | 0 internal/mirc/routes/{x => space}/v1/user.go | 0 11 files changed, 12 insertions(+), 10 deletions(-) rename internal/mirc/routes/{m => admin}/README.md (100%) rename internal/mirc/routes/{m => admin}/v1/user.go (100%) rename internal/mirc/routes/{r => bot}/README.md (100%) rename internal/mirc/routes/{r => bot}/v1/user.go (100%) rename internal/mirc/routes/{s => localoss}/README.md (100%) rename internal/mirc/routes/{s => localoss}/v1/user.go (100%) rename internal/mirc/routes/{x => space}/README.md (100%) rename internal/mirc/routes/{x => space}/v1/user.go (100%) diff --git a/internal/mirc/auto/api/v1/web_core.go b/internal/mirc/auto/api/v1/web_core.go index 6f1efce6..3e7d3d65 100644 --- a/internal/mirc/auto/api/v1/web_core.go +++ b/internal/mirc/auto/api/v1/web_core.go @@ -86,8 +86,8 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor h := func(c *gin.Context) { r.RenderArticles(c, s.Articles(c)) } - router.Handle("GET", "/articles/:category/", h) router.Handle("HEAD", "/articles/:category/", h) + router.Handle("GET", "/articles/:category/", h) } router.Handle("GET", "/index/", func(c *gin.Context) { diff --git a/internal/mirc/main.go b/internal/mirc/main.go index 34120f36..6213d798 100644 --- a/internal/mirc/main.go +++ b/internal/mirc/main.go @@ -10,11 +10,11 @@ import ( . "github.com/alimy/mir/v3/core" . "github.com/alimy/mir/v3/engine" - _ "github.com/rocboss/paopao-ce/internal/mirc/routes/m/v1" - _ "github.com/rocboss/paopao-ce/internal/mirc/routes/r/v1" - _ "github.com/rocboss/paopao-ce/internal/mirc/routes/s/v1" + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/admin/v1" + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/bot/v1" + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/localoss/v1" + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/space/v1" _ "github.com/rocboss/paopao-ce/internal/mirc/routes/v1" - _ "github.com/rocboss/paopao-ce/internal/mirc/routes/x/v1" ) //go:generate go run main.go diff --git a/internal/mirc/routes/README.md b/internal/mirc/routes/README.md index d7d0b9fb..c592aa65 100644 --- a/internal/mirc/routes/README.md +++ b/internal/mirc/routes/README.md @@ -1,8 +1,10 @@ ### RESTful API for paopao-ce 本目录包含所有RESTful API相关定义文件 -* v1 - Web系列 v1版本 相关RESTful API相关定义文件 -* m - Admin后台运维系列相关RESTful API相关定义文件 -* x - SpaceX系列相关RESTful API相关定义文件 -* s - LocalOSS OBS系列RESTful API相关定义文件 -* r - Bot系列相关RESTful API相关定义文件 +|目录|系列API|备注| +| ----- | ----- | ----- | +|v1|/|Web v1版本RESTful API相关定义文件| +|admin|m|Admin后台运维系列相关RESTful API相关定义文件| +|space|x|SpaceX系列相关RESTful API相关定义文件| +|localoss|s| LocalOSS OBS系列RESTful API相关定义文件| +|bot|r| Bot系列相关RESTful API相关定义文件| diff --git a/internal/mirc/routes/m/README.md b/internal/mirc/routes/admin/README.md similarity index 100% rename from internal/mirc/routes/m/README.md rename to internal/mirc/routes/admin/README.md diff --git a/internal/mirc/routes/m/v1/user.go b/internal/mirc/routes/admin/v1/user.go similarity index 100% rename from internal/mirc/routes/m/v1/user.go rename to internal/mirc/routes/admin/v1/user.go diff --git a/internal/mirc/routes/r/README.md b/internal/mirc/routes/bot/README.md similarity index 100% rename from internal/mirc/routes/r/README.md rename to internal/mirc/routes/bot/README.md diff --git a/internal/mirc/routes/r/v1/user.go b/internal/mirc/routes/bot/v1/user.go similarity index 100% rename from internal/mirc/routes/r/v1/user.go rename to internal/mirc/routes/bot/v1/user.go diff --git a/internal/mirc/routes/s/README.md b/internal/mirc/routes/localoss/README.md similarity index 100% rename from internal/mirc/routes/s/README.md rename to internal/mirc/routes/localoss/README.md diff --git a/internal/mirc/routes/s/v1/user.go b/internal/mirc/routes/localoss/v1/user.go similarity index 100% rename from internal/mirc/routes/s/v1/user.go rename to internal/mirc/routes/localoss/v1/user.go diff --git a/internal/mirc/routes/x/README.md b/internal/mirc/routes/space/README.md similarity index 100% rename from internal/mirc/routes/x/README.md rename to internal/mirc/routes/space/README.md diff --git a/internal/mirc/routes/x/v1/user.go b/internal/mirc/routes/space/v1/user.go similarity index 100% rename from internal/mirc/routes/x/v1/user.go rename to internal/mirc/routes/space/v1/user.go From 6738df8913ec882f134eebb7189008c54ffe21e6 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sat, 10 Dec 2022 17:40:35 +0800 Subject: [PATCH 21/28] update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index abbc76d0..5c196532 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ PaoPao主要由以下优秀的开源项目/工具构建 * Redis * Zinc -\* Zinc是一款轻量级全文搜索引擎,可以查阅 安装 +> Zinc是一款轻量级全文搜索引擎,可以查阅 安装 以上环境版本为PaoPao官方的开发版本,仅供参考,其他版本的环境未进行充分测试 @@ -498,7 +498,7 @@ jc/alimy 代码结构比较简单,很方便扩展,开发文档请参阅[docs](docs '开发文档'). ## 👯‍♀️ 贡献 -paopao-ce 是一个利用 *业余时间* 本着 **"Just for fun just do it."** 的心态 *持续有序* **开发/优化/维护**的开源项目,没有KPI考核、没有Roadmap进度压力、没有技术支持日程安排,或许有些许不足之处,但是重在精神可嘉。 借用网络中的话 **"F\*k talk, f\*k of tech innovation, Shut up and give me your code."** 一切都因更好的体验,一切都是为了爱好,一切都在代码里;期待老铁们加入,一起开发、一起折腾、一起快乐。 +paopao-ce 是一个利用 *业余时间* 本着 **"Just for fun just do it."** 的心态 *持续有序* **开发/优化/维护**的开源项目,没有KPI考核、没有Roadmap进度压力、没有技术支持日程安排,或许有些许不足之处,但是重在精神可嘉。 借用网络中的话 **"F\*k talk, f\*k of tech innovation, Shut up and show me your code."** 一切都因更好的体验,一切都是为了爱好,一切都在代码里;期待老铁们加入,一起开发、一起折腾、一起快乐。 喜欢的朋友记得给个Star,欢迎贡献PR。 From 9e1d09a55dfbad1a95d5b7b79e0379505bfe81bd Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sun, 11 Dec 2022 11:27:53 +0800 Subject: [PATCH 22/28] use github.com/alimy/cfg as features configure help library --- go.mod | 1 + go.sum | 2 + internal/conf/conf.go | 4 +- internal/conf/db.go | 2 +- internal/conf/logger.go | 2 +- internal/dao/dao.go | 2 +- internal/dao/jinzhu/jinzhu.go | 2 +- internal/dao/storage/storage.go | 2 +- internal/migration/migration.go | 2 +- internal/migration/migration_embed.go | 2 +- internal/servants/chain/priv.go | 2 +- internal/servants/docs/docs_embed.go | 2 +- internal/servants/servants.go | 2 +- internal/servants/web/broker/broker.go | 2 +- internal/servants/web/routers/api/api.go | 2 +- internal/servants/web/routers/docs_embed.go | 2 +- internal/servants/web/routers/router.go | 2 +- internal/service/service.go | 2 +- pkg/cfg/cfg.go | 45 ------ pkg/cfg/cfg_test.go | 82 ----------- pkg/cfg/feature.go | 153 -------------------- pkg/cfg/feature_test.go | 118 --------------- 22 files changed, 20 insertions(+), 415 deletions(-) delete mode 100644 pkg/cfg/cfg.go delete mode 100644 pkg/cfg/cfg_test.go delete mode 100644 pkg/cfg/feature.go delete mode 100644 pkg/cfg/feature_test.go diff --git a/go.mod b/go.mod index fa9ff517..3ab5270f 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.18 require ( github.com/Masterminds/semver/v3 v3.1.1 github.com/afocus/captcha v0.0.0-20191010092841-4bd1f21c8868 + github.com/alimy/cfg v0.1.0 github.com/alimy/mir/v3 v3.0.0-alpha.4 github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible github.com/allegro/bigcache/v3 v3.0.2 diff --git a/go.sum b/go.sum index bfe083a0..eed23c9b 100644 --- a/go.sum +++ b/go.sum @@ -142,6 +142,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk= +github.com/alimy/cfg v0.1.0 h1:J7KDLEoVIjEBMGlQJb2ljad/d49gJ4Tsl2ogZ9XNhaY= +github.com/alimy/cfg v0.1.0/go.mod h1:rOxbasTH2srl6StAjNF5Vyi8bfrdkl3fLGmOYtSw81c= github.com/alimy/mir/v3 v3.0.0-alpha.4 h1:tSmyyhgutMHjgx9TO9891ZCY4qbr3g8FGar4z+9Hhq4= github.com/alimy/mir/v3 v3.0.0-alpha.4/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM= diff --git a/internal/conf/conf.go b/internal/conf/conf.go index 75d363e7..bdadf5e4 100644 --- a/internal/conf/conf.go +++ b/internal/conf/conf.go @@ -9,7 +9,7 @@ import ( "sync" "time" - "github.com/rocboss/paopao-ce/pkg/cfg" + "github.com/alimy/cfg" ) var ( @@ -58,7 +58,7 @@ func setupSetting(suite []string, noDefault bool) error { // initialize features configure ss, kv := setting.featuresInfoFrom("Features") - cfg.Initialize(ss, kv) + cfg.Initial(ss, kv) if len(suite) > 0 { cfg.Use(suite, noDefault) } diff --git a/internal/conf/db.go b/internal/conf/db.go index 7f859152..62ad7fe3 100644 --- a/internal/conf/db.go +++ b/internal/conf/db.go @@ -8,8 +8,8 @@ import ( "sync" "time" + "github.com/alimy/cfg" "github.com/go-redis/redis/v8" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" "gorm.io/driver/mysql" "gorm.io/driver/postgres" diff --git a/internal/conf/logger.go b/internal/conf/logger.go index b514b375..cbe3cc1b 100644 --- a/internal/conf/logger.go +++ b/internal/conf/logger.go @@ -7,7 +7,7 @@ package conf import ( "io" - "github.com/rocboss/paopao-ce/pkg/cfg" + "github.com/alimy/cfg" "github.com/sirupsen/logrus" "gopkg.in/natefinch/lumberjack.v2" ) diff --git a/internal/dao/dao.go b/internal/dao/dao.go index e4b2ea6a..d0b05c9c 100644 --- a/internal/dao/dao.go +++ b/internal/dao/dao.go @@ -7,13 +7,13 @@ package dao import ( "sync" + "github.com/alimy/cfg" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/dao/jinzhu" "github.com/rocboss/paopao-ce/internal/dao/sakila" "github.com/rocboss/paopao-ce/internal/dao/search" "github.com/rocboss/paopao-ce/internal/dao/slonik" "github.com/rocboss/paopao-ce/internal/dao/storage" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) diff --git a/internal/dao/jinzhu/jinzhu.go b/internal/dao/jinzhu/jinzhu.go index 753bb639..dd20aeea 100644 --- a/internal/dao/jinzhu/jinzhu.go +++ b/internal/dao/jinzhu/jinzhu.go @@ -10,11 +10,11 @@ package jinzhu import ( "github.com/Masterminds/semver/v3" + "github.com/alimy/cfg" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/dao/cache" "github.com/rocboss/paopao-ce/internal/dao/security" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) diff --git a/internal/dao/storage/storage.go b/internal/dao/storage/storage.go index fff9d13f..0f03fa20 100644 --- a/internal/dao/storage/storage.go +++ b/internal/dao/storage/storage.go @@ -12,13 +12,13 @@ import ( "strconv" "time" + "github.com/alimy/cfg" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" "github.com/tencentyun/cos-go-sdk-v5" ) diff --git a/internal/migration/migration.go b/internal/migration/migration.go index 7437e996..1cac6012 100644 --- a/internal/migration/migration.go +++ b/internal/migration/migration.go @@ -8,7 +8,7 @@ package migration import ( - "github.com/rocboss/paopao-ce/pkg/cfg" + "github.com/alimy/cfg" "github.com/sirupsen/logrus" ) diff --git a/internal/migration/migration_embed.go b/internal/migration/migration_embed.go index 976b4f26..02ede293 100644 --- a/internal/migration/migration_embed.go +++ b/internal/migration/migration_embed.go @@ -10,6 +10,7 @@ package migration import ( "database/sql" + "github.com/alimy/cfg" "github.com/golang-migrate/migrate/v4" "github.com/golang-migrate/migrate/v4/database" "github.com/golang-migrate/migrate/v4/database/mysql" @@ -18,7 +19,6 @@ import ( "github.com/golang-migrate/migrate/v4/source" "github.com/golang-migrate/migrate/v4/source/iofs" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/rocboss/paopao-ce/scripts/migration" "github.com/sirupsen/logrus" ) diff --git a/internal/servants/chain/priv.go b/internal/servants/chain/priv.go index f03c14b7..6c09d0a8 100644 --- a/internal/servants/chain/priv.go +++ b/internal/servants/chain/priv.go @@ -5,10 +5,10 @@ package chain import ( + "github.com/alimy/cfg" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/app" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/rocboss/paopao-ce/pkg/errcode" ) diff --git a/internal/servants/docs/docs_embed.go b/internal/servants/docs/docs_embed.go index 653e1c07..8879896c 100644 --- a/internal/servants/docs/docs_embed.go +++ b/internal/servants/docs/docs_embed.go @@ -8,9 +8,9 @@ package docs import ( + "github.com/alimy/cfg" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/docs/openapi" - "github.com/rocboss/paopao-ce/pkg/cfg" ) // RegisterDocs register docs asset route diff --git a/internal/servants/servants.go b/internal/servants/servants.go index 496a60c1..dd03b1de 100644 --- a/internal/servants/servants.go +++ b/internal/servants/servants.go @@ -5,6 +5,7 @@ package servants import ( + "github.com/alimy/cfg" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/servants/admin" "github.com/rocboss/paopao-ce/internal/servants/bot" @@ -13,7 +14,6 @@ import ( "github.com/rocboss/paopao-ce/internal/servants/space" "github.com/rocboss/paopao-ce/internal/servants/statick" "github.com/rocboss/paopao-ce/internal/servants/web" - "github.com/rocboss/paopao-ce/pkg/cfg" ) // RegisterWebServants register all the servants to gin.Engine diff --git a/internal/servants/web/broker/broker.go b/internal/servants/web/broker/broker.go index 79423901..fcc5846d 100644 --- a/internal/servants/web/broker/broker.go +++ b/internal/servants/web/broker/broker.go @@ -5,9 +5,9 @@ package broker import ( + "github.com/alimy/cfg" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/dao" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) diff --git a/internal/servants/web/routers/api/api.go b/internal/servants/web/routers/api/api.go index 39e748ab..b2e60cb6 100644 --- a/internal/servants/web/routers/api/api.go +++ b/internal/servants/web/routers/api/api.go @@ -5,10 +5,10 @@ package api import ( + "github.com/alimy/cfg" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/dao" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" "github.com/smartwalle/alipay/v3" ) diff --git a/internal/servants/web/routers/docs_embed.go b/internal/servants/web/routers/docs_embed.go index a636e487..20754e1a 100644 --- a/internal/servants/web/routers/docs_embed.go +++ b/internal/servants/web/routers/docs_embed.go @@ -8,9 +8,9 @@ package routers import ( + "github.com/alimy/cfg" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/docs/openapi" - "github.com/rocboss/paopao-ce/pkg/cfg" ) // registerDocs register docs asset route diff --git a/internal/servants/web/routers/router.go b/internal/servants/web/routers/router.go index e46b533b..80b29be3 100644 --- a/internal/servants/web/routers/router.go +++ b/internal/servants/web/routers/router.go @@ -8,12 +8,12 @@ import ( "net/http" "path/filepath" + "github.com/alimy/cfg" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/servants/chain" "github.com/rocboss/paopao-ce/internal/servants/web/routers/api" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) diff --git a/internal/service/service.go b/internal/service/service.go index 549ae2f1..34a04574 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -7,7 +7,7 @@ package service import ( "log" - "github.com/rocboss/paopao-ce/pkg/cfg" + "github.com/alimy/cfg" "github.com/rocboss/paopao-ce/pkg/types" ) diff --git a/pkg/cfg/cfg.go b/pkg/cfg/cfg.go deleted file mode 100644 index f04dc297..00000000 --- a/pkg/cfg/cfg.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2022 ROC. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package cfg - -var ( - _features = newEmptyFeatures() - - // Use alias of Features.Use func - Use = _features.Use - - // UseDeafult alias of Features.UseDefault func - UseDefault = _features.UseDefault - - // As alias of Features.Cfg func - As = _features.Cfg - - // If alias of Features.CfgIf func - If = _features.CfgIf - - // In alias of Features.CfgIn func - In = _features.CfgIn - - // Be alias of Feaures.CfgBe func - Be = _features.CfgBe - - // Not alias of Features.CfgNot func - Not = _features.CfgNot -) - -// Initialize initialize features in cfg pkg -func Initialize(suites map[string][]string, kv map[string]string) { - _features = NewFeatures(suites, kv) - { - // must re-assign variable below - Use = _features.Use - UseDefault = _features.UseDefault - As = _features.Cfg - If = _features.CfgIf - In = _features.CfgIn - Be = _features.CfgBe - Not = _features.CfgNot - } -} diff --git a/pkg/cfg/cfg_test.go b/pkg/cfg/cfg_test.go deleted file mode 100644 index 68a3ce74..00000000 --- a/pkg/cfg/cfg_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2022 ROC. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package cfg - -import ( - "testing" -) - -func TestCfg(t *testing.T) { - suites := map[string][]string{ - "default": {"Sms", "Alipay", "Zinc", "MySQL", "Redis", "AliOSS", "LogZinc"}, - "develop": {"Zinc", "MySQL", "AliOSS", "LogFile"}, - "slim": {"Zinc", "MySQL", "Redis", "AliOSS", "LogFile"}, - } - kv := map[string]string{ - "sms": "SmsJuhe", - } - - Initialize(suites, kv) - UseDefault() - - if !If("Sms") { - t.Error(`want If("Sms") == true but not`) - } - - if v, exist := As("Sms"); exist && v != "SmsJuhe" { - t.Errorf(`want As("Sms") == "SmsJuhe", true but got: "%s", "%t"`, v, exist) - } - - matched := false - Be("Alipay", func() { - matched = true - }) - if !matched { - t.Error(`want Be("Alipay", ...) matched but not`) - } - - matched = false - Not("LogFile", func() { - matched = true - }) - if !matched { - t.Error(`want Not("LogFile", ...) matched but not`) - } - - var m1, m2, m3, m4 bool - In(Actions{ - "Sms": func() { - m1 = true - }, - "Alipay": func() { - m2 = true - }, - "Meili": func() { - m4 = true - }, - }, func() { - m3 = true - }) - if !m1 || !m2 || m3 || m4 { - t.Errorf(`In("Sms", "Alipay", "Meili", ...) not correct -> m1: %t m2:%t m3:%t m4:%t`, m1, m2, m3, m4) - } - - m1 = false - m2 = false - m3 = false - In(Actions{ - "LogFile": func() { - m1 = true - }, - "Meili": func() { - m2 = true - }, - }, func() { - m3 = true - }) - if m1 || m2 || !m3 { - t.Errorf(`In("Zinc", "MySQL", ...) not correct -> m1: %t m2:%t m3:%t`, m1, m2, m3) - } -} diff --git a/pkg/cfg/feature.go b/pkg/cfg/feature.go deleted file mode 100644 index 32810b47..00000000 --- a/pkg/cfg/feature.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2022 ROC. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package cfg - -import ( - "strings" - - "github.com/rocboss/paopao-ce/pkg/types" -) - -// Features fetures info struct -type Features struct { - kv map[string]string - suites map[string][]string - features map[string]string -} - -// Actions feature-func map alias type -type Actions map[string]types.Fn - -// NewFeatures create new Features instance -func NewFeatures(suites map[string][]string, kv map[string]string) *Features { - f := newEmptyFeatures() - for k, v := range suites { - if len(k) > 0 { - for i := 0; i < len(v); i++ { - // ignore empty string - if len(v[i]) == 0 { - lastIdx := len(v) - 1 - v[i] = v[lastIdx] - v = v[:lastIdx] - i-- - } - } - if len(v) > 0 { - f.suites[k] = v - } - } - } - for k, v := range kv { - if len(k) > 0 && len(v) > 0 { - f.kv[k] = v - } - } - f.UseDefault() - return f -} - -func newEmptyFeatures() *Features { - return &Features{ - suites: make(map[string][]string), - kv: make(map[string]string), - features: make(map[string]string), - } -} - -// UseDefault use default suite for features -func (f *Features) UseDefault() { - f.Use([]string{"default"}, true) -} - -// Use use custom suite for features -func (f *Features) Use(suite []string, noDefault bool) { - if noDefault && len(f.features) != 0 { - f.features = make(map[string]string) - } - features := f.flatFeatures(suite) - for _, feature := range features { - if len(feature) == 0 { - continue - } - f.features[feature] = f.kv[feature] - } -} - -func (f *Features) flatFeatures(suite []string) []string { - features := make([]string, 0, len(suite)+10) - for s := suite[:]; len(s) > 0; s = s[:len(s)-1] { - item := strings.TrimSpace(strings.ToLower(s[0])) - if len(item) > 0 { - if items, exist := f.suites[item]; exist { - s = append(s, items...) - } - features = append(features, item) - } - s[0] = s[len(s)-1] - } - return features -} - -// Cfg get value by key if exist -func (f *Features) Cfg(key string) (string, bool) { - key = strings.ToLower(key) - value, exist := f.features[key] - return value, exist -} - -// CfgIf check expression is true. if expression just have a string like -// `Sms` is mean `Sms` whether define in suite feature settings. expression like -// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value -// is `SmsJuhe` -func (f *Features) CfgIf(expression string) bool { - kv := strings.Split(expression, "=") - key := strings.Trim(strings.ToLower(kv[0]), " ") - v, ok := f.features[key] - if len(kv) == 2 && ok && strings.Trim(kv[1], " ") == v { - return true - } else if len(kv) == 1 && ok { - return true - } - return false -} - -// CfgIn range actions to check item's expression is true then do the handle, defFn will handle -// if all items are not matched, -func (f *Features) CfgIn(actions Actions, defAct ...types.Fn) { - itemMatched := false - for expression, handle := range actions { - if f.CfgIf(expression) && handle != nil { - handle() - itemMatched = true - } - } - if !itemMatched && len(defAct) > 0 { - for _, handle := range defAct { - if handle != nil { - handle() - } - } - } -} - -// CfgBe check expression is true then do the handle. if expression just have a string like -// `Sms` is mean `Sms` whether defined in suite feature settings. expression like -// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value -// is `SmsJuhe` -func (f *Features) CfgBe(expression string, handle types.Fn) { - if f.CfgIf(expression) && handle != nil { - handle() - } -} - -// CfgNot check expression is not true then do the handle. if expression just have a string like -// `Sms` is mean `Sms` whether defined in suite feature settings. expression like -// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value -// is `SmsJuhe` -func (f *Features) CfgNot(expression string, handle func()) { - if !f.CfgIf(expression) { - handle() - } -} diff --git a/pkg/cfg/feature_test.go b/pkg/cfg/feature_test.go deleted file mode 100644 index 21c44c72..00000000 --- a/pkg/cfg/feature_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2022 ROC. All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package cfg - -import ( - "testing" -) - -func TestUseDefault(t *testing.T) { - suites := map[string][]string{ - "default": {"Sms", "Alipay", "Zinc", "MySQL", "Redis", "AliOSS", "LogZinc"}, - "develop": {"Zinc", "MySQL", "AliOSS", "LogFile"}, - "slim": {"Zinc", "MySQL", "Redis", "AliOSS", "LogFile"}, - } - kv := map[string]string{ - "sms": "SmsJuhe", - } - f := NewFeatures(suites, kv) - for _, data := range []struct { - key string - expect string - exist bool - }{ - {"Sms", "SmsJuhe", true}, - {"Alipay", "", true}, - {"Zinc", "", true}, - {"Redis", "", true}, - {"Database", "", false}, - } { - if v, ok := f.Cfg(data.key); ok != data.exist || v != data.expect { - t.Errorf("key: %s expect: %s exist: %t got v: %s ok: %t", data.key, data.expect, data.exist, v, ok) - } - } - for exp, res := range map[string]bool{ - "Sms": true, - "Sms = SmsJuhe": true, - "SmsJuhe": false, - "default": true, - } { - if ok := f.CfgIf(exp); res != ok { - t.Errorf("CfgIf(%s) want %t got %t", exp, res, ok) - } - } -} - -func TestUse(t *testing.T) { - suites := map[string][]string{ - "default": {"Sms", "Alipay", "Zinc", "MySQL", "Redis", "AliOSS", "LogZinc"}, - "develop": {"Zinc", "MySQL", "AliOSS", "LogFile"}, - "slim": {"Zinc", "MySQL", "Redis", "AliOSS", "LogFile"}, - } - kv := map[string]string{ - "sms": "SmsJuhe", - } - f := NewFeatures(suites, kv) - - f.Use([]string{"develop"}, true) - for _, data := range []struct { - key string - expect string - exist bool - }{ - {"Sms", "", false}, - {"Alipay", "", false}, - {"Zinc", "", true}, - {"Redis", "", false}, - {"Database", "", false}, - } { - if v, ok := f.Cfg(data.key); ok != data.exist || v != data.expect { - t.Errorf("key: %s expect: %s exist: %t got v: %s ok: %t", data.key, data.expect, data.exist, v, ok) - } - } - for exp, res := range map[string]bool{ - "Sms": false, - "Sms = SmsJuhe": false, - "SmsJuhe": false, - "default": false, - "develop": true, - } { - if ok := f.CfgIf(exp); res != ok { - t.Errorf("CfgIf(%s) want %t got %t", exp, res, ok) - } - } - - f.UseDefault() - f.Use([]string{"slim", "", "demo"}, false) - for _, data := range []struct { - key string - expect string - exist bool - }{ - {"Sms", "SmsJuhe", true}, - {"Alipay", "", true}, - {"Zinc", "", true}, - {"Redis", "", true}, - {"Database", "", false}, - {"demo", "", true}, - } { - if v, ok := f.Cfg(data.key); ok != data.exist || v != data.expect { - t.Errorf("key: %s expect: %s exist: %t got v: %s ok: %t", data.key, data.expect, data.exist, v, ok) - } - } - for exp, res := range map[string]bool{ - "Sms": true, - "Sms = SmsJuhe": true, - "SmsJuhe": false, - "default": true, - "develop": false, - "slim": true, - "demo": true, - } { - if ok := f.CfgIf(exp); res != ok { - t.Errorf("CfgIf(%s) want %t got %t", exp, res, ok) - } - } -} From 72136a22666583cc4a80ae219a378c2c4d2f7098 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Sun, 11 Dec 2022 11:44:42 +0800 Subject: [PATCH 23/28] use github.com/alimy/cfg as features configure help library --- go.mod | 1 + go.sum | 2 + internal/conf/conf.go | 4 +- internal/conf/db.go | 2 +- internal/conf/logger.go | 2 +- internal/dao/dao.go | 2 +- internal/dao/jinzhu/jinzhu.go | 2 +- internal/dao/storage/storage.go | 2 +- internal/middleware/priv.go | 2 +- internal/migration/migration.go | 2 +- internal/migration/migration_embed.go | 2 +- internal/routers/api/api.go | 2 +- internal/routers/docs_embed.go | 2 +- internal/routers/router.go | 2 +- internal/service/service.go | 2 +- pkg/cfg/cfg.go | 41 ------- pkg/cfg/cfg_test.go | 78 -------------- pkg/cfg/feature.go | 149 -------------------------- pkg/cfg/feature_test.go | 114 -------------------- 19 files changed, 17 insertions(+), 396 deletions(-) delete mode 100644 pkg/cfg/cfg.go delete mode 100644 pkg/cfg/cfg_test.go delete mode 100644 pkg/cfg/feature.go delete mode 100644 pkg/cfg/feature_test.go diff --git a/go.mod b/go.mod index 8f4c9435..0215af0f 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.18 require ( github.com/Masterminds/semver/v3 v3.1.1 github.com/afocus/captcha v0.0.0-20191010092841-4bd1f21c8868 + github.com/alimy/cfg v0.1.0 github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible github.com/allegro/bigcache/v3 v3.0.2 github.com/bytedance/sonic v1.5.0 diff --git a/go.sum b/go.sum index 9221a97a..7262bc9a 100644 --- a/go.sum +++ b/go.sum @@ -142,6 +142,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk= +github.com/alimy/cfg v0.1.0 h1:J7KDLEoVIjEBMGlQJb2ljad/d49gJ4Tsl2ogZ9XNhaY= +github.com/alimy/cfg v0.1.0/go.mod h1:rOxbasTH2srl6StAjNF5Vyi8bfrdkl3fLGmOYtSw81c= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= diff --git a/internal/conf/conf.go b/internal/conf/conf.go index 97512264..3ede82d6 100644 --- a/internal/conf/conf.go +++ b/internal/conf/conf.go @@ -5,7 +5,7 @@ import ( "sync" "time" - "github.com/rocboss/paopao-ce/pkg/cfg" + "github.com/alimy/cfg" ) var ( @@ -48,7 +48,7 @@ func setupSetting(suite []string, noDefault bool) error { // initialize features configure ss, kv := setting.featuresInfoFrom("Features") - cfg.Initialize(ss, kv) + cfg.Initial(ss, kv) if len(suite) > 0 { cfg.Use(suite, noDefault) } diff --git a/internal/conf/db.go b/internal/conf/db.go index ef4f7c92..6ad7cd6e 100644 --- a/internal/conf/db.go +++ b/internal/conf/db.go @@ -4,8 +4,8 @@ import ( "sync" "time" + "github.com/alimy/cfg" "github.com/go-redis/redis/v8" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" "gorm.io/driver/mysql" "gorm.io/driver/postgres" diff --git a/internal/conf/logger.go b/internal/conf/logger.go index c65612dc..40b3500b 100644 --- a/internal/conf/logger.go +++ b/internal/conf/logger.go @@ -3,7 +3,7 @@ package conf import ( "io" - "github.com/rocboss/paopao-ce/pkg/cfg" + "github.com/alimy/cfg" "github.com/sirupsen/logrus" "gopkg.in/natefinch/lumberjack.v2" ) diff --git a/internal/dao/dao.go b/internal/dao/dao.go index 6f4a776a..f0244d3b 100644 --- a/internal/dao/dao.go +++ b/internal/dao/dao.go @@ -3,13 +3,13 @@ package dao import ( "sync" + "github.com/alimy/cfg" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/dao/jinzhu" "github.com/rocboss/paopao-ce/internal/dao/sakila" "github.com/rocboss/paopao-ce/internal/dao/search" "github.com/rocboss/paopao-ce/internal/dao/slonik" "github.com/rocboss/paopao-ce/internal/dao/storage" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) diff --git a/internal/dao/jinzhu/jinzhu.go b/internal/dao/jinzhu/jinzhu.go index 9f5e1c66..b3eb550f 100644 --- a/internal/dao/jinzhu/jinzhu.go +++ b/internal/dao/jinzhu/jinzhu.go @@ -6,11 +6,11 @@ package jinzhu import ( "github.com/Masterminds/semver/v3" + "github.com/alimy/cfg" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/dao/cache" "github.com/rocboss/paopao-ce/internal/dao/security" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) diff --git a/internal/dao/storage/storage.go b/internal/dao/storage/storage.go index 8e124047..c25d2907 100644 --- a/internal/dao/storage/storage.go +++ b/internal/dao/storage/storage.go @@ -8,13 +8,13 @@ import ( "strconv" "time" + "github.com/alimy/cfg" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" "github.com/tencentyun/cos-go-sdk-v5" ) diff --git a/internal/middleware/priv.go b/internal/middleware/priv.go index fe31b008..e479c6b1 100644 --- a/internal/middleware/priv.go +++ b/internal/middleware/priv.go @@ -1,10 +1,10 @@ package middleware import ( + "github.com/alimy/cfg" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/app" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/rocboss/paopao-ce/pkg/errcode" ) diff --git a/internal/migration/migration.go b/internal/migration/migration.go index 44c16fb4..9563f803 100644 --- a/internal/migration/migration.go +++ b/internal/migration/migration.go @@ -4,7 +4,7 @@ package migration import ( - "github.com/rocboss/paopao-ce/pkg/cfg" + "github.com/alimy/cfg" "github.com/sirupsen/logrus" ) diff --git a/internal/migration/migration_embed.go b/internal/migration/migration_embed.go index 84952538..c6a0ae34 100644 --- a/internal/migration/migration_embed.go +++ b/internal/migration/migration_embed.go @@ -6,6 +6,7 @@ package migration import ( "database/sql" + "github.com/alimy/cfg" "github.com/golang-migrate/migrate/v4" "github.com/golang-migrate/migrate/v4/database" "github.com/golang-migrate/migrate/v4/database/mysql" @@ -14,7 +15,6 @@ import ( "github.com/golang-migrate/migrate/v4/source" "github.com/golang-migrate/migrate/v4/source/iofs" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/rocboss/paopao-ce/scripts/migration" "github.com/sirupsen/logrus" ) diff --git a/internal/routers/api/api.go b/internal/routers/api/api.go index c722ac88..17d56d7c 100644 --- a/internal/routers/api/api.go +++ b/internal/routers/api/api.go @@ -1,10 +1,10 @@ package api import ( + "github.com/alimy/cfg" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/dao" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" "github.com/smartwalle/alipay/v3" ) diff --git a/internal/routers/docs_embed.go b/internal/routers/docs_embed.go index e9c0d17d..443f5c0a 100644 --- a/internal/routers/docs_embed.go +++ b/internal/routers/docs_embed.go @@ -4,9 +4,9 @@ package routers import ( + "github.com/alimy/cfg" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/docs/openapi" - "github.com/rocboss/paopao-ce/pkg/cfg" ) // registerDocs register docs asset route diff --git a/internal/routers/router.go b/internal/routers/router.go index 1a2b57f6..354b4abe 100644 --- a/internal/routers/router.go +++ b/internal/routers/router.go @@ -4,12 +4,12 @@ import ( "net/http" "path/filepath" + "github.com/alimy/cfg" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/middleware" "github.com/rocboss/paopao-ce/internal/routers/api" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) diff --git a/internal/service/service.go b/internal/service/service.go index 9d7d4c01..bb70e9f8 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -1,10 +1,10 @@ package service import ( + "github.com/alimy/cfg" "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/internal/dao" "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) diff --git a/pkg/cfg/cfg.go b/pkg/cfg/cfg.go deleted file mode 100644 index 019deba9..00000000 --- a/pkg/cfg/cfg.go +++ /dev/null @@ -1,41 +0,0 @@ -package cfg - -var ( - _features = newEmptyFeatures() - - // Use alias of Features.Use func - Use = _features.Use - - // UseDeafult alias of Features.UseDefault func - UseDefault = _features.UseDefault - - // As alias of Features.Cfg func - As = _features.Cfg - - // If alias of Features.CfgIf func - If = _features.CfgIf - - // In alias of Features.CfgIn func - In = _features.CfgIn - - // Be alias of Feaures.CfgBe func - Be = _features.CfgBe - - // Not alias of Features.CfgNot func - Not = _features.CfgNot -) - -// Initialize initialize features in cfg pkg -func Initialize(suites map[string][]string, kv map[string]string) { - _features = NewFeatures(suites, kv) - { - // must re-assign variable below - Use = _features.Use - UseDefault = _features.UseDefault - As = _features.Cfg - If = _features.CfgIf - In = _features.CfgIn - Be = _features.CfgBe - Not = _features.CfgNot - } -} diff --git a/pkg/cfg/cfg_test.go b/pkg/cfg/cfg_test.go deleted file mode 100644 index 0fccbce2..00000000 --- a/pkg/cfg/cfg_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package cfg - -import ( - "testing" -) - -func TestCfg(t *testing.T) { - suites := map[string][]string{ - "default": {"Sms", "Alipay", "Zinc", "MySQL", "Redis", "AliOSS", "LogZinc"}, - "develop": {"Zinc", "MySQL", "AliOSS", "LogFile"}, - "slim": {"Zinc", "MySQL", "Redis", "AliOSS", "LogFile"}, - } - kv := map[string]string{ - "sms": "SmsJuhe", - } - - Initialize(suites, kv) - UseDefault() - - if !If("Sms") { - t.Error(`want If("Sms") == true but not`) - } - - if v, exist := As("Sms"); exist && v != "SmsJuhe" { - t.Errorf(`want As("Sms") == "SmsJuhe", true but got: "%s", "%t"`, v, exist) - } - - matched := false - Be("Alipay", func() { - matched = true - }) - if !matched { - t.Error(`want Be("Alipay", ...) matched but not`) - } - - matched = false - Not("LogFile", func() { - matched = true - }) - if !matched { - t.Error(`want Not("LogFile", ...) matched but not`) - } - - var m1, m2, m3, m4 bool - In(Actions{ - "Sms": func() { - m1 = true - }, - "Alipay": func() { - m2 = true - }, - "Meili": func() { - m4 = true - }, - }, func() { - m3 = true - }) - if !m1 || !m2 || m3 || m4 { - t.Errorf(`In("Sms", "Alipay", "Meili", ...) not correct -> m1: %t m2:%t m3:%t m4:%t`, m1, m2, m3, m4) - } - - m1 = false - m2 = false - m3 = false - In(Actions{ - "LogFile": func() { - m1 = true - }, - "Meili": func() { - m2 = true - }, - }, func() { - m3 = true - }) - if m1 || m2 || !m3 { - t.Errorf(`In("Zinc", "MySQL", ...) not correct -> m1: %t m2:%t m3:%t`, m1, m2, m3) - } -} diff --git a/pkg/cfg/feature.go b/pkg/cfg/feature.go deleted file mode 100644 index a04d07ca..00000000 --- a/pkg/cfg/feature.go +++ /dev/null @@ -1,149 +0,0 @@ -package cfg - -import ( - "strings" - - "github.com/rocboss/paopao-ce/pkg/types" -) - -// Features fetures info struct -type Features struct { - kv map[string]string - suites map[string][]string - features map[string]string -} - -// Actions feature-func map alias type -type Actions map[string]types.Fn - -// NewFeatures create new Features instance -func NewFeatures(suites map[string][]string, kv map[string]string) *Features { - f := newEmptyFeatures() - for k, v := range suites { - if len(k) > 0 { - for i := 0; i < len(v); i++ { - // ignore empty string - if len(v[i]) == 0 { - lastIdx := len(v) - 1 - v[i] = v[lastIdx] - v = v[:lastIdx] - i-- - } - } - if len(v) > 0 { - f.suites[k] = v - } - } - } - for k, v := range kv { - if len(k) > 0 && len(v) > 0 { - f.kv[k] = v - } - } - f.UseDefault() - return f -} - -func newEmptyFeatures() *Features { - return &Features{ - suites: make(map[string][]string), - kv: make(map[string]string), - features: make(map[string]string), - } -} - -// UseDefault use default suite for features -func (f *Features) UseDefault() { - f.Use([]string{"default"}, true) -} - -// Use use custom suite for features -func (f *Features) Use(suite []string, noDefault bool) { - if noDefault && len(f.features) != 0 { - f.features = make(map[string]string) - } - features := f.flatFeatures(suite) - for _, feature := range features { - if len(feature) == 0 { - continue - } - f.features[feature] = f.kv[feature] - } -} - -func (f *Features) flatFeatures(suite []string) []string { - features := make([]string, 0, len(suite)+10) - for s := suite[:]; len(s) > 0; s = s[:len(s)-1] { - item := strings.TrimSpace(strings.ToLower(s[0])) - if len(item) > 0 { - if items, exist := f.suites[item]; exist { - s = append(s, items...) - } - features = append(features, item) - } - s[0] = s[len(s)-1] - } - return features -} - -// Cfg get value by key if exist -func (f *Features) Cfg(key string) (string, bool) { - key = strings.ToLower(key) - value, exist := f.features[key] - return value, exist -} - -// CfgIf check expression is true. if expression just have a string like -// `Sms` is mean `Sms` whether define in suite feature settings. expression like -// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value -// is `SmsJuhe` -func (f *Features) CfgIf(expression string) bool { - kv := strings.Split(expression, "=") - key := strings.Trim(strings.ToLower(kv[0]), " ") - v, ok := f.features[key] - if len(kv) == 2 && ok && strings.Trim(kv[1], " ") == v { - return true - } else if len(kv) == 1 && ok { - return true - } - return false -} - -// CfgIn range actions to check item's expression is true then do the handle, defFn will handle -// if all items are not matched, -func (f *Features) CfgIn(actions Actions, defAct ...types.Fn) { - itemMatched := false - for expression, handle := range actions { - if f.CfgIf(expression) && handle != nil { - handle() - itemMatched = true - } - } - if !itemMatched && len(defAct) > 0 { - for _, handle := range defAct { - if handle != nil { - handle() - } - } - } -} - -// CfgBe check expression is true then do the handle. if expression just have a string like -// `Sms` is mean `Sms` whether defined in suite feature settings. expression like -// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value -// is `SmsJuhe` -func (f *Features) CfgBe(expression string, handle types.Fn) { - if f.CfgIf(expression) && handle != nil { - handle() - } -} - -// CfgNot check expression is not true then do the handle. if expression just have a string like -// `Sms` is mean `Sms` whether defined in suite feature settings. expression like -// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value -// is `SmsJuhe` -func (f *Features) CfgNot(expression string, handle func()) { - if !f.CfgIf(expression) { - handle() - } -} diff --git a/pkg/cfg/feature_test.go b/pkg/cfg/feature_test.go deleted file mode 100644 index 98e01ec7..00000000 --- a/pkg/cfg/feature_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package cfg - -import ( - "testing" -) - -func TestUseDefault(t *testing.T) { - suites := map[string][]string{ - "default": {"Sms", "Alipay", "Zinc", "MySQL", "Redis", "AliOSS", "LogZinc"}, - "develop": {"Zinc", "MySQL", "AliOSS", "LogFile"}, - "slim": {"Zinc", "MySQL", "Redis", "AliOSS", "LogFile"}, - } - kv := map[string]string{ - "sms": "SmsJuhe", - } - f := NewFeatures(suites, kv) - for _, data := range []struct { - key string - expect string - exist bool - }{ - {"Sms", "SmsJuhe", true}, - {"Alipay", "", true}, - {"Zinc", "", true}, - {"Redis", "", true}, - {"Database", "", false}, - } { - if v, ok := f.Cfg(data.key); ok != data.exist || v != data.expect { - t.Errorf("key: %s expect: %s exist: %t got v: %s ok: %t", data.key, data.expect, data.exist, v, ok) - } - } - for exp, res := range map[string]bool{ - "Sms": true, - "Sms = SmsJuhe": true, - "SmsJuhe": false, - "default": true, - } { - if ok := f.CfgIf(exp); res != ok { - t.Errorf("CfgIf(%s) want %t got %t", exp, res, ok) - } - } -} - -func TestUse(t *testing.T) { - suites := map[string][]string{ - "default": {"Sms", "Alipay", "Zinc", "MySQL", "Redis", "AliOSS", "LogZinc"}, - "develop": {"Zinc", "MySQL", "AliOSS", "LogFile"}, - "slim": {"Zinc", "MySQL", "Redis", "AliOSS", "LogFile"}, - } - kv := map[string]string{ - "sms": "SmsJuhe", - } - f := NewFeatures(suites, kv) - - f.Use([]string{"develop"}, true) - for _, data := range []struct { - key string - expect string - exist bool - }{ - {"Sms", "", false}, - {"Alipay", "", false}, - {"Zinc", "", true}, - {"Redis", "", false}, - {"Database", "", false}, - } { - if v, ok := f.Cfg(data.key); ok != data.exist || v != data.expect { - t.Errorf("key: %s expect: %s exist: %t got v: %s ok: %t", data.key, data.expect, data.exist, v, ok) - } - } - for exp, res := range map[string]bool{ - "Sms": false, - "Sms = SmsJuhe": false, - "SmsJuhe": false, - "default": false, - "develop": true, - } { - if ok := f.CfgIf(exp); res != ok { - t.Errorf("CfgIf(%s) want %t got %t", exp, res, ok) - } - } - - f.UseDefault() - f.Use([]string{"slim", "", "demo"}, false) - for _, data := range []struct { - key string - expect string - exist bool - }{ - {"Sms", "SmsJuhe", true}, - {"Alipay", "", true}, - {"Zinc", "", true}, - {"Redis", "", true}, - {"Database", "", false}, - {"demo", "", true}, - } { - if v, ok := f.Cfg(data.key); ok != data.exist || v != data.expect { - t.Errorf("key: %s expect: %s exist: %t got v: %s ok: %t", data.key, data.expect, data.exist, v, ok) - } - } - for exp, res := range map[string]bool{ - "Sms": true, - "Sms = SmsJuhe": true, - "SmsJuhe": false, - "default": true, - "develop": false, - "slim": true, - "demo": true, - } { - if ok := f.CfgIf(exp); res != ok { - t.Errorf("CfgIf(%s) want %t got %t", exp, res, ok) - } - } -} From 057c464563f2228764b62f21193b1588b4ab99bc Mon Sep 17 00:00:00 2001 From: Michael Li Date: Mon, 12 Dec 2022 15:27:05 +0800 Subject: [PATCH 24/28] add features-status.md to track features develop status --- README.md | 71 ++++++++++---------- features-status.md | 163 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 200 insertions(+), 34 deletions(-) create mode 100644 features-status.md diff --git a/README.md b/README.md index 5c196532..4aa0eeec 100644 --- a/README.md +++ b/README.md @@ -314,40 +314,43 @@ release/paopao-ce --no-default-features --features sqlite3,localoss,loggerfile,r ``` 目前支持的功能集合: -* 数据库: MySQL/Sqlite3/PostgreSQL - `Gorm` + `MySQL`/`Sqlite3`/`PostgreSQL` 使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Grom` + `MySQL`组合(目前状态:稳定,默认,推荐使用); - `Sqlx` + `MySQL`/`PostgreSQL` 使用[sqlx](https://github.com/jmoiron/sqlx)作为数据库的ORM(目前状态:WIP); -* 对象存储: AliOSS/COS/HuaweiOBS/MinIO/LocalOSS - `AliOSS` 阿里云对象存储服务; - `COS` 腾讯云对象存储服务; - `HuaweiOBS` 华为云对象存储服务; - `MinIO` [MinIO](https://github.com/minio/minio)对象存储服务; - `S3` AWS S3兼容的对象存储服务; - `LocalOSS` 提供使用本地目录文件作为对象存储的功能,仅用于开发调试环境; -* 缓存: Redis/SimpleCacheIndex/BigCacheIndex - `SimpleCacheIndex` 提供简单的 广场推文列表 的缓存功能; - `BigCacheIndex` 使用[BigCache](https://github.com/allegro/bigcache)缓存 广场推文列表,缓存每个用户每一页,简单做到千人千面(推荐使用); -* 搜索: Zinc/Meili - `Zinc` 基于[Zinc](https://github.com/zinclabs/zinc)搜索引擎提供推文搜索服务(目前状态: 稳定,推荐使用); - `Meili` 基于[Meilisearch](https://github.com/meilisearch/meilisearch)搜索引擎提供推文搜索服务(目前状态: 稳定,推荐使用); -* 日志: LoggerFile/LoggerZinc/LoggerMeili - `LoggerFile` 使用文件写日志(目前状态: 稳定); - `LoggerZinc` 使用[Zinc](https://github.com/zinclabs/zinc)写日志(目前状态: 稳定,推荐使用); - `LoggerMeili` 使用[Meilisearch](https://github.com/meilisearch/meilisearch)写日志(目前状态: 内测阶段); -* 用户关系模式: Friendship/Followship - `Friendship` 弱关系好友模式,类似微信朋友圈(目前状态: 开发阶段); - `Followship` 关注者模式,类似Twitter的Follow模式(目前状态: WIP); -* 支付: Alipay - `Alipay` 开启基于[支付宝开放平台](https://open.alipay.com/)的钱包功能; -* 短信验证码: SmsJuhe(需要开启sms) - `Sms` 开启短信验证码功能,用于手机绑定验证手机是否注册者的;功能如果没有开启,手机绑定时任意短信验证码都可以绑定手机; -* 开发文档: Docs:OpenAPI - `Docs:OpenAPI` 开启openapi文档功能,提供web api文档说明(visit http://127.0.0.1:8008/docs/openapi); -* 其他: PhoneBind/OSS:Retention/OSS:TempDir - `PhoneBind` 手机绑定功能; - `OSS:Retention` 基于对象存储系统的对象过期自动删除特性实现 先创建临时对象再持久化的功能(目前状态: 内测阶段); - `OSS:TempDir` 基于对象存储系统的对象拷贝/移动特性实现 先创建临时对象再持久化的功能(目前状态: 内测阶段); - +| 功能项 | 类别 | 状态 | 备注 | +| ----- | ----- | ----- | ----- | +|`OldWeb` | 子服务 | 稳定(默认) | 开启旧的Web服务 | +|`Web` | 子服务 | WIP | 开启Web服务| +|`Admin` | 子服务 | WIP | 开启Admin后台运维服务| +|`SpaceX` | 子服务 | WIP | 开启SpaceX服务| +|`Bot` | 子服务 | WIP | 开启Bot服务| +|`NativeOBS` | 子服务 | WIP | 开启NativeOBS服务| +|`Deprecated:Web` | 子服务 | 稳定 | Deprecated(关闭) OldWeb服务| +|`Gorm` + `MySQL`/`Sqlite3`/`PostgreSQL` | 数据库 | 稳定(默认) | 使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Grom` + `MySQL`组合| +|`Sqlx` + `MySQL`/`Sqlite3`/`PostgreSQL`| 数据库 | WIP | 使用[sqlx](https://github.com/jmoiron/sqlx)作为数据库的ORM| +|`AliOSS` | 对象存储 | 稳定(推荐) |阿里云对象存储服务| +|`COS` | 对象存储 | 内测 |腾讯云对象存储服务| +|`HuaweiOBS` | 对象存储 | 内测 |华为云对象存储服务| +|`MinIO` | 对象存储 | 稳定 |[MinIO](https://github.com/minio/minio)对象存储服务| +|`S3` | 对象存储 | 内测 |AWS S3兼容的对象存储服务| +|`LocalOSS` | 对象存储 | 内测 |提供使用本地目录文件作为对象存储的功能,仅用于开发调试环境| +|`OSS:Retention` | 对象存储 | 内测 |基于对象存储系统的对象过期自动删除特性实现 先创建临时对象再持久化的功能| +|`OSS:TempDir` | 对象存储 | 内测 |基于对象存储系统的对象拷贝/移动特性实现 先创建临时对象再持久化的功能| +|`Redis` | 缓存 | 稳定 | Redis缓存功能 | +|`SimpleCacheIndex` | 缓存 | 稳定 | 提供简单的 广场推文列表 的缓存功能 | +|`BigCacheIndex` | 缓存 | 稳定(推荐) | 使用[BigCache](https://github.com/allegro/bigcache)缓存 广场推文列表,缓存每个用户每一页,简单做到千人千面 | +|`Zinc` | 搜索 | 稳定(推荐) | 基于[Zinc](https://github.com/zinclabs/zinc)搜索引擎提供推文搜索服务 | +|`Meili` | 搜索 | 稳定(推荐) | 基于[Meilisearch](https://github.com/meilisearch/meilisearch)搜索引擎提供推文搜索服务 | +|`Bleve` | 搜索 | WIP | 基于[Bleve](https://github.com/blevesearch/bleve)搜索引擎提供推文搜索服务 | +|`LoggerFile` | 日志 | 稳定 | 使用文件写日志 | +|`LoggerZinc` | 日志 | 稳定(推荐) | 使用[Zinc](https://github.com/zinclabs/zinc)写日志 | +|`LoggerMeili` | 日志 | 内测 | 使用[Meilisearch](https://github.com/meilisearch/meilisearch)写日志 | +|`Friendship` | 用户关系模式 | 内测(默认) | 弱关系好友模式,类似微信朋友圈 | +|`Followship` | 用户关系模式 | WIP | 关注者模式,类似Twitter的Follow模式 | +|`Alipay` | 支付 | 稳定 | 开启基于[支付宝开放平台](https://open.alipay.com/)的钱包功能 | +|`Sms` | 短信验证码 | 稳定 | 开启短信验证码功能,用于手机绑定验证手机是否注册者的;功能如果没有开启,手机绑定时任意短信验证码都可以绑定手机 | +|`Docs:OpenAPI` | 开发文档 | 稳定 | 开启openapi文档功能,提供web api文档说明(visit http://127.0.0.1:8008/docs/openapi) | +|`PhoneBind` | 其他 | 稳定 | 手机绑定功能 | + +功能项状态详情参考 [features-status](features-status.md). + ### 搭建依赖环境 #### [Zinc](https://github.com/zinclabs/zinc) 搜索引擎: * Zinc运行 diff --git a/features-status.md b/features-status.md new file mode 100644 index 00000000..450194e9 --- /dev/null +++ b/features-status.md @@ -0,0 +1,163 @@ +## Features Status +功能项状态说明。 + +## 目前支持的功能集合 +#### 子服务 +* `OldWeb` 开启旧的Web服务(目前状态: 默认) + * [ ] 提按文档 + * [x] 服务初始化逻辑 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `Web` 开启Web服务(目前状态: WIP) + * [ ] 提按文档 + * [x] 服务初始化逻辑 + * [ ] 接口定义 + * [ ] 业务逻辑实现 +* `Admin` 开启Admin后台运维服务(目前状态: WIP) + * [ ] 提按文档 + * [x] 服务初始化逻辑 + * [ ] 接口定义 + * [ ] 业务逻辑实现 +* `SpaceX` 开启SpaceX服务(目前状态: WIP) + * [ ] 提按文档 + * [x] 服务初始化逻辑 + * [ ] 接口定义 + * [ ] 业务逻辑实现 +* `Bot` 开启Bot服务(目前状态: WIP) + * [ ] 提按文档 + * [x] 服务初始化逻辑 + * [ ] 接口定义 + * [ ] 业务逻辑实现 +* `NativeOBS` 开启NativeOBS服务(目前状态: WIP) + * [ ] 提按文档 + * [ ] 服务初始化逻辑 + * [ ] 接口定义 + * [ ] 业务逻辑实现 +* `Deprecated:OldWeb` Deprecated(关闭)旧的Web服务(目前状态: WIP) + * [ ] 提按文档 + * [x] 服务初始化逻辑 + +#### 数据库: +* `Gorm` + `MySQL`/`Sqlite3`/`PostgreSQL` +使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Grom` + `MySQL`组合(目前状态:稳定,默认,推荐使用); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `Sqlx` + `MySQL`/`PostgreSQL` +使用[sqlx](https://github.com/jmoiron/sqlx)作为数据库的ORM(目前状态:WIP); + * [ ] 提按文档 + * [ ] 接口定义 + * [ ] 业务逻辑实现 + +#### 对象存储: +* `AliOSS` 阿里云对象存储服务; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `COS` 腾讯云对象存储服务; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `HuaweiOBS` 华为云对象存储服务; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `MinIO` [MinIO](https://github.com/minio/minio)对象存储服务; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `S3` AWS S3兼容的对象存储服务; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `LocalOSS` 提供使用本地目录文件作为对象存储的功能,仅用于开发调试环境; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `OSS:Retention` 基于对象存储系统的对象过期自动删除特性实现 先创建临时对象再持久化的功能(目前状态: 内测阶段); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `OSS:TempDir` 基于对象存储系统的对象拷贝/移动特性实现 先创建临时对象再持久化的功能(目前状态: 内测阶段); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 + +#### 缓存: +* `Redis` Redis缓存 + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `SimpleCacheIndex` 提供简单的 广场推文列表 的缓存功能能; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `BigCacheIndex` 使用[BigCache](https://github.com/allegro/bigcache)缓存 广场推文列表,缓存每个用户每一页,简单做到千人千面(推荐使用); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 + +#### 搜索: +* `Zinc` 基于[Zinc](https://github.com/zinclabs/zinc)搜索引擎提供推文搜索服务(目前状态: 稳定,推荐使用); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `Meili` 基于[Meilisearch](https://github.com/meilisearch/meilisearch)搜索引擎提供推文搜索服务(目前状态: 稳定,推荐使用); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `Bleve` 基于[Bleve](https://github.com/blevesearch/bleve)搜索引擎提供推文搜索服务(目前状态: WIP); + * [ ] 提按文档 + * [ ] 接口定义 + * [ ] 业务逻辑实现 +#### 日志: +* `LoggerFile` 使用文件写日志(目前状态: 稳定); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `LoggerZinc` 使用[Zinc](https://github.com/zinclabs/zinc)写日志(目前状态: 稳定,推荐使用); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `LoggerMeili` 使用[Meilisearch](https://github.com/meilisearch/meilisearch)写日志(目前状态: 内测阶段); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 + +#### 用户关系模式: +* `Friendship` 弱关系好友模式,类似微信朋友圈(目前状态: 开发阶段); + * [x] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `Followship` 关注者模式,类似Twitter的Follow模式(目前状态: WIP); + * [ ] 提按文档 + * [ ] 接口定义 + * [ ] 业务逻辑实现 + +### 支付: +* `Alipay` 开启基于[支付宝开放平台](https://open.alipay.com/)的钱包功能; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 + +### 短信验证码: +* SmsJuhe(需要开启sms) + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 +* `Sms` 开启短信验证码功能,用于手机绑定验证手机是否注册者的;功能如果没有开启,手机绑定时任意短信验证码都可以绑定手机; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 + +### 开发文档: +* `Docs:OpenAPI` 开启openapi文档功能,提供web api文档说明(visit http://127.0.0.1:8008/docs/openapi); + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 + +### 其他: +* `PhoneBind` 手机绑定功能; + * [ ] 提按文档 + * [x] 接口定义 + * [x] 业务逻辑实现 From 5c097de7a47c19007a4d6fa0b007cb396ac48dd5 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Mon, 12 Dec 2022 15:38:32 +0800 Subject: [PATCH 25/28] update features describe for README.md --- README.md | 13 ++++++++----- features-status.md | 4 ++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 4aa0eeec..bcd2d967 100644 --- a/README.md +++ b/README.md @@ -323,8 +323,11 @@ release/paopao-ce --no-default-features --features sqlite3,localoss,loggerfile,r |`Bot` | 子服务 | WIP | 开启Bot服务| |`NativeOBS` | 子服务 | WIP | 开启NativeOBS服务| |`Deprecated:Web` | 子服务 | 稳定 | Deprecated(关闭) OldWeb服务| -|`Gorm` + `MySQL`/`Sqlite3`/`PostgreSQL` | 数据库 | 稳定(默认) | 使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Grom` + `MySQL`组合| -|`Sqlx` + `MySQL`/`Sqlite3`/`PostgreSQL`| 数据库 | WIP | 使用[sqlx](https://github.com/jmoiron/sqlx)作为数据库的ORM| +|`Gorm` | 数据库 | 稳定(默认) | 使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Grom` + `MySQL`组合| +|`Sqlx`| 数据库 | WIP | 使用[sqlx](https://github.com/jmoiron/sqlx)作为数据库的ORM| +|`MySQL`| 数据库 | 稳定(默认) | 使用MySQL作为数据库| +|`Postgres`| 数据库 | 稳定 | 使用PostgreSQL作为数据库| +|`Sqlite3`| 数据库 | 稳定 | 使用Sqlite3作为数据库| |`AliOSS` | 对象存储 | 稳定(推荐) |阿里云对象存储服务| |`COS` | 对象存储 | 内测 |腾讯云对象存储服务| |`HuaweiOBS` | 对象存储 | 内测 |华为云对象存储服务| @@ -342,10 +345,10 @@ release/paopao-ce --no-default-features --features sqlite3,localoss,loggerfile,r |`LoggerFile` | 日志 | 稳定 | 使用文件写日志 | |`LoggerZinc` | 日志 | 稳定(推荐) | 使用[Zinc](https://github.com/zinclabs/zinc)写日志 | |`LoggerMeili` | 日志 | 内测 | 使用[Meilisearch](https://github.com/meilisearch/meilisearch)写日志 | -|`Friendship` | 用户关系模式 | 内测(默认) | 弱关系好友模式,类似微信朋友圈 | -|`Followship` | 用户关系模式 | WIP | 关注者模式,类似Twitter的Follow模式 | +|`Friendship` | 关系模式 | 内测(默认) | 弱关系好友模式,类似微信朋友圈 | +|`Followship` | 关系模式 | WIP | 关注者模式,类似Twitter的Follow模式 | |`Alipay` | 支付 | 稳定 | 开启基于[支付宝开放平台](https://open.alipay.com/)的钱包功能 | -|`Sms` | 短信验证码 | 稳定 | 开启短信验证码功能,用于手机绑定验证手机是否注册者的;功能如果没有开启,手机绑定时任意短信验证码都可以绑定手机 | +|`Sms` | 短信验证 | 稳定 | 开启短信验证码功能,用于手机绑定验证手机是否注册者的;功能如果没有开启,手机绑定时任意短信验证码都可以绑定手机 | |`Docs:OpenAPI` | 开发文档 | 稳定 | 开启openapi文档功能,提供web api文档说明(visit http://127.0.0.1:8008/docs/openapi) | |`PhoneBind` | 其他 | 稳定 | 手机绑定功能 | diff --git a/features-status.md b/features-status.md index 450194e9..38f8eb6e 100644 --- a/features-status.md +++ b/features-status.md @@ -124,7 +124,7 @@ * [x] 接口定义 * [x] 业务逻辑实现 -#### 用户关系模式: +#### 关系模式: * `Friendship` 弱关系好友模式,类似微信朋友圈(目前状态: 开发阶段); * [x] 提按文档 * [x] 接口定义 @@ -140,7 +140,7 @@ * [x] 接口定义 * [x] 业务逻辑实现 -### 短信验证码: +### 短信验证: * SmsJuhe(需要开启sms) * [ ] 提按文档 * [x] 接口定义 From dfb3fada2c2ec57b448cf6fbcb25eb341a29024e Mon Sep 17 00:00:00 2001 From: Michael Li Date: Mon, 12 Dec 2022 15:43:45 +0800 Subject: [PATCH 26/28] update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bcd2d967..acc0d1d1 100644 --- a/README.md +++ b/README.md @@ -323,7 +323,7 @@ release/paopao-ce --no-default-features --features sqlite3,localoss,loggerfile,r |`Bot` | 子服务 | WIP | 开启Bot服务| |`NativeOBS` | 子服务 | WIP | 开启NativeOBS服务| |`Deprecated:Web` | 子服务 | 稳定 | Deprecated(关闭) OldWeb服务| -|`Gorm` | 数据库 | 稳定(默认) | 使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Grom` + `MySQL`组合| +|`Gorm` | 数据库 | 稳定(默认) | 使用[gorm](https://github.com/go-gorm/gorm)作为数据库的ORM,默认使用 `Gorm` + `MySQL`组合| |`Sqlx`| 数据库 | WIP | 使用[sqlx](https://github.com/jmoiron/sqlx)作为数据库的ORM| |`MySQL`| 数据库 | 稳定(默认) | 使用MySQL作为数据库| |`Postgres`| 数据库 | 稳定 | 使用PostgreSQL作为数据库| @@ -352,7 +352,7 @@ release/paopao-ce --no-default-features --features sqlite3,localoss,loggerfile,r |`Docs:OpenAPI` | 开发文档 | 稳定 | 开启openapi文档功能,提供web api文档说明(visit http://127.0.0.1:8008/docs/openapi) | |`PhoneBind` | 其他 | 稳定 | 手机绑定功能 | -功能项状态详情参考 [features-status](features-status.md). +> 功能项状态详情参考 [features-status](features-status.md). ### 搭建依赖环境 #### [Zinc](https://github.com/zinclabs/zinc) 搜索引擎: From 4d379e278a7b6921378e467a339059b170f094ab Mon Sep 17 00:00:00 2001 From: Michael Li Date: Tue, 13 Dec 2022 12:19:12 +0800 Subject: [PATCH 27/28] upgrade github.com/alimy/mir/v3 => v3.0.0-alpha.5 --- go.mod | 2 +- go.sum | 4 ++-- internal/mirc/auto/api/m/v1/user.go | 18 +++++++------- internal/mirc/auto/api/r/v1/user.go | 18 +++++++------- internal/mirc/auto/api/s/v1/user.go | 26 ++++++++++---------- internal/mirc/auto/api/v1/web_core.go | 34 +++++++++++++-------------- internal/mirc/auto/api/x/v1/user.go | 18 +++++++------- 7 files changed, 60 insertions(+), 60 deletions(-) diff --git a/go.mod b/go.mod index 3ab5270f..e826578e 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/Masterminds/semver/v3 v3.1.1 github.com/afocus/captcha v0.0.0-20191010092841-4bd1f21c8868 github.com/alimy/cfg v0.1.0 - github.com/alimy/mir/v3 v3.0.0-alpha.4 + github.com/alimy/mir/v3 v3.0.0-alpha.5 github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible github.com/allegro/bigcache/v3 v3.0.2 github.com/bytedance/sonic v1.5.0 diff --git a/go.sum b/go.sum index eed23c9b..df94f30e 100644 --- a/go.sum +++ b/go.sum @@ -144,8 +144,8 @@ github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:C github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk= github.com/alimy/cfg v0.1.0 h1:J7KDLEoVIjEBMGlQJb2ljad/d49gJ4Tsl2ogZ9XNhaY= github.com/alimy/cfg v0.1.0/go.mod h1:rOxbasTH2srl6StAjNF5Vyi8bfrdkl3fLGmOYtSw81c= -github.com/alimy/mir/v3 v3.0.0-alpha.4 h1:tSmyyhgutMHjgx9TO9891ZCY4qbr3g8FGar4z+9Hhq4= -github.com/alimy/mir/v3 v3.0.0-alpha.4/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU= +github.com/alimy/mir/v3 v3.0.0-alpha.5 h1:KFv8ulmC1hDPDezh/dQ+ZwZwmmwrcWUV4TZJrMBZB8I= +github.com/alimy/mir/v3 v3.0.0-alpha.5/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= diff --git a/internal/mirc/auto/api/m/v1/user.go b/internal/mirc/auto/api/m/v1/user.go index c087ae87..b31984b9 100644 --- a/internal/mirc/auto/api/m/v1/user.go +++ b/internal/mirc/auto/api/m/v1/user.go @@ -38,21 +38,21 @@ type User interface { // Chain provide handlers chain for gin Chain() gin.HandlersChain - Logout(c *gin.Context) mir.Error - Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + Logout() mir.Error + Login(*LoginReq) (*LoginResp, mir.Error) mustEmbedUnimplementedUserServant() } type UserBinding interface { - BindLogin(c *gin.Context) (*LoginReq, mir.Error) + BindLogin(*gin.Context) (*LoginReq, mir.Error) mustEmbedUnimplementedUserBinding() } type UserRender interface { - RenderLogout(c *gin.Context, err mir.Error) - RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + RenderLogout(*gin.Context, mir.Error) + RenderLogin(*gin.Context, *LoginResp, mir.Error) mustEmbedUnimplementedUserRender() } @@ -66,7 +66,7 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { - r.RenderLogout(c, s.Logout(c)) + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { @@ -74,7 +74,7 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { if err != nil { r.RenderLogin(c, nil, err) } - resp, err := s.Login(c, req) + resp, err := s.Login(req) r.RenderLogin(c, resp, err) }) @@ -88,11 +88,11 @@ func (UnimplementedUserServant) Chain() gin.HandlersChain { return nil } -func (UnimplementedUserServant) Logout(c *gin.Context) mir.Error { +func (UnimplementedUserServant) Logout() mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedUserServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { +func (UnimplementedUserServant) Login(req *LoginReq) (*LoginResp, mir.Error) { return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } diff --git a/internal/mirc/auto/api/r/v1/user.go b/internal/mirc/auto/api/r/v1/user.go index ae9dd9cd..55961d75 100644 --- a/internal/mirc/auto/api/r/v1/user.go +++ b/internal/mirc/auto/api/r/v1/user.go @@ -38,21 +38,21 @@ type User interface { // Chain provide handlers chain for gin Chain() gin.HandlersChain - Logout(c *gin.Context) mir.Error - Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + Logout() mir.Error + Login(*LoginReq) (*LoginResp, mir.Error) mustEmbedUnimplementedUserServant() } type UserBinding interface { - BindLogin(c *gin.Context) (*LoginReq, mir.Error) + BindLogin(*gin.Context) (*LoginReq, mir.Error) mustEmbedUnimplementedUserBinding() } type UserRender interface { - RenderLogout(c *gin.Context, err mir.Error) - RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + RenderLogout(*gin.Context, mir.Error) + RenderLogin(*gin.Context, *LoginResp, mir.Error) mustEmbedUnimplementedUserRender() } @@ -66,7 +66,7 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { - r.RenderLogout(c, s.Logout(c)) + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { @@ -74,7 +74,7 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { if err != nil { r.RenderLogin(c, nil, err) } - resp, err := s.Login(c, req) + resp, err := s.Login(req) r.RenderLogin(c, resp, err) }) @@ -88,11 +88,11 @@ func (UnimplementedUserServant) Chain() gin.HandlersChain { return nil } -func (UnimplementedUserServant) Logout(c *gin.Context) mir.Error { +func (UnimplementedUserServant) Logout() mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedUserServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { +func (UnimplementedUserServant) Login(req *LoginReq) (*LoginResp, mir.Error) { return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } diff --git a/internal/mirc/auto/api/s/v1/user.go b/internal/mirc/auto/api/s/v1/user.go index 4751a141..a14c1e42 100644 --- a/internal/mirc/auto/api/s/v1/user.go +++ b/internal/mirc/auto/api/s/v1/user.go @@ -35,23 +35,23 @@ type UserInfo struct { } type User interface { - Logout(c *gin.Context) mir.Error - Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) - Index(c *gin.Context) mir.Error + Logout() mir.Error + Login(*LoginReq) (*LoginResp, mir.Error) + Index() mir.Error mustEmbedUnimplementedUserServant() } type UserBinding interface { - BindLogin(c *gin.Context) (*LoginReq, mir.Error) + BindLogin(*gin.Context) (*LoginReq, mir.Error) mustEmbedUnimplementedUserBinding() } type UserRender interface { - RenderLogout(c *gin.Context, err mir.Error) - RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) - RenderIndex(c *gin.Context, err mir.Error) + RenderLogout(*gin.Context, mir.Error) + RenderLogin(*gin.Context, *LoginResp, mir.Error) + RenderIndex(*gin.Context, mir.Error) mustEmbedUnimplementedUserRender() } @@ -62,7 +62,7 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { - r.RenderLogout(c, s.Logout(c)) + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { @@ -70,12 +70,12 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { if err != nil { r.RenderLogin(c, nil, err) } - resp, err := s.Login(c, req) + resp, err := s.Login(req) r.RenderLogin(c, resp, err) }) router.Handle("GET", "/index/", func(c *gin.Context) { - r.RenderIndex(c, s.Index(c)) + r.RenderIndex(c, s.Index()) }) } @@ -84,15 +84,15 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { type UnimplementedUserServant struct { } -func (UnimplementedUserServant) Logout(c *gin.Context) mir.Error { +func (UnimplementedUserServant) Logout() mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedUserServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { +func (UnimplementedUserServant) Login(req *LoginReq) (*LoginResp, mir.Error) { return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedUserServant) Index(c *gin.Context) mir.Error { +func (UnimplementedUserServant) Index() mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } diff --git a/internal/mirc/auto/api/v1/web_core.go b/internal/mirc/auto/api/v1/web_core.go index 3e7d3d65..4f797538 100644 --- a/internal/mirc/auto/api/v1/web_core.go +++ b/internal/mirc/auto/api/v1/web_core.go @@ -38,25 +38,25 @@ type WebCore interface { // Chain provide handlers chain for gin Chain() gin.HandlersChain - Logout(c *gin.Context) mir.Error - Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) - Articles(c *gin.Context) mir.Error - Index(c *gin.Context) mir.Error + Logout() mir.Error + Login(*LoginReq) (*LoginResp, mir.Error) + Articles() mir.Error + Index() mir.Error mustEmbedUnimplementedWebCoreServant() } type WebCoreBinding interface { - BindLogin(c *gin.Context) (*LoginReq, mir.Error) + BindLogin(*gin.Context) (*LoginReq, mir.Error) mustEmbedUnimplementedWebCoreBinding() } type WebCoreRender interface { - RenderLogout(c *gin.Context, err mir.Error) - RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) - RenderArticles(c *gin.Context, err mir.Error) - RenderIndex(c *gin.Context, err mir.Error) + RenderLogout(*gin.Context, mir.Error) + RenderLogin(*gin.Context, *LoginResp, mir.Error) + RenderArticles(*gin.Context, mir.Error) + RenderIndex(*gin.Context, mir.Error) mustEmbedUnimplementedWebCoreRender() } @@ -70,7 +70,7 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { - r.RenderLogout(c, s.Logout(c)) + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { @@ -78,20 +78,20 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor if err != nil { r.RenderLogin(c, nil, err) } - resp, err := s.Login(c, req) + resp, err := s.Login(req) r.RenderLogin(c, resp, err) }) { h := func(c *gin.Context) { - r.RenderArticles(c, s.Articles(c)) + r.RenderArticles(c, s.Articles()) } router.Handle("HEAD", "/articles/:category/", h) router.Handle("GET", "/articles/:category/", h) } router.Handle("GET", "/index/", func(c *gin.Context) { - r.RenderIndex(c, s.Index(c)) + r.RenderIndex(c, s.Index()) }) } @@ -104,19 +104,19 @@ func (UnimplementedWebCoreServant) Chain() gin.HandlersChain { return nil } -func (UnimplementedWebCoreServant) Logout(c *gin.Context) mir.Error { +func (UnimplementedWebCoreServant) Logout() mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedWebCoreServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { +func (UnimplementedWebCoreServant) Login(req *LoginReq) (*LoginResp, mir.Error) { return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedWebCoreServant) Articles(c *gin.Context) mir.Error { +func (UnimplementedWebCoreServant) Articles() mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedWebCoreServant) Index(c *gin.Context) mir.Error { +func (UnimplementedWebCoreServant) Index() mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } diff --git a/internal/mirc/auto/api/x/v1/user.go b/internal/mirc/auto/api/x/v1/user.go index 66446d03..8b579f67 100644 --- a/internal/mirc/auto/api/x/v1/user.go +++ b/internal/mirc/auto/api/x/v1/user.go @@ -38,21 +38,21 @@ type User interface { // Chain provide handlers chain for gin Chain() gin.HandlersChain - Logout(c *gin.Context) mir.Error - Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + Logout() mir.Error + Login(*LoginReq) (*LoginResp, mir.Error) mustEmbedUnimplementedUserServant() } type UserBinding interface { - BindLogin(c *gin.Context) (*LoginReq, mir.Error) + BindLogin(*gin.Context) (*LoginReq, mir.Error) mustEmbedUnimplementedUserBinding() } type UserRender interface { - RenderLogout(c *gin.Context, err mir.Error) - RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + RenderLogout(*gin.Context, mir.Error) + RenderLogin(*gin.Context, *LoginResp, mir.Error) mustEmbedUnimplementedUserRender() } @@ -66,7 +66,7 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { - r.RenderLogout(c, s.Logout(c)) + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { @@ -74,7 +74,7 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { if err != nil { r.RenderLogin(c, nil, err) } - resp, err := s.Login(c, req) + resp, err := s.Login(req) r.RenderLogin(c, resp, err) }) @@ -88,11 +88,11 @@ func (UnimplementedUserServant) Chain() gin.HandlersChain { return nil } -func (UnimplementedUserServant) Logout(c *gin.Context) mir.Error { +func (UnimplementedUserServant) Logout() mir.Error { return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } -func (UnimplementedUserServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { +func (UnimplementedUserServant) Login(req *LoginReq) (*LoginResp, mir.Error) { return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) } From 2397eff99d9fc5cf6933c756a559d7db3bb22d87 Mon Sep 17 00:00:00 2001 From: Michael Li Date: Tue, 13 Dec 2022 19:51:03 +0800 Subject: [PATCH 28/28] upgrade github.com/alimy/mir/v3 => v3.0.0-alpha.6 --- go.mod | 2 +- go.sum | 4 ++-- internal/mirc/auto/api/m/v1/user.go | 13 +++++++++++++ internal/mirc/auto/api/r/v1/user.go | 13 +++++++++++++ internal/mirc/auto/api/s/v1/user.go | 19 +++++++++++++++++++ internal/mirc/auto/api/v1/web_core.go | 25 +++++++++++++++++++++++++ internal/mirc/auto/api/x/v1/user.go | 13 +++++++++++++ 7 files changed, 86 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index e826578e..80d99a7f 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/Masterminds/semver/v3 v3.1.1 github.com/afocus/captcha v0.0.0-20191010092841-4bd1f21c8868 github.com/alimy/cfg v0.1.0 - github.com/alimy/mir/v3 v3.0.0-alpha.5 + github.com/alimy/mir/v3 v3.0.0-alpha.6 github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible github.com/allegro/bigcache/v3 v3.0.2 github.com/bytedance/sonic v1.5.0 diff --git a/go.sum b/go.sum index df94f30e..dee0dc5e 100644 --- a/go.sum +++ b/go.sum @@ -144,8 +144,8 @@ github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:C github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk= github.com/alimy/cfg v0.1.0 h1:J7KDLEoVIjEBMGlQJb2ljad/d49gJ4Tsl2ogZ9XNhaY= github.com/alimy/cfg v0.1.0/go.mod h1:rOxbasTH2srl6StAjNF5Vyi8bfrdkl3fLGmOYtSw81c= -github.com/alimy/mir/v3 v3.0.0-alpha.5 h1:KFv8ulmC1hDPDezh/dQ+ZwZwmmwrcWUV4TZJrMBZB8I= -github.com/alimy/mir/v3 v3.0.0-alpha.5/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU= +github.com/alimy/mir/v3 v3.0.0-alpha.6 h1:4xcyE12MgzTbcIcYtnt3ILrVrxFjI71qhqh0JL2gB58= +github.com/alimy/mir/v3 v3.0.0-alpha.6/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= diff --git a/internal/mirc/auto/api/m/v1/user.go b/internal/mirc/auto/api/m/v1/user.go index b31984b9..431343e7 100644 --- a/internal/mirc/auto/api/m/v1/user.go +++ b/internal/mirc/auto/api/m/v1/user.go @@ -66,13 +66,26 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + req, err := b.BindLogin(c) if err != nil { r.RenderLogin(c, nil, err) + return } resp, err := s.Login(req) r.RenderLogin(c, resp, err) diff --git a/internal/mirc/auto/api/r/v1/user.go b/internal/mirc/auto/api/r/v1/user.go index 55961d75..1850b157 100644 --- a/internal/mirc/auto/api/r/v1/user.go +++ b/internal/mirc/auto/api/r/v1/user.go @@ -66,13 +66,26 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + req, err := b.BindLogin(c) if err != nil { r.RenderLogin(c, nil, err) + return } resp, err := s.Login(req) r.RenderLogin(c, resp, err) diff --git a/internal/mirc/auto/api/s/v1/user.go b/internal/mirc/auto/api/s/v1/user.go index a14c1e42..ef2c855b 100644 --- a/internal/mirc/auto/api/s/v1/user.go +++ b/internal/mirc/auto/api/s/v1/user.go @@ -62,19 +62,38 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + req, err := b.BindLogin(c) if err != nil { r.RenderLogin(c, nil, err) + return } resp, err := s.Login(req) r.RenderLogin(c, resp, err) }) router.Handle("GET", "/index/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + r.RenderIndex(c, s.Index()) }) diff --git a/internal/mirc/auto/api/v1/web_core.go b/internal/mirc/auto/api/v1/web_core.go index 4f797538..613977fe 100644 --- a/internal/mirc/auto/api/v1/web_core.go +++ b/internal/mirc/auto/api/v1/web_core.go @@ -70,13 +70,26 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + req, err := b.BindLogin(c) if err != nil { r.RenderLogin(c, nil, err) + return } resp, err := s.Login(req) r.RenderLogin(c, resp, err) @@ -84,6 +97,12 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor { h := func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + r.RenderArticles(c, s.Articles()) } router.Handle("HEAD", "/articles/:category/", h) @@ -91,6 +110,12 @@ func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCor } router.Handle("GET", "/index/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + r.RenderIndex(c, s.Index()) }) diff --git a/internal/mirc/auto/api/x/v1/user.go b/internal/mirc/auto/api/x/v1/user.go index 8b579f67..89a3b086 100644 --- a/internal/mirc/auto/api/x/v1/user.go +++ b/internal/mirc/auto/api/x/v1/user.go @@ -66,13 +66,26 @@ func RegisterUserServant(e *gin.Engine, s User, b UserBinding, r UserRender) { // register routes info to router router.Handle("POST", "/user/logout/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + r.RenderLogout(c, s.Logout()) }) router.Handle("POST", "/user/login/", func(c *gin.Context) { + select { + case <-c.Request.Context().Done(): + return + default: + } + req, err := b.BindLogin(c) if err != nil { r.RenderLogin(c, nil, err) + return } resp, err := s.Login(req) r.RenderLogin(c, resp, err)