Go http.Handle和http.HandleFunc的路由问题

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"

Go http.Handle和http.HandleFunc的路由问题_第1张图片

 

你可能感兴趣的:(golang,web)