mirror of
https://github.com/Li4n0/revsuit.git
synced 2026-09-25 08:01:54 +08:00
feat(recycler): add error cecycler (#10)
This commit is contained in:
@@ -1,11 +1,18 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/li4n0/revsuit/internal/record"
|
||||
"github.com/li4n0/revsuit/internal/recycler"
|
||||
log "unknwon.dev/clog/v2"
|
||||
)
|
||||
|
||||
@@ -33,3 +40,48 @@ func events(c *gin.Context) {
|
||||
})
|
||||
log.Info(c.Request.RemoteAddr, "disconnect")
|
||||
}
|
||||
|
||||
func recovery(c *gin.Context) {
|
||||
timeFormat := func(t time.Time) string {
|
||||
var timeString = t.Format("2006/01/02 - 15:04:05")
|
||||
return timeString
|
||||
}
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
// Check for a broken connection, as it is not really a
|
||||
// condition that warrants a panic stack trace.
|
||||
var brokenPipe bool
|
||||
if ne, ok := err.(*net.OpError); ok {
|
||||
if se, ok := ne.Err.(*os.SyscallError); ok {
|
||||
if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
|
||||
brokenPipe = true
|
||||
}
|
||||
}
|
||||
}
|
||||
httpRequest, _ := httputil.DumpRequest(c.Request, false)
|
||||
headers := strings.Split(string(httpRequest), "\r\n")
|
||||
for idx, header := range headers {
|
||||
current := strings.Split(header, ":")
|
||||
if current[0] == "Authorization" {
|
||||
headers[idx] = current[0] + ": *"
|
||||
}
|
||||
}
|
||||
if brokenPipe {
|
||||
recycler.Recycle(fmt.Sprintf("%s\n%s", err, string(httpRequest)))
|
||||
} else if gin.IsDebugging() {
|
||||
recycler.Recycle(fmt.Sprintf("[Recovery] %s panic recovered:\n%s\n%s\n", timeFormat(time.Now()), strings.Join(headers, "\r\n"), err))
|
||||
} else {
|
||||
recycler.Recycle(fmt.Sprintf("[Recovery] %s panic recovered:\n%s\n", timeFormat(time.Now()), err))
|
||||
}
|
||||
|
||||
// If the connection is dead, we can't write a status to it.
|
||||
if brokenPipe {
|
||||
_ = c.Error(err.(error)) // nolint: errcheck
|
||||
c.Abort()
|
||||
} else {
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user