是否可以在服务器运行时更改 http 服务器的 Handler 结构字段?我有一个动态的路由列表,可以在服务器的整个生命周期内更改,但希望避免任何停机时间。
package main
import (
"log"
"net/http"
"time"
)
func main() {
// construct the handler for the first time
handler, err := constructHandler()
if err != nil {
return nil, err
}
// create the server
s := &http.Server{
Addr: ":80",
Handler: handler,
}
// start the server in on a separate goroutine.
go func() {
if err := s.ListenAndServe(); err != nil {
log.Fatalf("unable to start http server: %v", err)
}
}()
// recreate and hot-reload the handler every 30 seconds
for range time.Tick(30 * time.Second) {
handler, err = constructHandler()
if err != nil {
log.Printf("cannot reload: unable to construct handler: %v", err)
continue
}
// only hot-reload the handler if there wasn't an error
s.Handler = handler
}
}
func constructHandler() (handler http.Handler, err error) {
// handler gets created.
// this could involve making calls to a database.
// ...
return handler, err
}