When developing web servers, it's often desirable to remove the .html extension from file names to provide a cleaner and more user-friendly URL experience.
In a Go HTTP server, this can be achieved by implementing the http.FileSystem interface and registering it as a custom handler. The following code demonstrates how to do this:
<code class="go">package main import ( "net/http" "os" ) type HTMLDir struct { d http.Dir } func main() { fs := http.FileServer(HTMLDir{http.Dir("public/")}) http.Handle("/", http.StripPrefix("/", fs)) http.ListenAndServe(":8000", nil) } func (d HTMLDir) Open(name string) (http.File, error) { f, err := d.d.Open(name + ".html") if os.IsNotExist(err) { // Not found, try with .html if f, err := d.d.Open(name); err == nil { return f, nil } } return f, err }</code>
This custom file system, HTMLDir, overrides the Open method to search for files with and without the .html extension. When a request for a file is made, the server will first try to open the file with the .html extension. If not found, it will then try to open the file without the extension.
By implementing the custom file system and registering it as a handler, you can effectively remove the .html extension from file names while still providing access to the desired content.
The above is the detailed content of How to Strip the .html Extension from File Names in a Go HTTP Server?. For more information, please follow other related articles on the PHP Chinese website!