Home  >  Article  >  Backend Development  >  How to Remove the .html Extension from URLs in Your Go HTTP Server?

How to Remove the .html Extension from URLs in Your Go HTTP Server?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 03:19:31761browse

How to Remove the .html Extension from URLs in Your Go HTTP Server?

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!

Statement:
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