From 7d309e567cb9b6f9b157960d9217b440f8a03865 Mon Sep 17 00:00:00 2001 From: luduoxin <379356950@qq.com> Date: Thu, 18 Jan 2024 17:10:39 +0800 Subject: [PATCH] add WithoutCancel context --- api/gin.go | 6 +++--- lib/middleware/recovery.go | 2 +- utils/context.go | 31 +++++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 utils/context.go diff --git a/api/gin.go b/api/gin.go index a1d0cbc..bb18bce 100644 --- a/api/gin.go +++ b/api/gin.go @@ -193,18 +193,18 @@ func logger(ignoreRelease bool) gin.HandlerFunc { start := time.Now() path := c.Request.URL.Path raw := c.Request.URL.RawQuery - // Process request c.Next() if raw != "" { path = path + "?" + raw } - // ignore logger output if gin.Mode() == gin.ReleaseMode && ignoreRelease { return } - + if path == "/health" || path == "/monitor/prometheus" { + return + } // End time end := time.Now() fmt.Fprintf(os.Stdout, "[GIN] %s | %3d | %13v | %15s | %-7s %#v\n%s", end.Format("2006/01/02 - 15:04:05"), c.Writer.Status(), end.Sub(start), c.ClientIP(), c.Request.Method, path, c.Errors.ByType(gin.ErrorTypePrivate).String()) diff --git a/lib/middleware/recovery.go b/lib/middleware/recovery.go index cad8534..b761471 100644 --- a/lib/middleware/recovery.go +++ b/lib/middleware/recovery.go @@ -39,7 +39,7 @@ func Recovery() gin.HandlerFunc { }{ Code: -1, Data: nil, - Msg: "gin panic", + Msg: "server panic", }) c.Abort() } diff --git a/utils/context.go b/utils/context.go new file mode 100644 index 0000000..3d33fad --- /dev/null +++ b/utils/context.go @@ -0,0 +1,31 @@ +package utils + +import ( + "context" + "time" +) + +// WithoutCancel returns a copy of parent that is not canceled when parent is canceled. +// The returned context returns no Deadline or Err, and its Done channel is nil. +func WithoutCancel(parent context.Context) context.Context { + if parent == nil { + parent = context.Background() + } + return withoutCancelCtx{parent} +} + +type withoutCancelCtx struct { + context.Context +} + +func (withoutCancelCtx) Deadline() (deadline time.Time, ok bool) { + return +} + +func (withoutCancelCtx) Done() <-chan struct{} { + return nil +} + +func (withoutCancelCtx) Err() error { + return nil +}