我胡汉三又回来啦。好久没发文了,为保持平台上的活跃度,我今天就分享下个刚学到的知识,使用golang搭建静态web服务器,亲测可用,附代码!
golanggolangiisapachenginxkangle
为什么呢?
golangnet/httpHTTP
golangphp、java、.net、nodejsgolang
golang
我是新手上路,照搬文章里的内容,总是磕磕碰碰,每次运行都是找不到路径。代码是这样的:
func main() {
http.Handle("/css/", http.FileServer(http.Dir("template")))
http.Handle("/js/", http.FileServer(http.Dir("template")))
http.ListenAndServe(":8080", nil)
}
目录结构:
src
|--main
| |-main.go
|--template
| |-css
| |--admin.css
| |-js
| |--admin.js
| |-html
| |--404.html
template
其实我很纳闷,文章作者都可以成功运行起来这个demo,怎么到我这里,就启动不来了呢?
那么问题来了:
1.是什么原因导致程序起不来呢?
2.http.Dir()指向的是什么路径?
于是我追踪日志,如下
2018/01/07 11:09:28 open template/html/404.html: The system cannot find the path specified.
找不到路径http.Dir()
我查看了官方例子:
log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
http.Dir("/usr/share/doc")http.Dir()
另一个例子,使用http.StripPrefix()方法:
// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
tmpfilestmp
既然问题都解决了,那么就修改一下代码,重新运行
func Template_dir() string {
template_dir := "E:\\project\\gotest\\src\\template"
return template_dir
}
func main() {
http.Handle("/css/", http.FileServer(http.Dir(Template_dir())))
http.Handle("/js/", http.FileServer(http.Dir(Template_dir())))
http.ListenAndServe(":8080", nil)
}
localhost:8080/css/template/css/admin.css