This repository was archived by the owner on Sep 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
70 lines (65 loc) · 1.42 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// 🚀 Fiber is an Express inspired web framework written in Go with 💖
// 📌 API Documentation: https://fiber.wiki
// 📝 Github Repository: https://github.com/gofiber/fiber
package recover
import (
"fmt"
"io"
"os"
"github.com/gofiber/fiber"
)
// Config ...
type Config struct {
// Filter defines a function to skip middleware.
// Optional. Default: nil
Filter func(*fiber.Ctx) bool
// DEPRECTAED, Fiber Global ErrorHandler is called instead
Handler func(*fiber.Ctx, error)
// Log all errors to output
// Optional. Default: false
Log bool
// Output is a writter where logs are written
// Default: os.Stderr
Output io.Writer
}
// New ...
func New(config ...Config) func(*fiber.Ctx) {
// Init config
var cfg Config
// Set config if provided
if len(config) > 0 {
cfg = config[0]
}
// Set config default values
if cfg.Handler == nil {
cfg.Handler = func(c *fiber.Ctx, err error) {
c.SendStatus(500)
}
}
if cfg.Output == nil {
cfg.Output = os.Stderr
}
// Return middleware handle
return func(c *fiber.Ctx) {
// Filter request to skip middleware
if cfg.Filter != nil && cfg.Filter(c) {
c.Next()
return
}
defer func() {
if r := recover(); r != nil {
err, ok := r.(error)
if !ok {
err = fmt.Errorf("%v", r)
}
// Log error
if cfg.Log {
_, _ = cfg.Output.Write([]byte(err.Error() + "\n"))
}
// Call global error handler
c.Next(err)
}
}()
c.Next()
}
}