首頁  >  文章  >  後端開發  >  如何從 Go HTTP 伺服器中的 URL 中刪除 .html 副檔名?

如何從 Go HTTP 伺服器中的 URL 中刪除 .html 副檔名?

Linda Hamilton
Linda Hamilton原創
2024-10-28 08:34:29720瀏覽

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

從HTTP 伺服器中的檔案中刪除.html 副檔名

許多HTTP 伺服器會自動在URL 結尾新增「.html」名,在某些情況下這可能是不可取的。若要在 Go HTTP 伺服器中修改此行為,您可以使用 http.Dir 實作自訂 http.FileSystem。具體方法如下:

  1. 建立自訂檔案系統:
<code class="go">type HTMLDir struct {
    d http.Dir
}</code>
  1. 實作Open 方法:
實作Open 方法:

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) {
    // 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
}</code>

以「.html」副檔名和後備開始:
<code class="go">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
}</code>
  1. 使用您的自訂檔案系統:
<code class="go">fs := http.FileServer(HTMLDir{http.Dir("public/")})
http.Handle("/", http.StripPrefix("/", fs))</code>

透過實作http.FileSystem 並自訂Open 方法,您可以控制HTTP 伺服器如何提供文件,包括圍繞「.html」副檔名的行為。

以上是如何從 Go HTTP 伺服器中的 URL 中刪除 .html 副檔名?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn