我正在学习网络编程并理解一切,但我迷失在这 3 行看似简单的代码中:
fs := http.FileServer(http.Dir("public"))
handler := http.StripPrefix("/static/", fs)
mux.Handle("/static/", handler)
...我已经阅读了以下几行的 go src,这是我可以推断的:
http.Dir("public")
正在将字符串“public”转换为类型 Dir。- 然后我们使用 http.FileServer() 提供一个文件(包括其所有内容)
- 我们去掉前缀,因为现在我们在 fs 的 handleFunc() 中
- StripPrefix() 创建了一个 HandlerFunc()
- mux.Handle() 在 mux 中注册 HandlerFunc()。
- 深入兔子洞...然后这个 goroutine
go c.serve(ctx)
byfunc (srv *Server) Serve(l net.Listener) error {}/
- 因此
/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/