How do I dynamically change static files directory of the http server?

Viewed 127

I have the following piece of code, that serves static files from a static files directory (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))
}

This directory changes from time to time, and currently I always need to restart the server process to use the new value.

How can I reconfigure/reload the FileServer without restarting the whole process?

Additional complication to that: other handlers of the http server are executing long-running jobs (incl. child processes etc.), that I would like to keep untouched during this reload.

What is the standard solution of this quite typical task?

1 Answers

You can add a level of indirection in between:

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)
}
Related