Home >Backend Development >Golang >How Does Go's `net/http` Server Handle Static File Serving Without a Fixed Root Directory?
Unveiling the "Root" Directory in Go's Web Server
In Go's net/http web server, the concept of a fixed "root" directory for serving files is absent. Instead, handlers are utilized to respond to URL requests, providing more flexibility and control over content delivery.
Handler Mapping
A handler is a function that processes an HTTP request and generates the corresponding response. URLs are associated with handlers using the Handle() or HandleFunc() functions. When an HTTP request is received, the server matches the requested URL with the registered handlers to determine which handler should handle the request.
Static Files
For serving static files, Go provides a FileServer() function. It returns a handler that serves files from a specified "root" directory. This directory can be specified as an absolute or relative path.
Absolute Paths
If an absolute path is used with FileServer(), the "root" directory is unambiguous.
Relative Paths
Relative paths, however, depend on the current working directory, which is normally the directory from which the application was started. For instance:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
This assigns a handler to serve files from the "/tmp" directory, mapped to the root URL "/". Hence, the response to "/mydoc.txt" will be the file "/tmp/mydoc.txt".
Complex Mapping
More complex mapping scenarios can be achieved with the StripPrefix() function, which modifies the request URL path before it's passed to FileServer(). This enables serving files from a different directory or path than the root URL.
Example:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
This setup serves files from "/tmp" under the URL path "/tmpfiles/"; a request for "/tmpfiles/mydoc.txt" will respond with the file "/tmp/mydoc.txt".
The above is the detailed content of How Does Go's `net/http` Server Handle Static File Serving Without a Fixed Root Directory?. For more information, please follow other related articles on the PHP Chinese website!