源代码: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)//返回报错信息
}