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

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 08:34:29720browse

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:

  1. Create a custom FileSystem:
<code class="go">type HTMLDir struct {
    d http.Dir
}</code>
  1. Implement the Open method:

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>
  1. Use your custom FileSystem:
<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!

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