在服务器运行时是否可以更改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
}