Go http. Stripprefix for use in file server

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.