go - 如何在收到参数后安全关闭 golang 服务 - 最佳实践

标签 go service parameters shutdown

我一直在使用 golang 实现服务器。在收到预期的参数“代码”后,我需要关闭我的服务器。在关闭服务器之前,我需要重定向到另一个网页。我已经实现如下。此代码正在运行。我需要知道这是否是最好的方法?感谢您的建议..

func main() {
    var code string
    const port  int = 8888
    httpPortString := ":" + strconv.Itoa(port)
    mux := http.NewServeMux()
    fmt.Printf("Http Server initialized on Port %s", httpPortString)
    server := http.Server{Addr: httpPortString, Handler: mux}
    var timer *time.Timer
    mux.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
        err := r.ParseForm()
        if err != nil {
            fmt.Printf("Error parsing the code: %s", err)
        }
        code = r.Form.Get("code")
        if err != nil {
            log.Printf("Error occurred while establishing the server: %s", err)
        }
        http.Redirect(w, r, "https://cloud.google.com/sdk/auth_success", http.StatusMovedPermanently)

        timer = time.NewTimer(2 * time.Second)
        go func() {
            <-timer.C
            server.Shutdown(context.Background())
        }()
    })
    if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
        fmt.Printf("Error while establishing the service: %s", err)
    }
    fmt.Println("Finished executing the the service")

}

谢谢你..!

最佳答案

从引用的例子中吸取@Peter flushing 的建议和想法here :

f, ok := w.(http.Flusher)
if !ok {
    http.Error(w, "no flush support", http.StatusInternalServerError)
    return
}   

http.Redirect(w, r, "https://cloud.google.com/sdk/auth_success", http.StatusSeeOther)

f.Flush() // <-- ensures client gets all writes
          // this is done implicitly on http handler returns, but...
          // we're shutting down the server now!

go func() {
    server.Shutdown(context.Background())
    close(idleConnsClosed)
}()

查看idleConnsClo​​sed设置/清理的完整 Playground 版本:https://play.golang.org/p/UBmLfyhKT0B


附言不要使用 http.StatusMovedPermanently 除非您真的希望用户永远不再使用源 URL。用户的浏览器将缓存此 (301) 代码 - 而不会访问您的服务器 - 这可能不是您想要的。如果您想要临时重定向,请使用 http.StatusSeeOther(代码 303)。

关于go - 如何在收到参数后安全关闭 golang 服务 - 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55980396/

相关文章:

regex - 负面回顾替代方案

c++ - 我的 native Win32 服务是否需要单独的消息文件库?

Java TestNG 在@DataProvider 中使用@Parameters 调用方法

java - 我需要通过参数仅传递类的几个属性之一

go - 如何使用 Godep 将我的 Go 应用程序部署到 heroku?

go - DefaultHandler 是结构的 (*DefaultHandler)(nil) 是什么意思?

.net - 在 IIS 中托管 .NET 服务(无接口(interface))

java - Java函数参数总是按值传递吗?

go - 在方法或构造函数级别进行 Nil 处理?

Android 服务在更新时自行终止,但按钮/复选框等小部件保持不变