intelligent_monitoring_backend/Code/backend/internal/api/response.go

68 lines
1.3 KiB
Go
Raw Normal View History

2024-10-24 23:11:29 +08:00
package api
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
const (
CodeSuccess = 200
)
type Response struct {
Code int `json:"code"`
Err string `json:"errMsg,omitempty"`
Data interface{} `json:"data,omitempty"`
IsSuccess bool `json:"isSuccess"`
RequestID string `json:"requestID,omitempty"`
}
func (r Response) String() string {
return r.Err
}
func (r Response) LowerString() string {
return strings.ToLower(r.String())
}
func (r Response) Error() string {
return r.Err
}
func (r Response) Success() bool {
return r.Err == "" && r.Code < 400
}
func NewResponse(code int, id Message, params ...interface{}) Response {
return Response{Code: code, Err: Msg(id, params...)}
}
func Success(c *gin.Context, data interface{}) {
response := Response{
Code: CodeSuccess,
Data: data,
IsSuccess: true,
}
c.JSON(http.StatusOK, response)
}
func SuccessBool(c *gin.Context, data interface{}, success bool) {
response := Response{
Code: CodeSuccess,
Data: data,
IsSuccess: success,
}
c.JSON(http.StatusOK, response)
}
func SuccessYAML(c *gin.Context, data interface{}) {
response := Response{
Code: CodeSuccess,
Data: data,
IsSuccess: true,
}
c.YAML(http.StatusOK, response)
}