gpt4 book ai didi

http - 在不退出程序 golang 的情况下停止服务器

转载 作者:数据小太阳 更新时间:2023-10-29 03:11:10 26 4
gpt4 key购买 nike

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

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

最佳答案

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

时主线程变得畅通无阻

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

可运行的简化示例显示了这一点:

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

关于http - 在不退出程序 golang 的情况下停止服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51468060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com