英文:
Stop Echo server on api call in golang
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对Golang和Echo框架还不熟悉。我使用下面的代码启动了一个服务器,并希望在API请求/stopServer
时停止服务器。由于在API请求中找不到相关信息,我在Google上感到困惑。我只能看到如何在终端中停止服务器的方法。如果有任何指导,我将不胜感激。
func stopServer(c echo.Context) error {
//我不确定这里应该写什么代码
}
func main() {
// 创建 Echo 实例
e := echo.New()
e.GET("/stopServer", stopServer)
// 启动服务器
e.Logger.Fatal(e.Start(":1323"))
}
我还想在http://localhost:1323/stopServer
上打印消息"服务器成功停止"
。
英文:
I am new to Golang and Echo framework. I have started a server using code as shown below and want to stop the server on an API hit which is /stopServer
. Google making me more confused as I am not able to find this on the API hit. All I am able to see is stopping server on terminal interrupt. Any pointers would be appreciable.
func stopServer(c echo.Context) error {
//Some code which I am not sure about
}
func main() {
// Echo instance
e := echo.New()
e.GET("/stopServer", stopServer)
// Start server
e.Logger.Fatal(e.Start(":1323"))
}
I would also like to print the message on http://localhost:1323/stopServer
saying "Server stopped successfully"
答案1
得分: 3
你可以按照优雅关闭服务器的代码示例进行操作。
并参考以下代码片段:
package main
import (
"context"
"github.com/labstack/echo/v4"
"net/http"
)
func stopServer(c echo.Context) error {
err := c.Echo().Shutdown(context.Background())
if err != nil {
if err != http.ErrServerClosed {
c.Echo().Logger.Fatal("关闭服务器时出错")
}
}
return nil
}
func main() {
e := echo.New()
e.GET("/stopServer", stopServer)
e.Logger.Fatal(e.Start(":1323"))
}
然而,这将立即关闭 echo 服务器,并向客户端返回 "ERR_CONNECTION_REFUSED"。
英文:
You can follow the Graceful Shutdown Recipe source code.
and refer following code snippet
package main
import (
"context"
"github.com/labstack/echo/v4"
"net/http"
)
func stopServer(c echo.Context) error {
err := c.Echo().Shutdown(context.Background())
if err != nil {
if err != http.ErrServerClosed {
c.Echo().Logger.Fatal("shutting down the server")
}
}
return nil
}
func main() {
e := echo.New()
e.GET("/stopServer", stopServer)
e.Logger.Fatal(e.Start(":1323"))
}
However this will immediately shutdown the echo server and "ERR_CONNECTION_REFUSED" returned to the client.
答案2
得分: 0
关于err := c.Echo().Shutdown(context.Background())
的答案是正确的。我唯一可以补充的是使用recover()
来替代应用程序的恐慌。类似这样:
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("host finished")
}
}()
e := echo.New()
e.GET("/stopServer", stopServer)
e.Logger.Fatal(e.Start(":1323"))
}
英文:
the answer about err := c.Echo().Shutdown(context.Background())
is correct. The only thing that I could add is a recover()
instead of the application panic. Something like this:
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("host finished")
}
}()
e := echo.New()
e.GET("/stopServer", stopServer)
e.Logger.Fatal(e.Start(":1323"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论