lesismal / nbio

Pure Go 1000k+ connections solution, support tls/http1.x/websocket and basically compatible with net/http, with high-performance and low memory cost, non-blocking, event-driven, easy-to-use.
MIT License
2.23k stars 155 forks source link

I intentionally wrote a panic handler, but the request never returned. Is this a bug? #452

Closed sunvim closed 1 week ago

sunvim commented 1 week ago

as the title said, the code is [blow: 1 2

lesismal commented 1 week ago

It's not a bug. nbio is designed at the basic level as net/http.

When we try this:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "hello")
    })
    http.HandleFunc("/panic", func(w http.ResponseWriter, req *http.Request) {
        panic(nil)
    })

    http.ListenAndServe(":8080", nil)
}

We also can't get the response because of the panic.

But when we use some other frameworks, such as gin:

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/hello", func(c *gin.Context) {
        c.String(200, "hello")
    })
    r.GET("/panic", func(c *gin.Context) {
        panic(nil)
    })
    r.Run(":8080")
}

We get 500 Internal Server Error

Whatever, the best way is to use recover middleware.