【发布时间】: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()
}
截至目前,服务器关闭,程序退出,但没有启动新服务器。有没有办法做到这一点?
【问题讨论】:
-
这里已经回答了这个问题:stackoverflow.com/questions/39320025/…
-
已经有可以优雅重启的包,比如facebookgo/grace。不要重新发明轮子。
-
@MichaelHampton like this? 如果 OP 是从 Go 开始的,那么为了自己的缘故重新发明一切可能会很有用。
-
@ShrimpPhaser 我尝试使用关闭功能,但它关闭了程序