接收参数后如何安全关闭golang服务-最佳做法

时间:2019-05-04 07:15:40

标签: 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")

}

谢谢..!

1 个答案:

答案 0 :(得分:1)

从引用的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)
}()

查看idleConnsClosed设置/清理的完整游乐场版本:https://play.golang.org/p/UBmLfyhKT0B


P.S。除非您确实希望用户不要再使用源URL,否则不要使用http.StatusMovedPermanently。用户的浏览器将缓存此(301)代码-不会访问您的服务器-可能不是您想要的。如果要临时重定向,请使用http.StatusSeeOther(代码303)。

相关问题