從HTTP 伺服器中的檔案中刪除.html 副檔名
許多HTTP 伺服器會自動在URL 結尾新增「.html」名,在某些情況下這可能是不可取的。若要在 Go HTTP 伺服器中修改此行為,您可以使用 http.Dir 實作自訂 http.FileSystem。具體方法如下:
<code class="go">type HTMLDir struct { d http.Dir }</code>
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>
<code class="go">fs := http.FileServer(HTMLDir{http.Dir("public/")}) http.Handle("/", http.StripPrefix("/", fs))</code>
以上是如何從 Go HTTP 伺服器中的 URL 中刪除 .html 副檔名?的詳細內容。更多資訊請關注PHP中文網其他相關文章!