我胡漢三又回來啦。好久沒發(fā)文了,為保持平臺上的活躍度,我今天就分享下個剛學到的知識,使用golang搭建靜態(tài)web服務器,親測可用,附代碼!
使用過golang語言的程序猿都應該知道,在使用golang開發(fā)的時候,我們是不需要諸如iis,apache,nginx,kangle等服務器支持的。
為什么呢?
原因是,golang的net/http包中已經(jīng)提供了HTTP的客戶端與服務端實現(xiàn)方案。
網(wǎng)上言論都說golang不適合做web開發(fā),相對php、java、.net、nodejs等各類后端語言來說,使用golang來做web開發(fā),確實是一個大工程。
昨晚恰好看到一篇關于使用golang搭建web服務器的文章,心癢難耐,于是自己也折騰了一下,用來練練手。
我是新手上路,照搬文章里的內(nèi)容,總是磕磕碰碰,每次運行都是找不到路徑。代碼是這樣的:
func main() {
http.Handle("/css/", http.FileServer(http.Dir("template")))
http.Handle("/js/", http.FileServer(http.Dir("template")))
http.ListenAndServe(":8080", nil)
}
目錄結(jié)構(gòu):
src
|--main
| |-main.go
|--template
| |-css
| |--admin.css
| |-js
| |--admin.js
| |-html
| |--404.html
以上運行結(jié)果是:找不到template這個路徑。
其實我很納悶,文章作者都可以成功運行起來這個demo,怎么到我這里,就啟動不來了呢?
那么問題來了:
1.是什么原因?qū)е鲁绦蚱鸩粊砟兀?br />
2.http.Dir()指向的是什么路徑?
于是我追蹤日志,如下
2018/01/07 11:09:28 open template/html/404.html: The system cannot find the path specified.
發(fā)現(xiàn)問題是出在找不到路徑上。解決了第一個問題后,那么接下來就需要搞明白http.Dir()到底指向的是哪個路徑。
我查看了官方例子:
log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
從上面例子http.Dir("/usr/share/doc")可看出,該路徑指向的是linux系統(tǒng)里的絕對路徑。那么問題就解決了:我只需要將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"))))
可看出,tmpfiles是tmp目錄下的一個子目錄。
既然問題都解決了,那么就修改一下代碼,重新運行
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文件。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- golang DNS服務器的簡單實現(xiàn)操作
- golang-gin-mgo高并發(fā)服務器搭建教程
- golang HTTP 服務器 處理 日志/Stream流的操作
- golang項目如何上線部署到Linu服務器(方法詳解)
- golang文件服務器的兩種方式(可以訪問任何目錄)
- 詳解如何熱重啟golang服務器
- 淺談Golang中創(chuàng)建一個簡單的服務器的方法
- 基于 HLS 創(chuàng)建 Golang 視頻流服務器的優(yōu)缺點