Skip to content
Myr

recovery.go

This file

Path

recovery.go

204 lines · 5.7 KiB · Go

Last changed by

fix(recovery): record recovered panics in c.Errors (#4698)DadaVinqibefore adoption4a3eb31

History of this file

Take it

The walk stopped after 200 commits: lines older than cf32d2d point at it.

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 1–7why, one step back
1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (

perf(recovery): optimize line reading in stack function (#4466)Namebefore adoption64a6ed9

line 8why, one step back
8 "bufio"

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

line 9why, one step back
9 "bytes"

perf(recovery): optimize line reading in stack function (#4466)Namebefore adoption64a6ed9

line 10why, one step back
10 "cmp"

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 11–19why, one step back
11 "errors"
12 "fmt"13 "io"14 "log"15 "net/http"16 "net/http/httputil"17 "os"18 "runtime"19 "strings"

refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d

line 20why, one step back
20 "syscall"

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

line 21why, one step back
21 "time"

perf(recovery): optimize the log output of CustomRecoveryWithWriter (#4258)Namebefore adoption45b805f

lines 22–23why, one step back
22
23 "github.com/gin-gonic/gin/internal/bytesconv"

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 24–25why, one step back
24)
25

perf(recovery): optimize line reading in stack function (#4466)Namebefore adoption64a6ed9

lines 26–29why, one step back
26const (
27 dunno = "???"28 stackSkip = 329)

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 30–59why, one step back
30
31// RecoveryFunc defines the function passable to CustomRecovery.32type RecoveryFunc func(c *Context, err any)3334// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.35func Recovery() HandlerFunc {36 return RecoveryWithWriter(DefaultErrorWriter)37}3839// CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it.40func CustomRecovery(handle RecoveryFunc) HandlerFunc {41 return RecoveryWithWriter(DefaultErrorWriter, handle)42}4344// RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.45func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc {46 if len(recovery) > 0 {47 return CustomRecoveryWithWriter(out, recovery[0])48 }49 return CustomRecoveryWithWriter(out, defaultHandleRecovery)50}5152// CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.53func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {54 var logger *log.Logger55 if out != nil {56 logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags)57 }58 return func(c *Context) {59 defer func() {

refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d

line 60why, one step back
60 if rec := recover(); rec != nil {

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 61–62why, one step back
61 // Check for a broken connection, as it is not really a
62 // condition that warrants a panic stack trace.

refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d

lines 63–68why, one step back
63 var isBrokenPipe bool
64 err, ok := rec.(error)65 if ok {66 isBrokenPipe = errors.Is(err, syscall.EPIPE) ||67 errors.Is(err, syscall.ECONNRESET) ||68 errors.Is(err, http.ErrAbortHandler)

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 69–70why, one step back
69 }
70 if logger != nil {

refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d

lines 71–72why, one step back
71 if isBrokenPipe {
72 logger.Printf("%s\n%s%s", rec, secureRequestDump(c.Request), reset)

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 73–74why, one step back
73 } else if IsDebugging() {
74 logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",

refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d

line 75why, one step back
75 timeFormat(time.Now()), secureRequestDump(c.Request), rec, stack(stackSkip), reset)

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 76–77why, one step back
76 } else {
77 logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s",

refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d

line 78why, one step back
78 timeFormat(time.Now()), rec, stack(stackSkip), reset)

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 79–80why, one step back
79 }
80 }

refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d

line 81why, one step back
81 if isBrokenPipe {

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

line 82why, one step back
82 // If the connection is dead, we can't write a status to it.

refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d

line 83why, one step back
83 c.Error(err) //nolint: errcheck

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 84–85why, one step back
84 c.Abort()
85 } else {

refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d

line 86why, one step back
86 handle(c, rec)

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 87–93why, one step back
87 }
88 }89 }()90 c.Next()91 }92}93

