http - 如何动态更改http服务器的静态文件目录?

标签 http go

我有以下代码,用于从静态文件目录 (staticFilesDir) 提供静态文件:

for _, prefix := range []string{"css", "img", "js", "static"} {
    prefix = "/" + prefix + "/"
    fs := http.FileServer(http.Dir(staticFilesDir + prefix))
    r.PathPrefix(prefix).Handler(http.StripPrefix(prefix, fs))
}

这个目录会不时发生变化,目前我总是需要重新启动服务器进程才能使用新值。

如何在不重新启动整个过程的情况下重新配置/重新加载FileServer

额外的复杂性:http 服务器的其他处理程序正在执行长时间运行的作业(包括子进程等),我希望在重新加载期间保持不变。

这个非常典型的任务的标准解决方案是什么?

最佳答案

您可以在两者之间添加间接级别:

type MyFileServer struct {
   sync.RWMutex
   http.FileServer
}

func (f *MyFileServer) SetDir(dir string) {
    f.Lock()
    defer f.Unlock()
    f.FileServer=http.FileServer(dir)
}


func (f *MyFileServer) ServeHTTP(w http.ResponseWriter,req *http.Request) {
   f.RLock()
   defer f.RUnlock()
   f.FileServer.ServeHTTP(w,req)
}

关于http - 如何动态更改http服务器的静态文件目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68732197/

相关文章:

arrays - 如何将 []string 转换为 ...string

javascript - 将现有的 http 请求从 javascript 转换为 java

rest - gRPC(HTTP/2) 是否比使用 HTTP/2 的 REST 更快?

sql - 为什么 Cassandra 在插入重复记录时不会报错?

go - 无法加载 github.com/open-policy-agent/opa/capability : no Go source files

http - Golang 在服务器运行时获得 404

validation - 带有 Jersey 实现的 JAX-RS 中 POST 申请的 Bean 验证

html - 为什么 IE8 会忽略第一个样式表?

unit-testing - 如何为一小时后函数返回时间编写单元测试

go - 对字符串进行简单的 mapReduce 操作