golang http.Dir()

使用FileServer看到需要传一个FileSystem类型
http.FileServer(http.Dir("/public"))
FileSystem是个interface
clipboard.png

然后http.Dir实现了FileSystem

clipboard.png
不应该是http.Dir.Open("public")
为何可以直接http.Dir("public")?不解,有人给解答下?

阅读 9.3k
3 个回答

Dir实际上是string

type Dir string

http.Dir("/public")可以认为是类型转换,不是函数

因为Dir实现了Open接口,http.Dir("/public")将/public字符串转换为了Dir.

// A Dir implements FileSystem using the native file system restricted to a
// specific directory tree.
//
// While the FileSystem.Open method takes '/'-separated paths, a Dir's string
// value is a filename on the native file system, not a URL, so it is separated
// by filepath.Separator, which isn't necessarily '/'.
//
// Note that Dir will allow access to files and directories starting with a
// period, which could expose sensitive directories like a .git directory or
// sensitive files like .htpasswd. To exclude files with a leading period,
// remove the files/directories from the server or create a custom FileSystem
// implementation.
//
// An empty Dir is treated as ".".
type Dir string

func (d Dir) Open(name string) (File, error) {
    ....
}

// A FileSystem implements access to a collection of named files.
// The elements in a file path are separated by slash ('/', U+002F)
// characters, regardless of host operating system convention.
type FileSystem interface {
    Open(name string) (File, error)
}

这样看应该比较清楚吧

http.Dir("/public")是利用本地tmp目录实现一个文件系统;
http.FileServer(http.Dir("/public"))返回一个Handler,其用来处理访问本地"/tmp"文件夹的HTTP请求;

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题