-
Notifications
You must be signed in to change notification settings - Fork 5
/
middleware.go
64 lines (56 loc) · 1.17 KB
/
middleware.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
package tgbot
import (
"fmt"
"io"
"time"
"github.com/fatih/color"
)
func Recover(c *Context) (err error) {
defer func() {
if r := recover(); r != nil {
switch r := r.(type) {
case error:
err = r
default:
err = fmt.Errorf("%v", r)
}
}
}()
return c.Next()
}
func Logger(out io.Writer) func(*Context) error {
cyan := color.New(color.FgCyan)
white := color.New(color.FgWhite)
red := color.New(color.FgRed)
yellow := color.New(color.FgYellow)
green := color.New(color.FgGreen)
return func(c *Context) error {
start := time.Now()
p := c.Path
err := c.Next()
pp := c.Path
indent := "16"
cyan.Fprintf(out, "%13v ", time.Now().Sub(start))
fmt.Fprint(out, "<~")
white.Fprintf(out, " %s", p)
if c.Text != "" {
white.Fprintf(out, " (payload: '%s')", c.Text)
}
if p != pp {
white.Fprintf(out, "\n%"+indent+"v └── %s (override)", "", pp)
indent = "20"
}
defer fmt.Fprintln(out)
white.Fprintf(out, "\n%"+indent+"v └── ", "")
if err != nil {
if e, ok := err.(*Error); ok && e.Code == 404 {
yellow.Fprint(out, err)
} else {
red.Fprint(out, err)
}
} else {
green.Fprint(out, "OK")
}
return err
}
}