从简单 HTTP 服务器中的每个文件中删除 .html 扩展名

Mar*_*ton 3 http go server

我想让当有人访问我的 Go HTTP 服务器上的页面时,他们不会看到.html扩展。例如,当他们访问时,https://example.org/test他们会看到https://example.org/test.html.

我的代码:

package main

import (
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("public/"))

    http.Handle("/", http.StripPrefix("/", fs))
    http.ListenAndServe(":8000", nil)
}
Run Code Online (Sandbox Code Playgroud)

小智 6

一种选择是实现http.FileSystem使用http.Dir。这种方法的优点是它利用了 http.FileServer 中精心编写的代码。

它看起来像这样:

type HTMLDir struct {
    d http.Dir
}

func main() {
  fs := http.FileServer(HTMLDir{http.Dir("public/")})
  http.Handle("/", http.StripPrefix("/", fs))
  http.ListenAndServe(":8000", nil)
}
Run Code Online (Sandbox Code Playgroud)

Open方法的实现取决于应用程序要求。

如果您总是想添加 .html 扩展名,请使用以下代码:

func (d HTMLDir) Open(name string) (http.File, error) {
    return d.d.Open(name + ".html")
}
Run Code Online (Sandbox Code Playgroud)

如果要回退到 .html 扩展名,请使用以下代码:

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
}
Run Code Online (Sandbox Code Playgroud)

翻转上一个以从 .html 扩展名开始,然后回退到提供的名称:

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
}
Run Code Online (Sandbox Code Playgroud)