登录
首页 >  Golang >  Go问答

安全关闭 golang 服务的最佳实践 - 参数接收与实现

来源:stackoverflow

时间:2024-03-23 17:30:30 403浏览 收藏

在 Go 中实现服务器时,在接收特定参数后安全关闭服务器至关重要。文章讨论了通过 HTTP 服务器实现这一目标的最佳实践,包括参数解析、重定向和服务器关闭的步骤。代码示例演示了如何使用 `http.Server.Shutdown` 方法和 `http.Flusher` 接口确保客户端收到所有响应,从而避免数据丢失。

问题内容

我一直在使用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")

}

谢谢你..!


解决方案


here 引用的示例中获取 @peter 冲洗建议和想法:

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)
}()

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

附注不要使用 http.statusmovedpermanently 除非您确实希望用户不再使用源 url。用户的浏览器将缓存此 (301) 代码 - 并且不会访问您的服务器 - 这可能不是您想要的。如果您想要临时重定向,请使用 http.statusseeother(代码 303)。

今天关于《安全关闭 golang 服务的最佳实践 - 参数接收与实现》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>