解析Go標準庫http.FileServer實現(xiàn)靜態(tài)文件服務-創(chuàng)新互聯(lián)

http.FileServer 方法屬于標準庫 net/http,返回一個使用 FileSystem 接口 root 提供文件訪問服務的 HTTP 處理器??梢苑奖愕膶崿F(xiàn)靜態(tài)文件服務器。

創(chuàng)新互聯(lián)自2013年起,是專業(yè)互聯(lián)網(wǎng)技術服務公司,擁有項目成都網(wǎng)站建設、網(wǎng)站設計網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元奉節(jié)做網(wǎng)站,已為上家服務,為奉節(jié)各地企業(yè)和個人服務,聯(lián)系電話:13518219792

http.ListenAndServe(":8080", http.FileServer(http.Dir("/files/path")))

訪問 http://127.0.0.1:8080,即可看到類似 Nginx 中 autoindex 目錄瀏覽功能。

源碼解析

我們現(xiàn)在開始將上述的那僅有的一行代碼進行剖析,看看到底是如何實現(xiàn)的。源碼中英文注釋也比較詳細,可以參考。

我們先看 http.Dir(),再看 http.FileServer(),而 http.ListenAndServe() 監(jiān)聽 TCP 端口并提供路由服務,此處不贅述。

http.Dir()

從以下源碼我們可以看出,type Dir string 實現(xiàn)了 type FileSystem interface 的接口函數(shù) Open,http.Dir("/") 實際返回的是 http.Dir 類型,將字符串路徑轉換成文件系統(tǒng)。

// 所屬文件: src/net/http/fs.go, 26-87行
type Dir string
func (d Dir) Open(name string) (File, error) {
  // ...
}
type FileSystem interface {
  Open(name string) (File, error)
}
http.FileServer()
http.FileServer() 方法返回的是 fileHandler 實例,而 fileHandler 結構體實現(xiàn)了 Handler 接口的方法 ServeHTTP()。ServeHTTP 方法內的核心是 serveFile() 方法。
// 所屬文件: src/net/http/fs.go, 690-716行
type fileHandler struct {
  root FileSystem
}
func FileServer(root FileSystem) Handler {
  return &fileHandler{root}
}
func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
  upath := r.URL.Path
  if !strings.HasPrefix(upath, "/") {
    upath = "/" + upath
    r.URL.Path = upath
  }
  serveFile(w, r, f.root, path.Clean(upath), true)
}
// 所屬文件: src/net/http/server.go, 82行
type Handler interface {
  ServeHTTP(ResponseWriter, *Request)
}

另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

當前題目:解析Go標準庫http.FileServer實現(xiàn)靜態(tài)文件服務-創(chuàng)新互聯(lián)
文章路徑:http://bm7419.com/article44/cdeeee.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作、外貿(mào)網(wǎng)站建設、營銷型網(wǎng)站建設、定制網(wǎng)站、面包屑導航、網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設計公司