Golang 服务静态文件,请解释这 3 行代码中发生了什么

标签 go

我正在学习网络编程并理解一切,但我迷失在这 3 行看似简单的代码中:

fs := http.FileServer(http.Dir("public"))
handler := http.StripPrefix("/static/", fs)
mux.Handle("/static/", handler)

...我已经阅读了以下几行的 go src,这是我可以推断的:

  1. http.Dir("public") 正在将字符串“public”转换为类型 Dir。
  2. 然后我们使用 http.FileServer() 提供一个文件(包括其所有内容)
  3. 我们去掉前缀,因为现在我们在 fs 的 handleFunc() 中
  4. StripPrefix() 创建了一个 HandlerFunc()
  5. mux.Handle() 在 mux 中注册 HandlerFunc()。
  6. 深入兔子洞...然后这个 goroutine go c.serve(ctx) by func (srv *Server) Serve(l net.Listener) error {}/
  7. 因此 /public/ 目录中的每个静态文件都由我们的服务器同时提供服务。

有人可以确认或解释这 3 行代码中到底发生了什么。

最佳答案

在查看文档后,我认为会发生这种情况:

http.Dir("public")

您正在将 string "public" 转换为类型 Dir它实现了 FileSystem界面

fs := http.FileServer(http.Dir("public"))

根据docs做:

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.

root 是您作为参数传递的 Dir

handler := http.StripPrefix("/static/", fs)

您将 Handler fs 包装在由 StripPrefix 创建的 Handler 中函数

根据docs做:

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h

h 是作为参数传递的 Handler fs

mux.Handle("/static/", handler)

您让所有以路径 /static/ 开头的请求都由 handler 处理

所以简而言之,所有对路径 /static/ 的请求都将去除 /static/ 前缀,并从 public< 返回一个文件 您服务器上同名的目录,例如。对 /static/requestedFile.txt 的请求将返回 public/requestedFile.txt

下的文件

关于Golang 服务静态文件,请解释这 3 行代码中发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46867473/

相关文章:

google-app-engine - 创建数据存储的成本。 key : Storing a key in struct versus an id and fetching from the datastore

docker - nsq 无法通过连接到 nsqlookupd 来消费消息

戈朗 : cgo extern is not working

go - Protocol Buffer : Send arbitrary structure over GRPC

go - metadata.FromOutgoingContext 和 metadata.FromIncomingContext 有什么区别?

mongodb - 努力将 MongoDB singleResult 对象转换为 Go 结构

go - 如何启动和停止函数

go - 在 Viper 中使用 ENV 变量覆盖配置的问题

go - 是否可以覆盖自定义类型的 len 函数的行为?

mongodb - 执行 mgo.Pipe 没有结果,包括 $out