mirror of
https://github.com/kataras/iris.git
synced 2026-01-10 21:45:57 +00:00
Add iris#ConfigureHost as an alternative way to interact with the app's hosts.
Former-commit-id: 5f36f44b86b70818c4c0c6ef7c178b550cc4ac46
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
A silly example for this issue: https://github.com/kataras/iris/issues/688#issuecomment-318828259.
|
||||
However it seems useful and therefore is being included in the examples for everyone else.
|
||||
@@ -0,0 +1,32 @@
|
||||
package counter
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/context"
|
||||
"github.com/kataras/iris/core/host"
|
||||
)
|
||||
|
||||
func Configurator(app *iris.Application) {
|
||||
counterValue := 0
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
|
||||
for range ticker.C {
|
||||
counterValue++
|
||||
}
|
||||
|
||||
app.ConfigureHost(func(h *host.Supervisor) { // <- HERE: IMPORTANT
|
||||
h.RegisterOnShutdown(func() {
|
||||
ticker.Stop()
|
||||
})
|
||||
}) // or put the ticker outside of the gofunc and put the configurator before or after the app.Get, outside of this gofunc
|
||||
}()
|
||||
|
||||
app.Get("/counter", func(ctx context.Context) {
|
||||
ctx.Header("Content-Type", "text/plain")
|
||||
ctx.Writef("Counter value = %d", counterValue)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/kataras/iris/_examples/http-listening/iris-configurator-and-host-configurator/counter"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
app.Configure(counter.Configurator)
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
@@ -16,6 +16,8 @@ func main() {
|
||||
ctx.HTML("<h1>Hello, try to refresh the page after ~10 secs</h1>")
|
||||
})
|
||||
|
||||
// app.ConfigureHost(configureHost) -> or pass "configureHost" as `app.Addr` argument, same result.
|
||||
|
||||
app.Logger().Info("Wait 10 seconds and check your terminal again")
|
||||
// simulate a shutdown action here...
|
||||
go func() {
|
||||
@@ -40,9 +42,9 @@ func main() {
|
||||
|
||||
func configureHost(su *host.Supervisor) {
|
||||
// here we have full access to the host that will be created
|
||||
// inside the `Run` function.
|
||||
// inside the `app.Run` function or `NewHost`.
|
||||
//
|
||||
// we register a shutdown "event" callback
|
||||
// we're registering a shutdown "event" callback here:
|
||||
su.RegisterOnShutdown(func() {
|
||||
println("server is closed")
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user