Fix duplicate responses

This commit is contained in:
rxdn 2024-11-12 21:35:31 +00:00
parent 941c033323
commit b989f1b82d

View File

@ -1,6 +1,7 @@
package middleware
import (
"bytes"
"errors"
"github.com/TicketsBot/GoPanel/app"
"github.com/gin-gonic/gin"
@ -10,7 +11,19 @@ type ErrorResponse struct {
Error string `json:"error"`
}
type copyWriter struct {
gin.ResponseWriter
buf *bytes.Buffer
}
func (cw copyWriter) Write(b []byte) (int, error) {
return cw.buf.Write(b)
}
func ErrorHandler(c *gin.Context) {
cw := &copyWriter{buf: &bytes.Buffer{}, ResponseWriter: c.Writer}
c.Writer = cw
c.Next()
if len(c.Errors) > 0 {
@ -26,11 +39,17 @@ func ErrorHandler(c *gin.Context) {
c.JSON(-1, ErrorResponse{
Error: message,
})
return
}
if c.Writer.Status() >= 500 && len(c.Errors) == 0 {
if c.Writer.Status() >= 500 {
c.JSON(-1, ErrorResponse{
Error: "An internal server error occurred",
})
return
}
c.Writer.Write(cw.buf.Bytes())
}