項目地址
概述
設計一個 web 小應用,展示靜態文件服務、js 請求支持、模板輸出、表單處理、Filter 中間件設計等方面的能力。(不需要數據庫支持)
任務基本要求
編程web應用程序cloudgo-io。請在項目 README.MD 給出完成任務的證據! 基本要求:
- 支持靜態文件服務
- 支持簡單 js 訪問
- 提交表單,並輸出一個表格
- 對 /unknown 給出開發中的提示,返回碼 5xx
測試結果
運行代碼
靜態文件服務
assets文件夾下不存在index.html時:
- localhost:8080/static/
添加index.html:
- localhost:8080/static/
簡單 js 訪問
- localhost:8080/static/js/hello.js
提交表單,並輸出一個表格
- localhost:8080
- localhost:8080/login
對 /unknown 給出開發中的提示
- localhost:8080/unknown
- localhost:8080/sss
注意事項
相關包的安裝
實驗前需要使用 go get 命令安裝相關包
go get -u github.com/codegangsta/negroni
go get -u github.com/gorilla/mux
go get -u github.com/unrolled/render
執行目錄
必須在main.go目錄下執行go run
,而不能直接在其他目錄下執行go run '絕對路徑'
,否則在訪問時會出現404 page not found
.
StripPrefix的使用
server.go中,需要使用語句
mx.PathPrefix("/static").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(webRoot+"/assets/"))))
而不能直接使用
mx.PathPrefix("/static").Handler(http.FileServer(http.Dir(webRoot + "/assets/")))
這是因爲StripPrefix將訪問時url中的"/static/“前綴去掉後再交給http.FileServer(http.Dir(webRoot+"/assets/"))
處理,也就能訪問到assets目錄的路徑,如果不使用StripPrefix而直接使用以下代碼,則會出現404 page not found錯誤,因爲該服務器目錄中並沒有”/static/"這個路徑。