服務計算——web程式開發與Go原始碼
阿新 • • 發佈:2018-12-17
原始碼:https://github.com/kotomineshiki/WebServerOfGo
處理 web 程式的輸入與輸出
要求:
- 支援靜態檔案服務
- 支援簡單 js 訪問
- 提交表單,並輸出一個表格
- 對 /unknown 給出開發中的提示,返回碼 5xx
支援靜態檔案服務
支援簡單 js 訪問
這是一個簡單的計算器web程式
對 /unknown 給出開發中的提示,返回碼 5xx
表單的儲存及釋放
http包原始碼解析(註釋)
func NewServer() *negroni.Negroni { //copy自案例
formatter := render.New()//建立新的render例項
n := negroni.Classic()//標明是標準Negroni例項,有著預設的中介軟體
mx := mux.NewRouter()//建立router例項
initRoutes(mx, formatter)
n.UseHandler(mx)//新增一個httphandler到中介軟體的棧中。 handler按照新增順序被激發
return n
}
func initRoutes(mx *mux.Router, formatter *render.Render) {
webRoot := os.Getenv("WEBROOT")//獲取環境(根目錄)
if len(webRoot) == 0 {
if root, err := os.Getwd(); err != nil {
panic("Could not retrive working directory")
} else {
webRoot = root
}
}
mx.HandleFunc("/unknown", unknownPage).Methods("GET")
//HandleFunc登記了一個url匹配器
mx.HandleFunc ("/", indexPage).Methods("GET")
//Methods 匹配http方法。
mx.HandleFunc("/index", indexPage).Methods("GET")
mx.HandleFunc("/calculator", calculatorPage).Methods("GET")
mx.HandleFunc("/", submit).Methods("POST")
mx.PathPrefix("/file").Handler(http.StripPrefix("/file/", http.FileServer(http.Dir(webRoot+"/assets/"))))//這個是用來匹配字首的,比如/foobar/會被匹配為/foo
//而stripprefix 返回去除了字首之後的部分
//FileServer返回一個handler及該位置上的內容,即靜態檔案
}
下面好幾個檔案寫法比較雷同,挑代表性的講解
package service
import (
"html/template"
"net/http"
)
func calculatorPage(w http.ResponseWriter, req *http.Request) {
page := template.Must(template.ParseFiles("templates/calculator.html"))
//Must是用來防止出錯的。如果must引數是nil ,就會panic
//ParseFiles建立一個新的模板,並從名字解析定義
page.Execute(w, nil)
//execute函式使用解析過的檔案,輸出到螢幕
}
func unknownPage(reqw http.ResponseWriter, req *http.Request) {
http.Error(reqw, "504 Not Implemented!", 504)//返回報錯資訊
}