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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。