停止服务器而不退出程序golang

时间:2018-07-22 18:25:51

标签: http go

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

到目前为止,服务器关闭并且程序退出,但是没有新的服务器启动。有办法可以做到吗?

1 个答案:

答案 0 :(得分:1)

这里的问题是,当您调用server.Close()

时,主线程会被解除阻塞

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

可运行的简化示例,显示以下内容:

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

相关问题