http.StripPrefix 的參數含義


看下面兩行代碼:

http.Handle("/file/", http.StripPrefix("/file", http.FileServer(http.Dir("./output/"))))
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./output/"))))
http.Handle("/file1", http.StripPrefix("/file1", http.FileServer(http.Dir("./output/"))))
http.Handle("/file2", http.StripPrefix("/file2/", http.FileServer(http.Dir("./output/"))))

注意看下圖結果:

  • 1、2 行鏈接地址是帶對應前綴的。
  • 3行鏈接地址不帶
  • 4直接 404

 

image

image

 

image

image

 

TrimPrefix

TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

StripPrefix

// StripPrefix returns a handler that serves HTTP requests
// by removing the given prefix from the request URL's Path
// and invoking the handler h. StripPrefix handles a
// request for a path that doesn't begin with prefix by
// replying with an HTTP 404 not found error.
func StripPrefix(prefix string, h Handler) Handler {
    if prefix == "" {
        return h
    }
    return HandlerFunc(func(w ResponseWriter, r *Request) {
        if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
            r.URL.Path = p
            h.ServeHTTP(w, r)
        } else {
            NotFound(w, r)
        }
    })
}
如上圖代碼所示,
404 是觸發了上面的 else 條件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM