【问题标题】:stop server without exiting program golang停止服务器而不退出程序 golang
【发布时间】:2018-07-22 18:25:51
【问题描述】:

我正在使用 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()
}

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

【问题讨论】:

标签: http go


【解决方案1】:

这里的问题是当你调用server.Close()时主线程变得畅通了

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

可运行的简化示例:

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

【讨论】:

    猜你喜欢
    • 2013-01-28
    • 2015-12-21
    • 1970-01-01
    • 2018-01-20
    • 2017-08-05
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    相关资源
    最近更新 更多