Skip to content

Commit

Permalink
🔥 Feature: add ability to print custom message on startup (#2491)
Browse files Browse the repository at this point in the history
* feat: add a variadic parameter on OnListenHandler

* feat: accept a variadic ListenData in startupProcess parameters

* feat: add startupProcess variadic ListenData to function

* refactor: use runOnListenHooks instead of startupProcess for run onListenHooks

* refactor: remove variadic to make codes straightforward

* fix: add listen data to runOnListenHooks

* test: add listenData parameter to OnListen tests

* docs: update OnListen docs

* fix: remove unused codes

* docs: add tabs to onListen hook example

* docs: add if statement to docs example

* docs: replace fmt with log

* docs: fix return value of example

* docs: make 0.0.0.0 string a constant

* fix: change type of TLS from string to bool

* fix: return bool instead of a string

* docs: update example with new TLS type

* fix: change name tls to isTls to prevent shadowing tls variable

* style: make syntax of onListen example shorter

* refactor: remove unused no-lint comment

* refactor: change isTls to isTLS

* fix: add nolint for isTLS bool param

* Update listen.go

---------

Co-authored-by: M. Efe Çetin <efectn@protonmail.com>
  • Loading branch information
Saman-Safaei and efectn committed Jun 19, 2023
1 parent 3dc9e1d commit ed95fa8
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 19 deletions.
4 changes: 2 additions & 2 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -1104,8 +1104,8 @@ func (app *App) startupProcess() *App {
}

// Run onListen hooks. If they return an error, panic.
func (app *App) runOnListenHooks() {
if err := app.hooks.executeOnListenHooks(); err != nil {
func (app *App) runOnListenHooks(listenData ListenData) {
if err := app.hooks.executeOnListenHooks(listenData); err != nil {
panic(err)
}
}
27 changes: 25 additions & 2 deletions docs/guide/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ type OnRouteHandler = func(Route) error
type OnNameHandler = OnRouteHandler
type OnGroupHandler = func(Group) error
type OnGroupNameHandler = OnGroupHandler
type OnListenHandler = func() error
type OnListenHandler = func(ListenData) error
type OnForkHandler = func(int) error
type OnShutdownHandler = OnListenHandler
type OnShutdownHandler = func() error
type OnMountHandler = func(*App) error
```

Expand Down Expand Up @@ -127,6 +127,29 @@ OnListen is a hook to execute user functions on Listen, ListenTLS, Listener.
func (app *App) OnListen(handler ...OnListenHandler)
```

<Tabs>
<TabItem value="onlisten-example" label="OnListen Example">

```go
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
})

app.Hooks().OnListen(func(listenData fiber.ListenData) error {
if fiber.IsChild() {
return nil
}
scheme := "http"
if data.TLS {
scheme = "https"
}
log.Println(scheme + "://" + listenData.Host + ":" + listenData.Port)
return nil
})

app.Listen(":5000")
```

## OnFork

OnFork is a hook to execute user functions on Fork.
Expand Down
15 changes: 11 additions & 4 deletions hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ type (
OnNameHandler = OnRouteHandler
OnGroupHandler = func(Group) error
OnGroupNameHandler = OnGroupHandler
OnListenHandler = func() error
OnShutdownHandler = OnListenHandler
OnListenHandler = func(ListenData) error
OnShutdownHandler = func() error
OnForkHandler = func(int) error
OnMountHandler = func(*App) error
)
Expand All @@ -32,6 +32,13 @@ type Hooks struct {
onMount []OnMountHandler
}

// ListenData is a struct to use it with OnListenHandler
type ListenData struct {
Host string
Port string
TLS bool
}

func newHooks(app *App) *Hooks {
return &Hooks{
app: app,
Expand Down Expand Up @@ -174,9 +181,9 @@ func (h *Hooks) executeOnGroupNameHooks(group Group) error {
return nil
}

func (h *Hooks) executeOnListenHooks() error {
func (h *Hooks) executeOnListenHooks(listenData ListenData) error {
for _, v := range h.onListen {
if err := v(); err != nil {
if err := v(listenData); err != nil {
return err
}
}
Expand Down
4 changes: 2 additions & 2 deletions hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ func Test_Hook_OnListen(t *testing.T) {
buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)

app.Hooks().OnListen(func() error {
app.Hooks().OnListen(func(listenData ListenData) error {
_, err := buf.WriteString("ready")
utils.AssertEqual(t, nil, err)

Expand All @@ -234,7 +234,7 @@ func Test_Hook_OnListenPrefork(t *testing.T) {
buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)

app.Hooks().OnListen(func() error {
app.Hooks().OnListen(func(listenData ListenData) error {
_, err := buf.WriteString("ready")
utils.AssertEqual(t, nil, err)

Expand Down
38 changes: 30 additions & 8 deletions listen.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,17 @@ import (
"github.com/mattn/go-runewidth"
)

const (
globalIpv4Addr = "0.0.0.0"
)

// Listener can be used to pass a custom listener.
func (app *App) Listener(ln net.Listener) error {
// prepare the server for the start
app.startupProcess()

// run hooks
app.runOnListenHooks()
app.runOnListenHooks(app.prepareListenData(ln.Addr().String(), getTLSConfig(ln) != nil))

// Print startup message
if !app.config.DisableStartupMessage {
Expand Down Expand Up @@ -72,7 +76,7 @@ func (app *App) Listen(addr string) error {
app.startupProcess()

// run hooks
app.runOnListenHooks()
app.runOnListenHooks(app.prepareListenData(ln.Addr().String(), false))

// Print startup message
if !app.config.DisableStartupMessage {
Expand Down Expand Up @@ -137,7 +141,7 @@ func (app *App) ListenTLSWithCertificate(addr string, cert tls.Certificate) erro
app.startupProcess()

// run hooks
app.runOnListenHooks()
app.runOnListenHooks(app.prepareListenData(ln.Addr().String(), getTLSConfig(ln) != nil))

// Print startup message
if !app.config.DisableStartupMessage {
Expand Down Expand Up @@ -212,7 +216,7 @@ func (app *App) ListenMutualTLSWithCertificate(addr string, cert tls.Certificate
app.startupProcess()

// run hooks
app.runOnListenHooks()
app.runOnListenHooks(app.prepareListenData(ln.Addr().String(), getTLSConfig(ln) != nil))

// Print startup message
if !app.config.DisableStartupMessage {
Expand All @@ -231,8 +235,26 @@ func (app *App) ListenMutualTLSWithCertificate(addr string, cert tls.Certificate
return app.server.Serve(ln)
}

// prepareListenData create an slice of ListenData
func (app *App) prepareListenData(addr string, isTLS bool) ListenData { //revive:disable-line:flag-parameter // Accepting a bool param named isTLS if fine here
host, port := parseAddr(addr)
if host == "" {
if app.config.Network == NetworkTCP6 {
host = "[::1]"
} else {
host = globalIpv4Addr
}
}

return ListenData{
Host: host,
Port: port,
TLS: isTLS,
}
}

// startupMessage prepares the startup message with the handler number, port, address and other information
func (app *App) startupMessage(addr string, tls bool, pids string) { //nolint: revive // Accepting a bool param is fine here
func (app *App) startupMessage(addr string, isTLS bool, pids string) { //nolint: revive // Accepting a bool param named isTLS if fine here
// ignore child processes
if IsChild() {
return
Expand Down Expand Up @@ -294,12 +316,12 @@ func (app *App) startupMessage(addr string, tls bool, pids string) { //nolint: r
if app.config.Network == NetworkTCP6 {
host = "[::1]"
} else {
host = "0.0.0.0"
host = globalIpv4Addr
}
}

scheme := schemeHTTP
if tls {
if isTLS {
scheme = schemeHTTPS
}

Expand All @@ -320,7 +342,7 @@ func (app *App) startupMessage(addr string, tls bool, pids string) { //nolint: r
}
mainLogo += " │ " + centerValue("Fiber v"+Version, lineLen) + " │\n"

if host == "0.0.0.0" {
if host == globalIpv4Addr {
mainLogo += " │ " + center(fmt.Sprintf("%s://127.0.0.1:%s", scheme, port), lineLen) + " │\n" +
" │ " + center(fmt.Sprintf("(bound on host 0.0.0.0 and port %s)", port), lineLen) + " │\n"
} else {
Expand Down
2 changes: 1 addition & 1 deletion prefork.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func (app *App) prefork(network, addr string, tlsConfig *tls.Config) error {

// Run onListen hooks
// Hooks have to be run here as different as non-prefork mode due to they should run as child or master
app.runOnListenHooks()
app.runOnListenHooks(app.prepareListenData(addr, tlsConfig != nil))

// Print startup message
if !app.config.DisableStartupMessage {
Expand Down

1 comment on commit ed95fa8

@ReneWerner87
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 2.

Benchmark suite Current: ed95fa8 Previous: 35ea74a Ratio
Benchmark_TrimLeft/fiber 11.43 ns/op 0 B/op 0 allocs/op 3.638 ns/op 0 B/op 0 allocs/op 3.14

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.