feat(recycler): add error cecycler (#10)

This commit is contained in:
Li4n0
2021-04-26 16:31:32 +08:00
committed by GitHub
parent 7e99d93e43
commit 3d8507e682
19 changed files with 263 additions and 67 deletions
+52
View File
@@ -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()
}
+4 -4
View File
@@ -15,10 +15,10 @@ import (
)
func (revsuit *Revsuit) registerRouter() {
revsuit.http.Router = gin.Default()
if revsuit.logLevel != log.LevelTrace {
revsuit.http.Router = gin.New()
revsuit.http.Router.Use(gin.Recovery())
revsuit.http.Router = gin.New()
revsuit.http.Router.Use(recovery)
if revsuit.logLevel == log.LevelTrace {
revsuit.http.Router.Use(gin.Logger())
}
revsuit.registerPlatformRouter()