The Go net/http package provides a web server but does not have a concept of a filesystem root. It utilizes handlers that map HTTP requests to URLs.
However, a static file server is available through the http package's FileServer() function. This function takes a root directory parameter, which can be absolute or relative to the current working directory (the folder where you execute your application).
http.Handle("/", http.FileServer(http.Dir("/tmp")))
This handles all requests to the root URL ("/") and serves files from the "/tmp" directory.
http.Handle("/", http.FileServer(http.Dir("./myfiles")))
Here, files are served from the "./myfiles" directory relative to the current working directory.
You can employ the StripPrefix() function for more advanced routing. For instance:
http.Handle("/tmpfiles/",</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
This serves files from "/tmp" but under the URL "/tmpfiles/".
The above is the detailed content of How Do I Specify the Root Directory for a Go Web Server's Static Files?. For more information, please follow other related articles on the PHP Chinese website!