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

Patricia Arquette
Release: 2024-10-28 03:19:31
Original
868 people have browsed it

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

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

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

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

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

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!

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