我胡漢三又回來啦。好久沒發文了,為保持平臺上的活躍度,我今天就分享下個剛學到的知識,使用golang搭建靜態web服務器,親測可用,附代碼!
使用過golang語言的程序猿都應該知道,在使用golang開發的時候,我們是不需要諸如iis,apache,nginx,kangle等服務器支持的。
為什么呢?
原因是,golang的net/http包中已經提供了HTTP的客戶端與服務端實現方案。
網上言論都說golang不適合做web開發,相對php、java、.net、nodejs等各類后端語言來說,使用golang來做web開發,確實是一個大工程。
昨晚恰好看到一篇關于使用golang搭建web服務器的文章,心癢難耐,于是自己也折騰了一下,用來練練手。
我是新手上路,照搬文章里的內容,總是磕磕碰碰,每次運行都是找不到路徑。代碼是這樣的:
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")可看出,該路徑指向的是linux系統里的絕對路徑。那么問題就解決了:我只需要將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文件。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答