哈尔滨网站设计人,网站建设公司福州,网站建设费记什么科目,网站集群建设合同Golang的net/http包提供了原生的http服务#xff0c;其中http.Handle和http.HandleFunc是两个重要的路由函数。
1. 函数介绍
http.HandleFunc和http.Handle的函数原型如下#xff0c;其中DefaultServeMux是http包提供的一个默认的路由选择器。
func HandleFunc(pattern st…Golang的net/http包提供了原生的http服务其中http.Handle和http.HandleFunc是两个重要的路由函数。
1. 函数介绍
http.HandleFunc和http.Handle的函数原型如下其中DefaultServeMux是http包提供的一个默认的路由选择器。
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {DefaultServeMux.HandleFunc(pattern, handler)
}
func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
2. 路由介绍
两个函数中的pattern参数为路由匹配不需要输入域名。
/在其他路由没有匹配成功的时候匹配任何路由。浏览器请求的URL为localhost:8080
/js/浏览器请求的路由为localhost:8080/js/
http.Handle(/js/, http.FileServer(http.Dir(./public/)))寻找的目录在./public/js/filename举个例子URL为localhost:8080/js/scr.js后台程序中寻找src.js的路径为./public/js/src.js。这就需要再工程的public目录下再建立一个js目录为了解决这个问题可以使用 http.StripPrefix 函数例如
http.Handle(/js/, http.StripPrefix(/js, http.FileServer(http.Dir(./src/public/))))后台程序寻找的路径就没有/js/了即为./public/src.js虽然URL还有/js/ func myWeb(w http.ResponseWriter, r *http.Request) {t, _ : template.ParseFiles(./public/index.html)t.Execute(w, )
}
http.HandleFunc(/, myWeb)
http.Handle(/js/, http.FileServer(http.Dir(./public/)))
这里有个注意点./public/和./public/index.html中的.指的是当前打开的工程的根目录。例如如下图./public/和./public/index.html就要变为./src/public/和./src/public/index.html如果工程打开的是src目录则为./public/和./public/index.html