mirror of
https://github.com/kataras/iris.git
synced 2025-12-28 07:17:06 +00:00
Version 3.0.0-beta cleaned
This commit is contained in:
30
middleware/recovery/README.md
Normal file
30
middleware/recovery/README.md
Normal file
@@ -0,0 +1,30 @@
|
||||
## Middleware information
|
||||
|
||||
This folder contains a middleware for safety recover the server from panic
|
||||
|
||||
## How to use
|
||||
|
||||
```go
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/middleware/recovery"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
iris.Use(recovery.New(os.Stderr)) // optional parameter is the writer which the stack of the panic will be printed
|
||||
|
||||
iris.Get("/", func(ctx *iris.Context) {
|
||||
ctx.Write("Hi, let's panic")
|
||||
panic("errorrrrrrrrrrrrrrr")
|
||||
})
|
||||
|
||||
println("Server is running at :8080")
|
||||
iris.Listen(":8080")
|
||||
}
|
||||
|
||||
```
|
||||
45
middleware/recovery/recovery.go
Normal file
45
middleware/recovery/recovery.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package recovery
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
type recovery struct {
|
||||
//out optional output to log any panics
|
||||
out io.Writer
|
||||
}
|
||||
|
||||
func (r recovery) Serve(ctx *iris.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
r.out.Write([]byte("[" + time.Now().String() + "]Recovery from panic \n"))
|
||||
//ctx.Panic just sends http status 500 by default, but you can change it by: iris.OnPanic(func( c *iris.Context){})
|
||||
ctx.Panic()
|
||||
}
|
||||
}()
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// Recovery restores the server on internal server errors (panics)
|
||||
// receives an optional writer, the default is the os.Stderr if no out writer given
|
||||
// returns the middleware as iris.Handler
|
||||
// same as New(...)
|
||||
func Recovery(out ...io.Writer) iris.Handler {
|
||||
r := recovery{os.Stderr}
|
||||
if out != nil && len(out) == 1 {
|
||||
r.out = out[0]
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// New restores the server on internal server errors (panics)
|
||||
// receives an optional writer, the default is the os.Stderr if no out writer given
|
||||
// returns the middleware as iris.Handler
|
||||
// same as Recovery(...)
|
||||
func New(out ...io.Writer) iris.Handler {
|
||||
return Recovery(out...)
|
||||
}
|
||||
Reference in New Issue
Block a user