2024-01-12 19:18:33 +08:00
|
|
|
package nf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2024-01-14 19:10:05 +08:00
|
|
|
"log"
|
2024-01-12 19:18:33 +08:00
|
|
|
"os"
|
|
|
|
"runtime/debug"
|
2024-01-14 19:10:05 +08:00
|
|
|
"time"
|
2024-01-12 19:18:33 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func NewRecover(enableStackTrace bool) HandlerFunc {
|
|
|
|
return func(c *Ctx) error {
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
if enableStackTrace {
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("recovered from panic: %v\n%s\n", r, debug.Stack()))
|
|
|
|
} else {
|
|
|
|
os.Stderr.WriteString(fmt.Sprintf("recovered from panic: %v\n", r))
|
|
|
|
}
|
2024-02-20 15:34:00 +08:00
|
|
|
|
|
|
|
//serveError(c, 500, []byte(fmt.Sprint(r)))
|
|
|
|
_ = c.Status(500).SendString(fmt.Sprint(r))
|
2024-01-12 19:18:33 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return c.Next()
|
|
|
|
}
|
|
|
|
}
|
2024-01-14 19:10:05 +08:00
|
|
|
|
|
|
|
func NewLogger() HandlerFunc {
|
|
|
|
l := log.New(os.Stdout, "[NF] ", 0)
|
|
|
|
|
|
|
|
durationFormat := func(num int64) string {
|
|
|
|
var (
|
|
|
|
unit = "ns"
|
|
|
|
)
|
|
|
|
|
|
|
|
if num > 1000 {
|
|
|
|
num = num / 1000
|
|
|
|
unit = "µs"
|
|
|
|
}
|
|
|
|
|
|
|
|
if num > 1000 {
|
|
|
|
num = num / 1000
|
|
|
|
unit = "ms"
|
|
|
|
}
|
|
|
|
|
|
|
|
if num > 1000 {
|
|
|
|
num = num / 1000
|
2024-02-20 15:34:00 +08:00
|
|
|
unit = "s"
|
2024-01-14 19:10:05 +08:00
|
|
|
}
|
|
|
|
|
2024-02-20 15:34:00 +08:00
|
|
|
return fmt.Sprintf("%3d %2s", num, unit)
|
2024-01-14 19:10:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return func(c *Ctx) error {
|
|
|
|
start := time.Now()
|
|
|
|
|
|
|
|
err := c.Next()
|
|
|
|
|
|
|
|
var (
|
|
|
|
duration = time.Now().Sub(start).Nanoseconds()
|
|
|
|
status = c.StatusCode
|
|
|
|
path = c.path
|
|
|
|
method = c.Request.Method
|
|
|
|
)
|
|
|
|
|
|
|
|
l.Printf("%s | %5s | %d | %s | %s",
|
|
|
|
start.Format("06/01/02T15:04:05"),
|
|
|
|
method,
|
|
|
|
status,
|
|
|
|
durationFormat(duration),
|
|
|
|
path,
|
|
|
|
)
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|