天天看點

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,寫的不對的地方還請多多指正。