api_response.go 1.26 KB
Newer Older
haoyanbin's avatar
1  
haoyanbin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
package response

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"regexp"
	_ "regexp"
)

const (
	APIERROR    = 400
	APIERROR401 = 401
	APIERROR402 = 402
	APIERROR403 = 403
	APIERROR404 = 404
	APISUCCESS  = 200
)

func ApiResult(code int, data interface{}, msg string, c *gin.Context) {
	// 开始时间
	c.JSON(http.StatusOK, Response{
		code,
		data,
		msg,
	})
}

func ApiOk(c *gin.Context) {
	Result(APISUCCESS, map[string]interface{}{}, "操作成功", c)
}

func ApiOkWithMessage(message string, c *gin.Context) {
	Result(APISUCCESS, map[string]interface{}{}, message, c)
}

func ApiOkWithData(data interface{}, c *gin.Context) {
	Result(APISUCCESS, data, "请求成功", c)
}

func ApiOkWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(APISUCCESS, data, message, c)
}

func ApiFail(c *gin.Context) {
	Result(APIERROR, map[string]interface{}{}, "请求失败", c)
}

func ApiFailWithMessage(errorCode int, message string, c *gin.Context) {
	res := regexp.MustCompile("[\u4e00-\u9fa5]").FindAllStringSubmatch(message, -1)

	var result string
	for _, i := range res {
		result += i[0]
	}

	Result(errorCode, map[string]interface{}{}, result, c)
}

func ApiFailWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(APIERROR, data, message, c)
}