上次寫了一個2行實現一個靜態服務器的文章
今天群里有個哥們是這么寫居然返回的是404 見鬼了嘛??
http.handle("/js", http.FileServer(http.Dir("js"))
http.ListenAndServe("8080", nil)
大概的意思就是綁定 路由為 js 的時候訪問這個js 文件夾 看了一下確實代碼上面沒什么毛病。但是路徑怎么修改 也不好使。
我把代碼拿到我的 電腦上面運行 shitfuck 這是搞什么啊居然出現下面的這個情況

奇怪居然在我電腦上面也不能執行了。莫非我的文件夾權限有問題
給賦值一下 777 權限 重新運行
居然還不好使。來回改路徑 就這么搗鼓了兩個小時無意中看到一個文章就是說的這個
加一個StripPrefix 方法就好了
那這個玩意是干嘛的呢。看看手冊

然后我的代碼就變成這個樣子
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("js"))))
http.StripPrefix用于過濾request,參數里的handler的request過濾掉特定的前序,只有這樣,才能正確顯示文件目錄。 shitfuck
看一下我的路徑 以及下面存放的文件

修改代碼完成后就這么神奇般的解決了

浪費了兩個小時不過 還不錯最起碼解決問題了。
補充:Golang1.8標準庫http.Fileserver跟http.ServerFile小例子
我就廢話不多說了,大家還是直接看代碼吧~
package main
import (
"fmt"
"net/http"
"os"
"path"
"strings"
)
var staticfs = http.FileServer(http.Dir("D:\\code\\20160902\\src\\"))
func main() {
//瀏覽器打開的時候顯示的就是D:\\code\\20160902\\src\\client目錄下的內容"
http.Handle("/client/", http.FileServer(http.Dir("D:\\code\\20160902\\src\\")))
http.HandleFunc("/static/", static)
http.HandleFunc("/js/", js)
http.HandleFunc("/", route)
http.ListenAndServe(":1789", nil)
}
func route(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL)
fmt.Fprintln(w, "welcome")
r.Body.Close()
}
//這里可以自行定義安全策略
func static(w http.ResponseWriter, r *http.Request) {
fmt.Printf("訪問靜態文件:%s\n", r.URL.Path)
old := r.URL.Path
r.URL.Path = strings.Replace(old, "/static", "/client", 1)
staticfs.ServeHTTP(w, r)
}
//設置單文件訪問,不能訪問目錄
func js(w http.ResponseWriter, r *http.Request) {
fmt.Printf("不能訪問目錄:%s\n", r.URL.Path)
old := r.URL.Path
name := path.Clean("D:/code/20160902/src" + strings.Replace(old, "/js", "/client", 1))
info, err := os.Lstat(name)
if err == nil {
if !info.IsDir() {
http.ServeFile(w, r, name)
} else {
http.NotFound(w, r)
}
} else {
http.NotFound(w, r)
}
}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- Golang實現http server提供壓縮文件下載功能
- golang語言http協議get拼接參數操作
- Golang 實現分片讀取http超大文件流和并發控制
- 在Golang中使用http.FileServer返回靜態文件的操作
- golang HTTP 服務器 處理 日志/Stream流的操作
- golang http使用踩過的坑與填坑指南