This is a creation in Article, where the information may have evolved or changed.
I. keeping the code clean and properly diverted
http. One of the functions of the Stripprefix function is to filter the specific prefix from the URL before directing the request to the request processing point specified by the parameter. Here is an example of a browser or HTTP client requesting a resource:
/static/example.txt
The Stripprefix function will filter out the/static/and direct the modified request to HTTP. Fileserver the returned handler, so the requested resource will be:
/example.txt
http. The handler returned by Fileserver will be looked up and the contents related to the folder or file system will be returned to you as a parameter (here you will "static" as the root directory of the static file). Because your "example.txt" file is in a static directory, you must define a relative path to get the correct file path.
Two. customize access paths as needed
The following example can be found in the HTTP package documentation:
// To serve a directory on disk (/tmp) under an alternate URL// path (/tmpfiles/), use StripPrefix to modify the request// URL's path before the FileServer sees it:http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
Fileserver has defined the root directory of the static file in "/tmp", but we want the URL to start with "/tmpfiles/". If someone requests "/tempfiles/example.txt", we want the server to send the file to him. To achieve this, we must filter out "/tmpfiles" from the URL, while the remaining path is relative to the root directory "/tmp". If we follow the above approach, we will get the following results:
/tmp/example.txt