You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.9 KiB
61 lines
1.9 KiB
package response
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
|
|
"git.devices.local/mawas/golang-api-skeleton/lib/apperrors"
|
|
"github.com/gin-gonic/gin"
|
|
errs "github.com/go-errors/errors"
|
|
)
|
|
|
|
// Envelope for response objects
|
|
type Envelope struct {
|
|
Success bool `json:"success"`
|
|
RequestID string `json:"request_id,omitempty"`
|
|
Warnings []string `json:"warnings,omitempty"`
|
|
Errors []apperrors.Error `json:"errors,omitempty"`
|
|
// PaginationInfo *pagination.Pagination `json:"pagination_info,omitempty"`
|
|
Result interface{} `json:"result,omitempty"`
|
|
}
|
|
|
|
// AppendError to envelope
|
|
func (envelope *Envelope) AppendError(err error) *Envelope {
|
|
envelope.Success = false
|
|
envelope.Result = nil
|
|
envelope.Errors = append(envelope.Errors, err.(apperrors.Error))
|
|
return envelope
|
|
}
|
|
|
|
// HTTPError to envelope
|
|
func (envelope *Envelope) HTTPError(err error) (int, *Envelope) {
|
|
envelope.Success = false
|
|
envelope.Result = nil
|
|
if e, ok := err.(apperrors.Error); ok {
|
|
envelope.Errors = append(envelope.Errors, e)
|
|
return e.HTTPStatus, envelope
|
|
}
|
|
e := apperrors.NewError(apperrors.UnknownError, err.Error())
|
|
envelope.Errors = append(envelope.Errors, e.(apperrors.Error))
|
|
return http.StatusInternalServerError, envelope
|
|
}
|
|
|
|
// SetSuccess to envelope
|
|
func (envelope *Envelope) SetSuccess(result interface{}) *Envelope {
|
|
envelope.Success = true
|
|
envelope.Result = result
|
|
return envelope
|
|
}
|
|
|
|
// Recovery returns with JSON error after panic
|
|
func (envelope *Envelope) Recovery(c *gin.Context) {
|
|
if err := recover(); err != nil {
|
|
httprequest, _ := httputil.DumpRequest(c.Request, false)
|
|
goErr := errs.Wrap(err, 3)
|
|
reset := string([]byte{27, 91, 48, 109})
|
|
fmt.Printf("panic recovered:\n\n%s%s\n\n%s%s", httprequest, goErr.Error(), goErr.Stack(), reset)
|
|
envelope.AppendError(apperrors.NewError(apperrors.UnknownError, fmt.Sprintf("%s\n%s", goErr.Error(), goErr.Stack())))
|
|
c.AbortWithStatusJSON(500, envelope)
|
|
}
|
|
}
|