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

2022-10-08,,,

一、方法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,与文件服务器无关,可以先不用关注。用这种方式,就可以把任意文件夹下的文件路由出来了。

《golang文件服务器,可以访问任何目录.doc》

下载本文的Word格式文档,以方便收藏与打印。