54 lines
1.0 KiB
Go
54 lines
1.0 KiB
Go
package service
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type ResponseData struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data interface{} `json:"data"`
|
|
}
|
|
|
|
func ErrorResponse(c *gin.Context, code int, message string) {
|
|
c.JSON(code, ResponseData{
|
|
Code: code,
|
|
Message: message,
|
|
Data: nil,
|
|
})
|
|
}
|
|
|
|
func SuccessResponse(c *gin.Context, code int, data interface{}) {
|
|
c.JSON(code, ResponseData{
|
|
Code: code,
|
|
Message: "success",
|
|
Data: data,
|
|
})
|
|
}
|
|
|
|
func UnifiedResponseMiddleware() gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
ctx.Next()
|
|
|
|
if len(ctx.Errors) > 0 {
|
|
err := ctx.Errors.Last()
|
|
ErrorResponse(ctx, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
if ctx.Writer.Status() == 0 {
|
|
ctx.Writer.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
if ctx.Writer.Status() >= http.StatusOK && ctx.Writer.Status() < http.StatusMultipleChoices {
|
|
data, exists := ctx.Get("response_data")
|
|
if exists {
|
|
SuccessResponse(ctx, ctx.Writer.Status(), data)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|