diff --git a/app/controller/message_contoller.go b/app/controller/message_contoller.go index 2c2b8c9..df0dcaa 100644 --- a/app/controller/message_contoller.go +++ b/app/controller/message_contoller.go @@ -3,7 +3,6 @@ package controller import ( lang "github.com/gin-contrib/i18n" "github.com/gin-gonic/gin" - "message/app/model" "message/app/repository" "message/app/request" "message/app/response" @@ -18,7 +17,7 @@ import ( // @Tags message // @Accept json // @Produce json -// @Security BasicAuth +// @Security ApiKeyAuth // @Param filter query string false "过滤语句(title = 标题,status = 0|1|2,...)" // @Param sortColumn query string false "排序列(created_at|updated_at|sender_ids|title|content|category|big_content|introducer_ids|status)" // @Param sortType query string false "排序类型(asc/desc)" @@ -47,7 +46,7 @@ func MessageIndex(ctx *gin.Context) { } // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) // 将 message 转换为 MessageRequest 类型 messageRequest := message.(*request.MessageRequest) @@ -63,7 +62,7 @@ func MessageIndex(ctx *gin.Context) { } } - logs.LogInfo.Infof("MessageIndex %v %s", messageRequest, messageToken.AuthId) + logs.LogInfo.Infof("MessageIndex %v %s", messageRequest, messageToken) // 返回查询结果 ctx.JSON( @@ -83,7 +82,7 @@ func MessageIndex(ctx *gin.Context) { // @Tags message // @Accept json // @Produce json -// @Security BasicAuth +// @Security ApiKeyAuth // @Param _ body request.MessageCreateUpdateRequest true "创建的数据" // @Success 200 {object} response.Message "创建成功" // @Success 202 {object} response.HTTPError "创建失败" @@ -108,7 +107,7 @@ func MessageCreate(ctx *gin.Context) { } // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) // 将 messageCreateUpdate 转换为 MessageCreateUpdateRequest 类型 messageCreateRequest := messageCreate.(*request.MessageCreateUpdateRequest) @@ -126,11 +125,11 @@ func MessageCreate(ctx *gin.Context) { lang.MustGetMessage(ctx, "createMessageFail"), ) - logs.LogInfo.Infof("MessageCreate-失败 %s %s", err, messageToken.AuthId) + logs.LogInfo.Infof("MessageCreate-失败 %s %s", err, messageToken) return } - logs.LogInfo.Infof("MessageCreate-成功 %s", messageToken.AuthId) + logs.LogInfo.Infof("MessageCreate-成功 %s", messageToken) // 返回创建成功的消息 ctx.JSON(http.StatusOK, message) @@ -143,7 +142,7 @@ func MessageCreate(ctx *gin.Context) { // @Tags message // @Accept json // @Produce json -// @Security BasicAuth +// @Security ApiKeyAuth // @Param id path string true "消息id" // @Param _ body request.MessageCreateUpdateRequest true "更新消息" // @Success 200 {object} response.Message "更新成功" @@ -170,13 +169,13 @@ func MessageUpdate(ctx *gin.Context) { } // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) // 将 messageCreateUpdate 转换为 MessageCreateUpdateRequest 类型 messageUpdateRequest := messageUpdate.(*request.MessageCreateUpdateRequest) // 根据id查询消息 oldMessage := repository.QueryMessageById( - messageToken.AuthId, + messageToken, ctx.Param("id"), ) @@ -203,11 +202,11 @@ func MessageUpdate(ctx *gin.Context) { lang.MustGetMessage(ctx, "updateMessageFail"), ) - logs.LogInfo.Infof("MessageUpdate-失败 %s %s", err, messageToken.AuthId) + logs.LogInfo.Infof("MessageUpdate-失败 %s %s", err, messageToken) return } - logs.LogInfo.Infof("MessageUpdate-成功 %s", messageToken.AuthId) + logs.LogInfo.Infof("MessageUpdate-成功 %s", messageToken) // 返回更新成功后的消息 ctx.JSON(http.StatusOK, messageNew) @@ -220,7 +219,7 @@ func MessageUpdate(ctx *gin.Context) { // @Tags message // @Accept json // @Produce json -// @Security BasicAuth +// @Security ApiKeyAuth // @Param _ body []request.MessageStatusRequest true "消息状态" // @Success 200 {object} []response.MessageStatusResponse "更新后返回的数据" // @Failure 400 {object} request.ValidationError "请求参数错误" @@ -244,11 +243,11 @@ func MessageUpdateStatus(ctx *gin.Context) { } // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) // 将 messageStatus 转换为 []MessageStatusRequest 类型 messageStatusRequest := messageStatus.(*[]request.MessageStatusRequest) - logs.LogInfo.Infof("MessageUpdateStatus %v %s", messageStatusRequest, messageToken.AuthId) + logs.LogInfo.Infof("MessageUpdateStatus %v %s", messageStatusRequest, messageToken) // 更新消息状态,并返回更新后的结果 ctx.JSON( @@ -267,7 +266,7 @@ func MessageUpdateStatus(ctx *gin.Context) { // @Tags message // @Accept json // @Produce json -// @Security BasicAuth +// @Security ApiKeyAuth // @Param _ body []request.MessageDeleteRequest true "删除的消息" // @Success 200 {object} []response.MessageDeleteResponse "更新后返回的数据" // @Failure 400 {object} request.ValidationError "请求参数错误" @@ -292,11 +291,11 @@ func MessageDelete(ctx *gin.Context) { } // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) // 将 messageDelete 转换为 []MessageDeleteRequest 类型 messageDeleteRequests := messageDelete.(*[]request.MessageDeleteRequest) - logs.LogInfo.Infof("MessageDelete %v %s", messageDeleteRequests, messageToken.AuthId) + logs.LogInfo.Infof("MessageDelete %v %s", messageDeleteRequests, messageToken) // 删除消息,并返回删除结果 ctx.JSON( diff --git a/app/middleware/auth_middleware.go b/app/middleware/auth_middleware.go index 3f97f45..348e486 100755 --- a/app/middleware/auth_middleware.go +++ b/app/middleware/auth_middleware.go @@ -1,58 +1,20 @@ package middleware import ( - "encoding/base64" - "fmt" lang "github.com/gin-contrib/i18n" "github.com/gin-gonic/gin" "message/app/repository" + "message/app/request" "message/app/response" "message/logs" "net/http" - "strings" ) -// parseAuthorization 函数用于解析 Authorization 头中的 Basic token。 -// -// 它接受一个字符串参数 basic,该字符串应包含完整的 Authorization 请求头的值。 -// -// 函数返回一个包含两个字符串的切片和一个错误对象。 -// -// 如果解析成功,切片中将包含从基于 Base64 编码的 token 中解码得到的信息; -// -// 如果解析失败,则返回一个错误。 -func parseAuthorization(authorization string) (token []string, err error) { - // 使用空格将传入的 basic 字符串分割成两部分。 - parts := strings.Split(authorization, " ") - // 检查分割后的结果是否正好两部分,并且第一部分(不区分大小写)是否为"basic"。 - if len(parts) != 2 || strings.ToLower(parts[0]) != "basic" { - // 如果不满足条件,返回一个空的字符串切片和一个格式错误的错误信息。 - return []string{}, fmt.Errorf("格式错误") - } - - // 尝试对第二部分(即 Base64 编码的 token)进行解码。 - decodeByte, err := base64.StdEncoding.DecodeString(parts[1]) - if err != nil { - // 如果解码过程中发生错误,同样返回一个空的字符串切片和一个格式错误的错误信息。 - return []string{}, fmt.Errorf("格式错误") - } - - // 将解码后的字节序列转换为字符串,并以冒号为分隔符进行分割。 - info := strings.Split(string(decodeByte), ":") - // 检查分割后的结果是否正好两部分,这通常对应于用户名和密码。 - if len(info) != 2 { - // 如果不满足条件,再次返回一个空的字符串切片和一个格式错误的错误信息。 - return []string{}, fmt.Errorf("格式错误") - } - // 如果所有检查都通过,则返回解析得到的信息和 nil 错误。 - return info, nil -} - // AuthMiddleware 是一个 Gin 中间件函数,用于验证请求的授权信息。 // // 该中间件从请求头中获取 Authorization,并解析为授权信息。 // -// 授权信息通过调用 repository.GetMessageToken() 方法获取消息令牌。 +// 授权信息通过调用 repository.GetMessageToken() 方法获取消息令牌是否有效。 // // 如果授权信息无效或获取消息令牌失败,则返回相应的错误响应。 // @@ -61,21 +23,15 @@ func parseAuthorization(authorization string) (token []string, err error) { // 返回一个 gin.HandlerFunc 处理程序函数。 func AuthMiddleware() gin.HandlerFunc { return func(ctx *gin.Context) { - // 从请求头中获取 Authorization 并解析 Authorization - authorization, err := parseAuthorization(ctx.GetHeader("Authorization")) - if err != nil { + token := ctx.GetHeader("Authorization") + if err := request.Validate.Var(token, "required,len=32"); err != nil { logs.LogInfo.Infof("AuthMiddleware-失败 %s %s", err, ctx.ClientIP()) - response.NewError( - ctx, - http.StatusUnauthorized, - lang.MustGetMessage(ctx, "unauthorized"), - ) - ctx.Abort() + request.HandlingValidateErrors(ctx, err) return } // 获取消息令牌 - token, err := repository.GetMessageToken(authorization[0], authorization[1]) + _, err := repository.GetMessageToken(token) if err != nil { logs.LogInfo.Infof("AuthMiddleware-失败-找不到凭证 %s", ctx.ClientIP()) response.NewError( @@ -87,7 +43,7 @@ func AuthMiddleware() gin.HandlerFunc { return } - logs.LogInfo.Infof("AuthMiddleware-成功 %s %s", ctx.ClientIP(), token.AuthId) + logs.LogInfo.Infof("AuthMiddleware-成功 %s %s", ctx.ClientIP(), token) // 将消息令牌设置到上下文中 ctx.Set("token", token) ctx.Next() diff --git a/app/model/message_model.go b/app/model/message_model.go index 5b7743a..c0c2c5a 100644 --- a/app/model/message_model.go +++ b/app/model/message_model.go @@ -24,12 +24,5 @@ type Message struct { Status uint8 `gorm:"type:tinyint;default:0;comment:消息阅读状态"` } -// MessageToken 查询消息的凭证 -type MessageToken struct { - gorm.Model `json:"_"` - AuthId string `json:"auth_id,omitempty" gorm:"type:varchar(32);index;unique;comment:"` // User字段长度为32 - Token string `json:"token,omitempty" gorm:"type:varchar(255)"` // Token字段长度为255 -} - type MessageCategory struct { } diff --git a/app/repository/auto_repository.go b/app/repository/auto_repository.go index 1329e14..c5988d0 100644 --- a/app/repository/auto_repository.go +++ b/app/repository/auto_repository.go @@ -1,25 +1,26 @@ package repository import ( - "message/app/model" + "fmt" + "message/config" "message/database" ) // GetMessageToken 尝试获取一个符合指定条件的MessageToken。 // // 它返回找到的MessageToken和可能出现的错误。如果记录不存在,将返回nil和gorm.ErrRecordNotFound。 -func GetMessageToken(authId string, authToken string) (model.MessageToken, error) { - var token model.MessageToken - result := database.DB.Model(model.MessageToken{}). - Where("auth_id = ?", authId). - Where("token = ?", authToken). - First(&token) +func GetMessageToken(messageToken string) (bool, error) { + verify := config.AppConfig.App.Verify + result := database.DB.Table(verify.Table). + Select(verify.Column). + Where(fmt.Sprintf("%s = ?", verify.Column), messageToken). + Limit(1) if result.Error != nil { // 直接返回错误,包括未找到记录的情况 - return token, result.Error + return false, result.Error } // 记录被成功找到,返回token的指针和nil作为错误 - return token, nil + return true, nil } diff --git a/app/repository/message_repository.go b/app/repository/message_repository.go index 52ff8f2..003dde5 100644 --- a/app/repository/message_repository.go +++ b/app/repository/message_repository.go @@ -15,7 +15,7 @@ import ( // QueryMessagesByMessageTokenMessageRequest 根据消息凭证和消息请求查询消息 func QueryMessagesByMessageTokenMessageRequest( // 消息凭证 - token model.MessageToken, + token string, // 消息请求参数 messageRequest *request.MessageRequest, // 消息过滤器 @@ -29,7 +29,7 @@ func QueryMessagesByMessageTokenMessageRequest( query.Where( query.Where( "introducer_ids LIKE ?", - fmt.Sprintf("%%%s%%", token.AuthId), + fmt.Sprintf("%%%s%%", token), ).Or("introducer_ids = ?", ""), ) @@ -84,7 +84,7 @@ func QueryMessagesByMessageTokenMessageRequest( // CreateMessage 创建一条新消息 func CreateMessage( - token model.MessageToken, + token string, createMessage *request.MessageCreateUpdateRequest, ) (*response.Message, error) { messageId := utils.BuildMessageId() @@ -93,7 +93,7 @@ func CreateMessage( // 生成消息 ID MessageId: messageId, // 设置消息的发送者 ID - SenderIds: []string{token.AuthId}, + SenderIds: []string{token}, // 设置消息标题 Title: createMessage.Title, // 设置消息内容 @@ -150,7 +150,7 @@ func UpdateMessage( // UpdateMessageStatus 更新消息状态 func UpdateMessageStatus( // 消息凭证 - token model.MessageToken, + token string, // 要更新的状态请求切片 status *[]request.MessageStatusRequest, ) []response.MessageStatusResponse { @@ -162,7 +162,7 @@ func UpdateMessageStatus( // 对model.Message模型执行更新操作,设置新的状态 // 使用LIKE查询匹配introducer_ids,并确保message_id与AuthId相符 result := database.DB.Model(&model.Message{}). - Where("introducer_ids LIKE ?", fmt.Sprintf("%%%s%%", token.AuthId)). + Where("introducer_ids LIKE ?", fmt.Sprintf("%%%s%%", token)). Where("message_id = ?", statusRequest.Id). Update("status", statusRequest.Status) @@ -206,7 +206,7 @@ func QueryMessageById( // DeleteMessagesById 根据消息 ID 批量删除消息 func DeleteMessagesById( // 消息凭证 - token model.MessageToken, + token string, // 要删除的消息请求切片 deleteRequests *[]request.MessageDeleteRequest, ) []response.MessageDeleteResponse { @@ -226,13 +226,13 @@ func DeleteMessagesById( // 物理删除要删除的消息 database.DB.Unscoped(). - Where("sender_ids LIKE ?", fmt.Sprintf("%%%s%%", token.AuthId)). + Where("sender_ids LIKE ?", fmt.Sprintf("%%%s%%", token)). Where("message_id in ?", deletes). Delete(&model.Message{}) // 软删除要软删除的消息 database.DB. - Where("sender_ids LIKE ?", fmt.Sprintf("%%%s%%", token.AuthId)). + Where("sender_ids LIKE ?", fmt.Sprintf("%%%s%%", token)). Where("message_id in ?", softDeletes). Delete(&model.Message{}) @@ -240,14 +240,14 @@ func DeleteMessagesById( var failDeletes []string database.DB. Select("message_id"). - Where("sender_ids LIKE ?", fmt.Sprintf("%%%s%%", token.AuthId)). + Where("sender_ids LIKE ?", fmt.Sprintf("%%%s%%", token)). Where("message_id in ?", softDeletes).Find(&failDeletes) // 存储软删除失败的消息 ID var failSoftDeletes []string database.DB. Select("message_id"). - Where("sender_ids LIKE ?", fmt.Sprintf("%%%s%%", token.AuthId)). + Where("sender_ids LIKE ?", fmt.Sprintf("%%%s%%", token)). Where("message_id in ?", softDeletes).Find(&failSoftDeletes) // 存储删除操作的结果切片 diff --git a/app/request/base_requests.go b/app/request/base_requests.go index 9543b9b..f7369ee 100755 --- a/app/request/base_requests.go +++ b/app/request/base_requests.go @@ -37,7 +37,7 @@ func validateSliceAndSetContext(ctx *gin.Context, object interface{}, saveKey st // 使用 Validate 对象进行参数校验 if err := Validate.Var(object, "required,gt=0,dive,required"); err != nil { - handlingErrors(ctx, err) + HandlingValidateErrors(ctx, err) return false } @@ -62,7 +62,7 @@ func validateStructAndSetContext(ctx *gin.Context, object interface{}, saveKey s // 使用 Validate 对象进行参数校验 if err := Validate.Struct(object); err != nil { - handlingErrors(ctx, err) + HandlingValidateErrors(ctx, err) return false } @@ -72,12 +72,12 @@ func validateStructAndSetContext(ctx *gin.Context, object interface{}, saveKey s return true } -// handlingErrors 处理错误 -func handlingErrors(ctx *gin.Context, err error) { +// HandlingValidateErrors 处理错误 +func HandlingValidateErrors(ctx *gin.Context, err error) { // 处理校验错误 var invalidValidationError *validator.InvalidValidationError if errors.As(err, &invalidValidationError) { - logs.LogError.Errorf("handlingErrors %s", err) + logs.LogError.Errorf("HandlingValidateErrors %s", err) response.NewError( ctx, http.StatusBadGateway, diff --git a/app/request/message_requests.go b/app/request/message_requests.go index 61917a8..9d3f55f 100755 --- a/app/request/message_requests.go +++ b/app/request/message_requests.go @@ -2,7 +2,6 @@ package request import ( "github.com/gin-gonic/gin" - "message/app/model" "message/logs" "strings" ) @@ -26,7 +25,7 @@ func ValidateMessageRequestMiddleware() gin.HandlerFunc { // 从上下文中获取 token token, _ := ctx.Get("token") // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) message := &MessageRequest{} if !validateStructAndSetContext( @@ -34,7 +33,7 @@ func ValidateMessageRequestMiddleware() gin.HandlerFunc { message, "message", ) { - logs.LogInfo.Infof("ValidateMessageRequestMiddleware-参数错误 %s", messageToken.AuthId) + logs.LogInfo.Infof("ValidateMessageRequestMiddleware-参数错误 %s", messageToken) return } @@ -68,15 +67,15 @@ func ValidateMessageRequestMiddleware() gin.HandlerFunc { } if err := Validate.Var(&filters, "required,gt=0,dive,required"); err != nil { - handlingErrors(ctx, err) - logs.LogInfo.Infof("ValidateMessageRequestMiddleware-失败-查询过滤语法 %s", messageToken.AuthId) + HandlingValidateErrors(ctx, err) + logs.LogInfo.Infof("ValidateMessageRequestMiddleware-失败-查询过滤语法 %s", messageToken) return } ctx.Set("messageFilters", &filters) ctx.Next() } - logs.LogInfo.Infof("ValidateMessageRequestMiddleware-成功 %s", messageToken.AuthId) + logs.LogInfo.Infof("ValidateMessageRequestMiddleware-成功 %s", messageToken) } } @@ -94,17 +93,17 @@ func ValidateMessageCreateUpdateRequestMiddleware() gin.HandlerFunc { // 从上下文中获取 token token, _ := ctx.Get("token") // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) if !validateStructAndSetContext( ctx, &MessageCreateUpdateRequest{}, "messageCreateUpdate", ) { - logs.LogInfo.Infof("ValidateMessageCreateUpdateRequestMiddleware-失败-参数错误 %s", messageToken.AuthId) + logs.LogInfo.Infof("ValidateMessageCreateUpdateRequestMiddleware-失败-参数错误 %s", messageToken) return } - logs.LogInfo.Infof("ValidateMessageCreateUpdateRequestMiddleware-成功 %s", messageToken.AuthId) + logs.LogInfo.Infof("ValidateMessageCreateUpdateRequestMiddleware-成功 %s", messageToken) } } @@ -119,17 +118,17 @@ func ValidateMessageStatusRequestMiddleware() gin.HandlerFunc { // 从上下文中获取 token token, _ := ctx.Get("token") // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) if !validateSliceAndSetContext( ctx, &[]MessageStatusRequest{}, "messageStatus", ) { - logs.LogInfo.Infof("ValidateMessageStatusRequestMiddleware-失败-参数错误 %s", messageToken.AuthId) + logs.LogInfo.Infof("ValidateMessageStatusRequestMiddleware-失败-参数错误 %s", messageToken) return } - logs.LogInfo.Infof("ValidateMessageStatusRequestMiddleware-成功 %s", messageToken.AuthId) + logs.LogInfo.Infof("ValidateMessageStatusRequestMiddleware-成功 %s", messageToken) } } @@ -144,17 +143,17 @@ func ValidateMessageDeleteRequestMiddleware() gin.HandlerFunc { // 从上下文中获取 token token, _ := ctx.Get("token") // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) if !validateSliceAndSetContext( ctx, &[]MessageDeleteRequest{}, "messageDelete", ) { - logs.LogInfo.Infof("ValidateMessageDeleteRequestMiddleware-失败-参数错误 %s", messageToken.AuthId) + logs.LogInfo.Infof("ValidateMessageDeleteRequestMiddleware-失败-参数错误 %s", messageToken) return } - logs.LogInfo.Infof("ValidateMessageDeleteRequestMiddleware-成功 %s", messageToken.AuthId) + logs.LogInfo.Infof("ValidateMessageDeleteRequestMiddleware-成功 %s", messageToken) } } @@ -164,16 +163,16 @@ func ValidateMessageIdRequestMiddleware() gin.HandlerFunc { // 从上下文中获取 token token, _ := ctx.Get("token") // 将 token 转换为 MessageToken 类型 - messageToken := token.(model.MessageToken) + messageToken := token.(string) err := Validate.Var(ctx.Param("id"), "required,len=32") if err != nil { - handlingErrors(ctx, err) - logs.LogInfo.Infof("ValidateMessageIdRequestMiddleware-失败-参数错误 %s", messageToken.AuthId) + HandlingValidateErrors(ctx, err) + logs.LogInfo.Infof("ValidateMessageIdRequestMiddleware-失败-参数错误 %s", messageToken) return } ctx.Next() - logs.LogInfo.Infof("ValidateMessageIdRequestMiddleware-成功 %s", messageToken.AuthId) + logs.LogInfo.Infof("ValidateMessageIdRequestMiddleware-成功 %s", messageToken) } } diff --git a/config/config.go b/config/config.go index 57774e3..b92681d 100644 --- a/config/config.go +++ b/config/config.go @@ -21,6 +21,10 @@ type ServiceConfig struct { Error string `yaml:"error"` Access string `yaml:"access"` } `yaml:"log"` + Verify struct { + Table string `yaml:"table"` + Column string `yaml:"column"` + } `yaml:"verify"` } `yaml:"app"` Database struct { Host string `yaml:"host"` diff --git a/config/config.yaml b/config/config.yaml index a48e3cc..12aa005 100644 --- a/config/config.yaml +++ b/config/config.yaml @@ -19,6 +19,11 @@ app: error: logs/error.log access: logs/access.log + # 验证的信息 + verify: + table: user + column: message_token + database: host: 127.0.0.1 port: 3306 diff --git a/database/migrations.go b/database/migrations.go index df0941e..737b850 100755 --- a/database/migrations.go +++ b/database/migrations.go @@ -19,8 +19,6 @@ func InitMigration() { err := DB.Set("gorm:table_options", dbConfig).AutoMigrate( // 迁移消息模型 &model.Message{}, - // 迁移消息令牌模型 - &model.MessageToken{}, ) if err != nil { // 输出迁移错误信息 diff --git a/docs/docs.go b/docs/docs.go index 04cdbb2..6e53e00 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -28,7 +28,7 @@ const docTemplate = `{ "get": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "根据用户凭证查询消息", @@ -104,7 +104,7 @@ const docTemplate = `{ "post": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "创建消息", @@ -165,7 +165,7 @@ const docTemplate = `{ "delete": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "根据数组的数据删除消息", @@ -234,7 +234,7 @@ const docTemplate = `{ "put": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "根据数组的数据更新消息状态", @@ -297,7 +297,7 @@ const docTemplate = `{ "put": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "根据消息id更新消息", @@ -484,40 +484,58 @@ const docTemplate = `{ "type": "object", "properties": { "big_content": { - "type": "string" + "type": "string", + "example": "复杂的内容" }, "category": { - "type": "string" + "type": "string", + "example": "important" }, "content": { - "type": "string" + "type": "string", + "example": "简单的内容" }, "created_at": { - "type": "string" + "type": "string", + "example": "2024-02-15T05:49:57Z" }, "introducer_ids": { "type": "array", "items": { "type": "string" - } + }, + "example": [ + "fc64c1a807c2e69655f68d31e5caa35d", + "70c021d35ce60436c115b20b5cf583d0", + "..." + ] }, "message_id": { - "type": "string" + "type": "string", + "example": "7e55cb38290f49ee2b0e9cfd2adf13e4" }, "sender_ids": { "type": "array", "items": { "type": "string" - } + }, + "example": [ + "2f14ec370621a8be08c8f0ece459e7e0", + "22798c5dcd6e5b66c8660c447010d49d", + "..." + ] }, "status": { - "type": "integer" + "type": "integer", + "example": 0 }, "title": { - "type": "string" + "type": "string", + "example": "标题" }, "updated_at": { - "type": "string" + "type": "string", + "example": "2024-02-15T05:49:57Z" } } }, @@ -557,8 +575,10 @@ const docTemplate = `{ } }, "securityDefinitions": { - "BasicAuth": { - "type": "basic" + "ApiKeyAuth": { + "type": "apiKey", + "name": "Authorization", + "in": "header" } }, "externalDocs": { diff --git a/docs/swagger.json b/docs/swagger.json index 7b1c9a1..c0eb23f 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -22,7 +22,7 @@ "get": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "根据用户凭证查询消息", @@ -98,7 +98,7 @@ "post": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "创建消息", @@ -159,7 +159,7 @@ "delete": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "根据数组的数据删除消息", @@ -228,7 +228,7 @@ "put": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "根据数组的数据更新消息状态", @@ -291,7 +291,7 @@ "put": { "security": [ { - "BasicAuth": [] + "ApiKeyAuth": [] } ], "description": "根据消息id更新消息", @@ -478,40 +478,58 @@ "type": "object", "properties": { "big_content": { - "type": "string" + "type": "string", + "example": "复杂的内容" }, "category": { - "type": "string" + "type": "string", + "example": "important" }, "content": { - "type": "string" + "type": "string", + "example": "简单的内容" }, "created_at": { - "type": "string" + "type": "string", + "example": "2024-02-15T05:49:57Z" }, "introducer_ids": { "type": "array", "items": { "type": "string" - } + }, + "example": [ + "fc64c1a807c2e69655f68d31e5caa35d", + "70c021d35ce60436c115b20b5cf583d0", + "..." + ] }, "message_id": { - "type": "string" + "type": "string", + "example": "7e55cb38290f49ee2b0e9cfd2adf13e4" }, "sender_ids": { "type": "array", "items": { "type": "string" - } + }, + "example": [ + "2f14ec370621a8be08c8f0ece459e7e0", + "22798c5dcd6e5b66c8660c447010d49d", + "..." + ] }, "status": { - "type": "integer" + "type": "integer", + "example": 0 }, "title": { - "type": "string" + "type": "string", + "example": "标题" }, "updated_at": { - "type": "string" + "type": "string", + "example": "2024-02-15T05:49:57Z" } } }, @@ -551,8 +569,10 @@ } }, "securityDefinitions": { - "BasicAuth": { - "type": "basic" + "ApiKeyAuth": { + "type": "apiKey", + "name": "Authorization", + "in": "header" } }, "externalDocs": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 8022f91..8903bb2 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -81,28 +81,44 @@ definitions: response.Message: properties: big_content: + example: 复杂的内容 type: string category: + example: important type: string content: + example: 简单的内容 type: string created_at: + example: "2024-02-15T05:49:57Z" type: string introducer_ids: + example: + - fc64c1a807c2e69655f68d31e5caa35d + - 70c021d35ce60436c115b20b5cf583d0 + - '...' items: type: string type: array message_id: + example: 7e55cb38290f49ee2b0e9cfd2adf13e4 type: string sender_ids: + example: + - 2f14ec370621a8be08c8f0ece459e7e0 + - 22798c5dcd6e5b66c8660c447010d49d + - '...' items: type: string type: array status: + example: 0 type: integer title: + example: 标题 type: string updated_at: + example: "2024-02-15T05:49:57Z" type: string type: object response.MessageDeleteResponse: @@ -188,7 +204,7 @@ paths: schema: type: string security: - - BasicAuth: [] + - ApiKeyAuth: [] summary: 删除消息 tags: - message @@ -237,7 +253,7 @@ paths: schema: $ref: '#/definitions/response.HTTPError' security: - - BasicAuth: [] + - ApiKeyAuth: [] summary: 查询消息 tags: - message @@ -276,7 +292,7 @@ paths: schema: $ref: '#/definitions/response.HTTPError' security: - - BasicAuth: [] + - ApiKeyAuth: [] summary: 创建消息 tags: - message @@ -325,7 +341,7 @@ paths: schema: $ref: '#/definitions/response.HTTPError' security: - - BasicAuth: [] + - ApiKeyAuth: [] summary: 更新消息 tags: - message @@ -365,11 +381,13 @@ paths: schema: $ref: '#/definitions/response.HTTPError' security: - - BasicAuth: [] + - ApiKeyAuth: [] summary: 更新状态 tags: - message securityDefinitions: - BasicAuth: - type: basic + ApiKeyAuth: + in: header + name: Authorization + type: apiKey swagger: "2.0" diff --git a/main.go b/main.go index e7373b5..6a09cec 100644 --- a/main.go +++ b/main.go @@ -27,7 +27,9 @@ import ( // @host localhost:1204 // @BasePath / -// @securityDefinitions.basic BasicAuth +// @securityDefinitions.apikey ApiKeyAuth +// @in header +// @name Authorization // @externalDocs.description OpenAPI // @externalDocs.url https://swagger.io/resources/open-api/