util.go 626 Bytes
Newer Older
qiuqunfeng's avatar
qiuqunfeng 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
package utils

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"gitlab.com/security-rd/go-pkg/logging"
)

const APIVersion = "v1"

func AssembleResponse(c *gin.Context, data interface{}, err error, opts ...ResponseDataOptionFunc) {
	code := http.StatusOK
	if err != nil {
		logging.Get().Err(err)
		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)
}