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

Linda Hamilton
Release: 2024-10-28 08:34:29
Original
734 people have browsed it

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>
Copy after login
  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>
Copy after login

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>
Copy after login

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>
Copy after login
  1. Use your custom FileSystem:
<code class="go">fs := http.FileServer(HTMLDir{http.Dir("public/")})
http.Handle("/", http.StripPrefix("/", fs))</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!