1. 程式人生 > >golang實現簡單檔案伺服器

golang實現簡單檔案伺服器

用golang做一個簡單的檔案伺服器,http包提供了很好的支援,由於時間緊促,只看了http包中自己需要的一小部分,建議大家如果需要還是去看官網的文件,搜尋引擎搜尋出來的前幾個方法不是很符合需求.

主要用到的方法是http包的FileServer

第一個Demo:

package main

import (
    "fmt"
    "net/http"
)


func main() {
    http.Handle("/", http.FileServer(http.Dir("./")))

    e := http.ListenAndServe(":8080", nil)
    fmt.Println(e)
}

這裡直接使用了http.FileServer方法,引數很簡單,就是要路由的資料夾的路徑。但是這個例子的路由只能把根目錄也就是“/”目錄映射出來,沒法更改成其他路由,例如你寫成”http.Handle("/files", http.FileServer(http.Dir("./")))“,就無法把通過訪問”/files“把當前路徑下的檔案映射出來。於是就有了http包的StripPrefix方法。

第二個Demo,加上了http包的StripPrefix方法:

package main

import (
    "fmt"
    "net/http"
)


func main() {
     mux := http.NewServeMux()
    mux.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir("../files"))))
    if err := http.ListenAndServe(":3000", mux); err != nil {
        log.Fatal(err)
    }
}

這裡生成了一個ServeMux,與檔案伺服器無關,可以先不用關注。用這種方式,就可以把任意資料夾下的檔案路由出來了,哈哈

 很久不用golang,寫的不對的地方還請多多指正。