util.go 612 Bytes
Newer Older
qiuqunfeng's avatar
qiuqunfeng committed
1 2 3 4 5 6
package utils

import (
	"net/http"

	"github.com/gin-gonic/gin"
qiuqunfeng's avatar
commit  
qiuqunfeng committed
7
	"github.com/rs/zerolog/log"
qiuqunfeng's avatar
qiuqunfeng committed
8 9 10 11 12 13 14
)

const APIVersion = "v1"

func AssembleResponse(c *gin.Context, data interface{}, err error, opts ...ResponseDataOptionFunc) {
	code := http.StatusOK
	if err != nil {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
15
		log.Error().Err(err)
qiuqunfeng's avatar
qiuqunfeng committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
		code = http.StatusInternalServerError
		c.JSON(code, FailResponse{
			APIVersion: APIVersion,
			Error: RespErr{
				Code:    code,
				Message: err.Error(),
			},
		})
		return
	}
	resp := SuccessResponse{
		APIVersion: APIVersion,
		Data:       data,
	}

	for _, opt := range opts {
		opt(&resp)
	}

	c.JSON(code, resp)
}