How to Strip the .html Extension from File Names in a Go HTTP Server?

Linda Hamilton
Release: 2024-10-29 13:59:02
Original
338 people have browsed it

How to Strip the .html Extension from File Names in a Go HTTP Server?

How to Remove the .html Extension from Files in an HTTP Server

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

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!

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!