Remove the .html Extension Using a Custom File System
To avoid displaying the .html extension in URLs, one approach is to implement the http.FileSystem interface using http.Dir. This solution leverages the robust code in http.FileServer.
To implement this, create a custom type that embeds http.Dir:
<code class="go">type HTMLDir struct { d http.Dir }</code>
Modify the main function to use this custom file system instead of http.FileServer:
<code class="go">func main() { fs := http.FileServer(HTMLDir{http.Dir("public/")}) http.Handle("/", http.StripPrefix("/", fs)) http.ListenAndServe(":8000", nil) }</code>
Next, define the Open method for the HTMLDir type. This method determines how the file system should handle file requests.
Always Tacking on the .html Extension:
<code class="go">func (d HTMLDir) Open(name string) (http.File, error) { return d.d.Open(name + ".html") }</code>
Fallback to the .html Extension:
<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>
Fallback to the File Name (Without Extension):
<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 implementing the above solutions, you can effectively remove the .html extension from URLs when accessing your Go HTTP server.
The above is the detailed content of How to Remove the .html Extension from URLs in Your Go HTTP Server?. For more information, please follow other related articles on the PHP Chinese website!