How to Hide HTML File Extensions from URLs in a Go HTTP Server?

Mary-Kate Olsen
Release: 2024-10-27 16:26:02
Original
623 people have browsed it

How to Hide HTML File Extensions from URLs in a Go HTTP Server?

How to Conceal File Extensions in a Simple HTTP Server

Many web servers display file extensions in the URL, which can be undesirable for aesthetic or user-experience reasons. This guide demonstrates how to conceal the .html extension from URLs in a Go HTTP server.

Solution

Implement http.FileSystem using http.Dir offers several benefits, including leveraging the robust code within http.FileServer. A custom HTMLDir struct can be created to implement this functionality.

Implementation

The implementation of Open depends on the desired behavior. Three scenarios are presented below:

Option 1: Always Append .html

<code class="go">func (d HTMLDir) Open(name string) (http.File, error) {
    return d.d.Open(name + ".html")
}</code>
Copy after login

Option 2: Fallback to .html

<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

Option 3: Start with .html and Fallback

<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 using HTMLDir with http.StripPrefix, the .html extension can be effectively concealed when serving files from the specified directory. This technique provides a more seamless and aesthetically pleasing user experience, while still allowing access to the intended content.

The above is the detailed content of How to Hide HTML File Extensions 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