api-base/pkg/response/response.go

82 lines
2.0 KiB
Go

package response
type RespType string
const (
RespSuccess RespType = "success"
RespCreated RespType = "created"
RespAccepted RespType = "accepted"
RespNoContent RespType = "noContent"
RespRedirect RespType = "redirect"
RespDataFormat RespType = "dataFormat"
RespUnauthorized RespType = "unauthorized"
RespForbidden RespType = "forbidden"
RespNotFound RespType = "notFound"
RespInternalError RespType = "internalError"
)
// swagger:model defResponse
type RespBody struct {
MessageCode MessageCode `json:"messageCode"`
Message string `json:"message"`
}
// swagger:response genericResponse
type Resp struct {
// in: body
Body RespBody
Status int
}
func Get(key RespType, c ...MessageCode) Resp {
r := Resp{Body: RespBody{}}
switch key {
case RespSuccess:
r.Status = 200
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeSuccess)
break
case RespCreated:
r.Status = 201
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeCreated)
break
case RespAccepted:
r.Status = 202
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeAccepted)
break
case RespNoContent:
r.Status = 204
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeNoContent)
break
case RespRedirect:
r.Status = 301
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeRedirect)
break
case RespDataFormat:
r.Status = 400
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeDataFormat)
break
case RespUnauthorized:
r.Status = 401
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeUnauthorized)
break
case RespForbidden:
r.Status = 403
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeForbidden)
break
case RespNotFound:
r.Status = 404
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeNotFound)
break
default:
r.Status = 500
r.Body.MessageCode, r.Body.Message = GetCodeMessage(CodeInternalError)
}
if len(c) > 0 {
r.Body.MessageCode, r.Body.Message = GetCodeMessage(c[0])
}
return r
}