douzhan8395 2017-10-21 19:56
浏览 9
已采纳

Golang提供静态文件,请解释这三行代码会发生什么

I'm learning go web programming and understand everthing but I'm getting lost in this 3 apparently simple lines:

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

...I have read the go src for the following lines and this is what I can infer:

  1. http.Dir("public") is casting string "public" to type Dir.
  2. then we serve a file (including all its content) with http.FileServer()
  3. We strip prefix because now we are inside a handleFunc() for fs
  4. StripPrefix() created a HandlerFunc()
  5. mux.Handle() registers HandlerFunc() in the mux.
  6. Deep goes the rabbit hole... and then this goroutine go c.serve(ctx) by func (srv *Server) Serve(l net.Listener) error {}
  7. So each static file inside /public/ dir is served concurrently by our server.

Can someone confirm or explain what exactly is happening in the 3 lines of code.

  • 写回答

3条回答 默认 最新

  • douliudong8108 2017-10-21 20:34
    关注

    After looking at the docs I think this is what happens:

    http.Dir("public")
    

    you are converting the string "public" to the type Dir which implements the FileSystem interface

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

    which according to the docs does:

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

    root being the Dir you are passing as a parameter

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

    you wrap the Handler fs in the Handler created by the StripPrefix func

    which according to the docs does:

    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 being the Handler fs you are passing as a parameter

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

    you let all requests starting with the path /static/ be handled by handler

    So in short all requests for the the path /static/ will get stripped of the /static/ prefix and will return a file from the public directory on you server with the same name, eg. a request to /static/requestedFile.txt will return the file under public/requestedFile.txt

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法