perf(recovery): optimize the log output of CustomRecoveryWithWriter (#4258)Namebefore adoption45b805f

lines 94–108why, one step back
94// secureRequestDump returns a sanitized HTTP request dump where the Authorization header,
95// if present, is replaced with a masked value ("Authorization: *") to avoid leaking sensitive credentials.96//97// Currently, only the Authorization header is sanitized. All other headers and request data remain unchanged.98func secureRequestDump(r *http.Request) string {99 httpRequest, _ := httputil.DumpRequest(r, false)100 lines := strings.Split(bytesconv.BytesToString(httpRequest), "\r\n")101 for i, line := range lines {102 if strings.HasPrefix(line, "Authorization:") {103 lines[i] = "Authorization: *"104 }105 }106 return strings.Join(lines, "\r\n")107}108

fix(recovery): record recovered panics in c.Errors (#4698)DadaVinqibefore adoption4a3eb31

lines 109–114why, one step back
109func defaultHandleRecovery(c *Context, err any) {
110 e, ok := err.(error)111 if !ok {112 e = fmt.Errorf("%v", err)113 }114 c.Error(e) //nolint: errcheck

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 115–122why, one step back
115 c.AbortWithStatus(http.StatusInternalServerError)
116}117118// stack returns a nicely formatted stack frame, skipping skip frames.119func stack(skip int) []byte {120 buf := new(bytes.Buffer) // the returned data121 // As we loop, we open files and read them. These variables record the currently122 // loaded file.

perf(recovery): optimize line reading in stack function (#4466)Namebefore adoption64a6ed9

lines 123–127why, one step back
123 var (
124 nLine string125 lastFile string126 err error127 )

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 128–135why, one step back
128 for i := skip; ; i++ { // Skip the expected number of frames
129 pc, file, line, ok := runtime.Caller(i)130 if !ok {131 break132 }133 // Print this much at least. If we can't find the source, it won't show.134 fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)135 if file != lastFile {

perf(recovery): optimize line reading in stack function (#4466)Namebefore adoption64a6ed9

line 136why, one step back
136 nLine, err = readNthLine(file, line-1)

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 137–141why, one step back
137 if err != nil {
138 continue139 }140 lastFile = file141 }

perf(recovery): optimize line reading in stack function (#4466)Namebefore adoption64a6ed9

line 142why, one step back
142 fmt.Fprintf(buf, "\t%s: %s\n", function(pc), cmp.Or(nLine, dunno))

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 143–146why, one step back
143 }
144 return buf.Bytes()145}146

perf(recovery): optimize line reading in stack function (#4466)Namebefore adoption64a6ed9

lines 147–153why, one step back
147// readNthLine reads the nth line from the file.
148// It returns the trimmed content of the line if found,149// or an empty string if the line doesn't exist.150// If there's an error opening the file, it returns the error.151func readNthLine(file string, n int) (string, error) {152 if n < 0 {153 return "", nil

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

line 154why, one step back
154 }

perf(recovery): optimize line reading in stack function (#4466)Namebefore adoption64a6ed9

lines 155–173why, one step back
155
156 f, err := os.Open(file)157 if err != nil {158 return "", err159 }160 defer f.Close()161162 scanner := bufio.NewScanner(f)163 for i := 0; i < n; i++ {164 if !scanner.Scan() {165 return "", nil166 }167 }168169 if scanner.Scan() {170 return strings.TrimSpace(scanner.Text()), nil171 }172173 return "", nil

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 174–176why, one step back
174}
175176// function returns, if possible, the name of the function containing the PC.

perf(recover): replace bytes with strings in function for better performance (#4252)Namebefore adoption3c12d2a

line 177why, one step back
177func function(pc uintptr) string {

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 178–181why, one step back
178 fn := runtime.FuncForPC(pc)
179 if fn == nil {180 return dunno181 }

perf(recover): replace bytes with strings in function for better performance (#4252)Namebefore adoption3c12d2a

line 182why, one step back
182 name := fn.Name()

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 183–190why, one step back
183 // The name includes the path name to the package, which is unnecessary
184 // since the file name is already included. Plus, it has center dots.185 // That is, we see186 // runtime/debug.*T·ptrmethod187 // and want188 // *T.ptrmethod189 // Also the package path might contain dot (e.g. code.google.com/...),190 // so first eliminate the path prefix

perf(recover): replace bytes with strings in function for better performance (#4252)Namebefore adoption3c12d2a

line 191why, one step back
191 if lastSlash := strings.LastIndexByte(name, '/'); lastSlash >= 0 {

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 192–193why, one step back
192 name = name[lastSlash+1:]
193 }

perf(recover): replace bytes with strings in function for better performance (#4252)Namebefore adoption3c12d2a

line 194why, one step back
194 if period := strings.IndexByte(name, '.'); period >= 0 {

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 195–196why, one step back
195 name = name[period+1:]
196 }

perf(recover): replace bytes with strings in function for better performance (#4252)Namebefore adoption3c12d2a

line 197why, one step back
197 name = strings.ReplaceAll(name, "·", ".")

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 198–204why, one step back
198 return name
199}200201// timeFormat returns a customized time string for logger.202func timeFormat(t time.Time) string {203 return t.Format("2006/01/02 - 15:04:05")204}