Home > Backend Development > Golang > How Do I Specify the Root Directory for a Go Web Server's Static Files?

How Do I Specify the Root Directory for a Go Web Server's Static Files?

Barbara Streisand
Release: 2024-12-17 05:43:26
Original
372 people have browsed it

How Do I Specify the Root Directory for a Go Web Server's Static Files?

Where Can I Find the Root Directory of a Go Webserver?

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.

Static File Serving

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).

Example (Absolute Path):

http.Handle("/", http.FileServer(http.Dir("/tmp")))

This handles all requests to the root URL ("/") and serves files from the "/tmp" directory.

Example (Relative Path):

http.Handle("/", http.FileServer(http.Dir("./myfiles")))

Here, files are served from the "./myfiles" directory relative to the current working directory.

Stripping Prefixes for Complex Mapping:

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"))))
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template