登录
首页 >  Golang >  Go问答

如何在Golang中安全停止服务器

来源:stackoverflow

时间:2024-03-10 09:57:26 253浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《如何在Golang中安全停止服务器》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我正在使用 golang 在 http://localhost:8080 上运行一个简单的服务器。当用户访问 http://localhost:8080/winrestart 时,我需要一种方法来停止服务器并重新启动不同的服务器。到目前为止我有这个:

package main


import (
  "net/http" //serving files and stuff
  "log"      //logging that the server is running and other stuff
  "fmt"      //"congrats on winning!"
)


func main() {

  //servemux
  srvmx := http.NewServeMux()

  //handlers that serve the home html file when called
  fs := http.FileServer(http.Dir("./home/"))
  os := http.FileServer(http.Dir("./lvlone/"))
  ws := http.FileServer(http.Dir("./win/"))

  //creates custom server
  server := http.Server {
    Addr: ":8080",
    Handler: srvmx,
  }

  //handles paths by serving correct files
  srvmx.Handle("/", fs)
  srvmx.Handle("/lvlione/", http.StripPrefix("/lvlione/", os))
  srvmx.Handle("/win/", http.StripPrefix("/win/", ws))
  srvmx.HandleFunc("/winrestart/", func(w http.ResponseWriter, r *http.Request){
    fmt.Println("server is being closed")

    //creates new servemux
    wsm := http.NewServeMux()

    //this handler just redirects people to the beggining
    rh := http.RedirectHandler("http://127.0.0.1:8080/", 308)

    //create new redirect server
    redirector := http.Server {
      Addr: ":8080",
      Handler: wsm,
    }

    //Handle all paths by redirecting
    wsm.Handle("/lvlione/", rh)
    wsm.Handle("/win/", rh)
    wsm.Handle("/winrestart/", rh)

    //logs redirect server is Listening
    log.Println("redirecting...")
    server.Close()
    redirector.ListenAndServe()
  })

  //logs that server is Listening
  log.Println("Listening...")
  //starts normal level server
  server.ListenAndServe()
}

截至目前,服务器关闭,程序退出,但没有启动新的服务器。有办法做到这一点吗?


解决方案


这里的问题是,当你调用server.Close()时,主线程变得解锁

主线程在最后一行启动服务器:server.ListenAndServe(),但是当 /winrestart/ 处理程序方法被调用时;此处理程序方法调用 server.Close(),这会停止服务器,并且对 server.ListenAndServe() 的原始阻塞调用将变为解除阻塞。主协程退出,程序退出。

可运行的简化示例显示了这一点:

https://play.golang.org/p/RM1uNASBaC1

终于介绍完啦!小伙伴们,这篇关于《如何在Golang中安全停止服务器》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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