Home >Backend Development >Golang >How to Remove the .html Extension from URLs in a Go HTTP Server?
Remove .html Extension from Files in an HTTP Server
Many HTTP servers automatically add a ".html" extension to the end of URLs, which can be undesirable in some cases. To modify this behavior in a Go HTTP server, you can implement a custom http.FileSystem using http.Dir. Here's how:
<code class="go">type HTMLDir struct { d http.Dir }</code>
The Open method determines how files should be opened. Depending on your requirements, you have several options:
Always append ".html" extension:
<code class="go">func (d HTMLDir) Open(name string) (http.File, error) { return d.d.Open(name + ".html") }</code>
Fallback to ".html" extension:
<code class="go">func (d HTMLDir) Open(name string) (http.File, error) { // Try name as supplied f, err := d.d.Open(name) if os.IsNotExist(err) { // Not found, try with .html if f, err := d.d.Open(name + ".html"); err == nil { return f, nil } } return f, err }</code>
Start with ".html" extension and fallback:
<code class="go">func (d HTMLDir) Open(name string) (http.File, error) { // Try name with added extension f, err := d.d.Open(name + ".html") if os.IsNotExist(err) { // Not found, try again with name as supplied. if f, err := d.d.Open(name); err == nil { return f, nil } } return f, err }</code>
<code class="go">fs := http.FileServer(HTMLDir{http.Dir("public/")}) http.Handle("/", http.StripPrefix("/", fs))</code>
By implementing http.FileSystem and customizing the Open method, you can control how files are served by your HTTP server, including the behavior around ".html" extensions.
The above is the detailed content of How to Remove the .html Extension from URLs in a Go HTTP Server?. For more information, please follow other related articles on the PHP Chinese website!