How to Conceal File Extensions in a Simple HTTP Server
Many web servers display file extensions in the URL, which can be undesirable for aesthetic or user-experience reasons. This guide demonstrates how to conceal the .html extension from URLs in a Go HTTP server.
Solution
Implement http.FileSystem using http.Dir offers several benefits, including leveraging the robust code within http.FileServer. A custom HTMLDir struct can be created to implement this functionality.
Implementation
The implementation of Open depends on the desired behavior. Three scenarios are presented below:
Option 1: Always Append .html
<code class="go">func (d HTMLDir) Open(name string) (http.File, error) { return d.d.Open(name + ".html") }</code>
Option 2: Fallback to .html
<code class="go">func (d HTMLDir) Open(name string) (http.File, error) { f, err := d.d.Open(name) if os.IsNotExist(err) { if f, err := d.d.Open(name + ".html"); err == nil { return f, nil } } return f, err }</code>
Option 3: Start with .html and Fallback
<code class="go">func (d HTMLDir) Open(name string) (http.File, error) { f, err := d.d.Open(name + ".html") if os.IsNotExist(err) { if f, err := d.d.Open(name); err == nil { return f, nil } } return f, err }</code>
By using HTMLDir with http.StripPrefix, the .html extension can be effectively concealed when serving files from the specified directory. This technique provides a more seamless and aesthetically pleasing user experience, while still allowing access to the intended content.
The above is the detailed content of How to Hide HTML File Extensions from URLs in a Go HTTP Server?. For more information, please follow other related articles on the PHP Chinese website!