首页  >  文章  >  后端开发  >  如何从 Go HTTP 服务器中的 URL 中删除 .html 扩展名?

如何从 Go HTTP 服务器中的 URL 中删除 .html 扩展名?

Patricia Arquette
Patricia Arquette原创
2024-10-28 03:19:31761浏览

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

使用自定义文件系统删除 .html 扩展名

要避免在 URL 中显示 .html 扩展名,一种方法是实现使用 http.Dir 的 http.FileSystem 接口。此解决方案利用了 http.FileServer 中强大的代码。

要实现此目的,请创建一个嵌入 http.Dir 的自定义类型:

<code class="go">type HTMLDir struct {
    d http.Dir
}</code>

修改 main 函数以使用此自定义文件系统而不是 http.FileServer:

<code class="go">func main() {
    fs := http.FileServer(HTMLDir{http.Dir("public/")})
    http.Handle("/", http.StripPrefix("/", fs))
    http.ListenAndServe(":8000", nil)
}</code>

接下来,为 HTMLDir 类型定义 Open 方法。此方法确定文件系统应如何处理文件请求。

始终使用 .html 扩展名:

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

回退到 .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>

回退到文件名(不带扩展名):

<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>

通过实施上述解决方案,您可以有效地删除 .访问 Go HTTP 服务器时,来自 URL 的 html 扩展名。

以上是如何从 Go HTTP 服务器中的 URL 中删除 .html 扩展名?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn