当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > golang文件服务器,可以访问任何目录

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

2020年04月26日  | 移动技术网IT编程  | 我要评论
一、方法1: 主要用到的方法是http包的FileServer,参数很简单,就是要路由的文件夹的路径。 package main import ( "fmt" "net/http" ) func main() { http.Handle("/", http.FileServer(http.Dir(" ...

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

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网