Reputation: 45
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?
Upvotes: 1
Views: 3327
Reputation: 5898
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
Upvotes: 1