dongleiwei2182
2019-05-04 07:15 阅读 98
已采纳

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

I have been implementing server using golang. I need to shutdown my server after receiving the expected parameter 'code'. Before shutting down the sever I need to redirect to a another web page. I have implemented as give below. This code is working. I need to know whether it is the best way of doing it ? Your suggestions are appreciated..

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")

}

Thank you ..!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dougou6727 dougou6727 2019-05-04 15:49

    Taking @Peter flushing suggestion and ideas from the example cited 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)
    }()
    

    See full playground version for idleConnsClosed setup/cleanup: https://play.golang.org/p/UBmLfyhKT0B


    P.S. Don't use http.StatusMovedPermanently unless you really want users never to use the source URL again. Users' browsers will cache this (301) code - and not hit your server - which may not be what you want. If you want temporary redirects use http.StatusSeeOther (code 303).

    点赞 评论 复制链接分享

相关推荐