How to implement graceful shutdown
Take a look at app.Shutdown: https://github.com/gofiber/fiber/blob/5d8e5339464fdbddc46db44534e9e00446adc3cc/app.go#L550
To add to this - if you would like to implement a graceful shutdown that is triggered by an interrupt signal, you could do something like the following:
package main
import (
"log"
"fmt"
"github.com/gofiber/fiber/v2"
"os"
"os/signal"
)
func main() {
app := fiber.New()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
_ = <-c
fmt.Println("Gracefully shutting down...")
_ = app.Shutdown()
}()
// ...
if err := app.Listen(":3000"); err != nil {
log.Panic(err)
}
fmt.Println("Running cleanup tasks...")
// Your cleanup tasks go here
}
Output
K: via ๐น v1.15.2 took 1m29s
โฏ go run .\main.go
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Fiber v2.0.6 โ
โ http://127.0.0.1:3000 โ
โ โ
โ Handlers ............. 0 Threads ............. 8 โ
โ Prefork ....... Disabled PID ............. 18672 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
^CGracefully shutting down...
Running cleanup tasks...
If you need any more help, feel free to re-open.
@codemicro Can we add this to recipes, what do you think?
@frederikhors that sounds like a great idea! I'll submit a pull request today, unless you want to?
@frederikhors that sounds like a great idea! I'll submit a pull request today, unless you want to?
I do not have time right now.
No worries! I'll do it.
I do not understand with your code how to change Shutdown timeout. Is there a way or I have to use custom code for this?
I think this code is not working, @codemicro.
I cannot get fmt.Println("Gracefully shutting down...") printed for example.
It works. My fault.
The only problem is timeout now.
This example has no shutdown timeout - as soon as an interrupt is received, app.Shutdown is called.
It's briefly explained here.
Ok. I was talking about something like this: https://github.com/go-chi/chi/tree/master/_examples/graceful.
Thanks again!
Most helpful comment
To add to this - if you would like to implement a graceful shutdown that is triggered by an interrupt signal, you could do something like the following:
Output