【玩轉Golang】beego下實現martini中的透明式靜態檔案服務(static folder)效果。

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

  出於效率等原因,最近將web架構由martini切換為了beego,其他地方都很平順,只是兩個架構的handler簽名不一致,需要修改,所以耗時較長,這是預計到的。但是有一個地方沒有預計到,也耗費了較多時間,那就是靜態檔案的服務。

  用過martini的tx都知道,在mairtini中如果我們設定一個目錄為靜態檔案目錄,只需添加martini的Static外掛程式,如設定web子目錄為應用的靜態檔案路徑:

        m.Use(martini.Static("web"))

  此時,如果我們訪問一個url,此url並沒有在martini中註冊,但是如果位於web目錄中,就可以得到響應,例如:

http://127.0.0.1:8088/ //返回web目錄下的index.htmlhttp://127.0.0.1:8088/ js/jquery.js//返回web/js/jquery.js

  但是,切換為beego之後,卻沒有找到這樣的功能。發現beego對於靜態檔案的支援設計的有點不夠友好,比如我進行如下設定

beego.SetStaticPath("/web", "web")

  這時候訪問結果如下

http://127.0.0.1:8088/ //返回404頁面http://127.0.0.1:8088/web//返回404頁面http://127.0.0.1:8088/web/index.html//返回403 (Forbidden)http://127.0.0.1:8088/web/chat.html//返回正常http://127.0.0.1:8088/web/images/test.png//返回正常

  據此結果,有兩點不滿意:

  1. 必須添加該staticdir 映射的path訪問,設定為“/” 無效
  2. 竟然不能返回預設頁面!看文檔需要設定”beego.DirectoryIndex=true“ ,不是我需要的!

  因此,我著手自己實現該需求。通過學習beego文檔,發現可以設定Filter。於是,編寫如下代碼:

//main中如下設定filter
beego.InsertFilter("/*", beego.BeforeRouter, TransparentStatic).
.
.func TransparentStatic(ctx
*context.Context) { defInd := 0 maxInd := len(defHomes) - 1 orpath := ctx.Request.URL.Path beego.Debug(" in trasparentstatic filter orpath", orpath) if strings.Index(orpath, "api/") >= 0 || strings.Index(orpath, "web/") >= 0 { return }DefaultStartPage: p := orpath if strings.EqualFold(p, "/") { p += defHomes[defInd] defInd++ } ps := strings.Split(p, "/") ps = append([]string{"web"}, ps...) rp := strings.Join(ps, "/") fp := fw.MapPath(rp) beego.Debug("test fp", fp) if !fileutils.Exists(fp) { if defInd > 0 && defInd < maxInd { goto DefaultStartPage } return } else { beego.Debug("found static ", fp) http.ServeFile(ctx.ResponseWriter, ctx.Request, fp) //cannot use Redirect! will lead loop //http.Redirect(ctx.ResponseWriter, ctx.Request, rp, http.StatusFound) return } //}

  運行之後,發現訪問服務地址,帶不帶末尾的"/",都不能返回預設頁面,如果明確訪問/index.html可以實現訪問。後經探索發現,雖然beego說明中說"/*"可以適配所有url,但是實際上不能適配"/",因此需要在註冊一個filter到”/":

beego.InsertFilter("/", beego.BeforeRouter, TransparentStatic) //must has this for default pagebeego.InsertFilter("/*", beego.BeforeRouter, TransparentStatic)

至此,一切正常了。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.