首頁  >  文章  >  後端開發  >  如何從 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>
回退到.html 副檔名:

回退到檔案名稱(不含副檔名):

<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