golang文件服务器,可以访问任何目录

一、方法1:

主要用到的方法是http包的FileServer,参数很简单,就是要路由的文件夹的路径。

package main

import (
    "fmt"
    "net/http"
)

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

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

上面例子的路由只能把根目录也就是“/”目录映射出来,例如你写成”http.Handle("/files", http.FileServer(http.Dir("./")))“,就无法把通过访问”/files“把当前路径下的文件映射出来。于是就有了http包的StripPrefix方法。

二、方法2:

实现访问任意文件夹下面的文件。

package main

import (
    "fmt"
    "net/http"
)

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

这里生成了一个ServeMux,与文件服务器无关,可以先不用关注。用这种方式,就可以把任意文件夹下的文件路由出来了。

posted on 2020-04-26 15:08  lxsky  阅读(1244)  评论(0编辑  收藏  举报

导航