dthh5038 2018-07-22 18:25
浏览 548
已采纳

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

I am using golang to run a simple server on http://localhost:8080. I need a way to stop the server and restart a different server when a user accesses http://localhost:8080/winrestart. So far I have this:

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()
}

As of now, the server closes and the program exits, but no new server is started. Is there a way this can be done?

  • 写回答

1条回答 默认 最新

  • dongren4758 2018-07-23 10:33
    关注

    The problem here is that the main thread becomes unblocked when you call server.Close()

    The main thread starts the server on it's very last line: server.ListenAndServe() but when the /winrestart/ handler method gets called; this handler method calls server.Close(), which stops the server, and the original blocking call to server.ListenAndServe() becomes unblocked. The main goroutine exits, and the program exits.

    Runnable, simplified example showing this:

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。