這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
隨學隨記,留備查
1、核心是需要擷取檔案的絕對路徑,os.Open()需要;
2、windows使用“\”表示路徑,而go需要“/”表示路徑,所以需要將“\”替換為“/”;
3、使用內建的http.ServerFile()函數提供後續的檔案傳輸服務;
package mainimport ("fmt""log""net/http""os""path/filepath""strings")var StaticDir = "/static"func getCurDir() string {dir, err := filepath.Abs(filepath.Dir(os.Args[0]))if err != nil {log.Fatal(err)}return strings.Replace(dir, "\\", "/", -1)}func dealStaticFiles(w http.ResponseWriter, r *http.Request) {stDir := getCurDir()if strings.HasPrefix(r.URL.Path, StaticDir) {file := stDir + r.URL.Pathfmt.Println(file)f, err := os.Open(file)defer f.Close()if err != nil && os.IsNotExist(err) {fmt.Fprintln(w, "File not exist")return}http.ServeFile(w, r, file)return} else {fmt.Fprintln(w, "Hello world")}}func main() {http.HandleFunc("/", dealStaticFiles) //設定訪問的路由err := http.ListenAndServe(":8080", nil) //設定監聽的連接埠if err != nil {log.Fatal("ListenAndServe: ", err)}}