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



我正在学习go web编程,并了解所有内容,但我迷失在这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提供一个文件(包括它的所有内容)。文件服务器()
  3. 我们去掉前缀,因为现在我们在fs的handleFunc()中
  4. StripPrefix()创建了一个HandlerFunc()
  5. mux。Handle()在mux中注册HandlerFunc()
  6. 兔子洞很深。。。然后这个goroutinego c.serve(ctx)by CCD_
  7. 因此,/public/目录中的每个静态文件都由我们的服务器同时提供服务

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

在查看了文档后,我认为会发生以下情况:

http.Dir("public")

您正在将string"public"转换为实现FileSystem接口的类型Dir

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

根据文件显示:

FileServer返回一个处理程序,该处理程序使用根目录下的文件系统的内容。

root是作为参数传递的Dir

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

Handlerfs封装在由StripPrefix函数创建的Handler

根据文件显示:

StripPrefix返回一个处理程序,该处理程序通过删除请求URL的Path中的给定前缀,并调用处理程序h

h是作为参数传递的Handlerfs

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

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

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

目前正在阅读SohamKamani的GoLang教程,发现他的解释有很大帮助:

func newRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/hello", handler).Methods("GET")
// Declare the static file directory and point it to the
// directory we just made
staticFileDirectory := http.Dir("./assets/")
// Declare the handler, that routes requests to their respective filename.
// The fileserver is wrapped in the `stripPrefix` method, because we want to
// remove the "/assets/" prefix when looking for files.
// For example, if we type "/assets/index.html" in our browser, the file server
// will look for only "index.html" inside the directory declared above.
// If we did not strip the prefix, the file server would look for
// "./assets/assets/index.html", and yield an error
staticFileHandler := http.StripPrefix("/assets/", http.FileServer(staticFileDirectory))
// The "PathPrefix" method acts as a matcher, and matches all routes starting
// with "/assets/", instead of the absolute route itself
r.PathPrefix("/assets/").Handler(staticFileHandler).Methods("GET")
return r
}

确认:

您正在注册静态文件的自动处理程序。形式为:GET /static/some_file的请求将通过从/public目录传递文件来同时处理。

最新更新