dqhdz04240 2018-12-11 22:44 采纳率: 0%
浏览 51

Golang net / http服务器处理程序热重载

Is it possible to change the http Server's Handler struct field whilst the Server is running? I have a dynamic list of routes which can change throughout the lifetime of the server, but want to avoid any downtime.

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
}
  • 写回答

1条回答 默认 最新

  • 一抹惜鱼 2021-07-22 14:21
    关注

    你这个代码,想切换端口就不能用了;

    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示