小编典典

为什么需要使用http.StripPrefix访问我的静态文件?

go

main.go

package main

import (
    "net/http"
)

func main() {
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
    http.ListenAndServe(":8080", nil)
}

目录结构:

%GOPATH%/src/project_name/main.go
%GOPATH%/src/project_name/static/..files and folders ..

即使阅读了文档,我仍然无法理解http.StripPrefix此处的确切功能。

1)localhost:8080/static如果删除,为什么我无法访问http.StripPrefix

2)/static如果删除该功能,URL将映射到文件夹吗?


阅读 430

收藏
2020-07-02

共1个答案

小编典典

http.StripPrefix()
将请求的处理转发给您指定为其参数的对象,但在此之前,它会通过剥离指定的前缀来修改请求URL。

因此,例如,在您的情况下,如果浏览器(或HTTP客户端)请求资源:

/static/example.txt

StripPrefix将会剪切/static/和将修改后的请求转发到由返回的处理程序,http.FileServer()因此它将看到请求的资源是

/example.txt

Handler通过返回http.FileServer()将寻找并送达文件的内容 相对
文件夹(或者更确切地说,FileSystem指定作为其参数)(指定"static"为静态文件的根目录)。

现在,由于"example.txt"位于static文件夹中,因此您必须指定相对路径以获取相应的文件路径。

另一个例子

该示例可以在http软件包文档页面(此处)中找到:

// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/",
        http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))

说明:

FileServer()被告知静态文件的根是"/tmp"。我们希望网址以开头"/tmpfiles/"。因此,如果有人要求"/tempfiles/example.txt",我们希望服务器发送文件"/tmp/example.txt"

为了实现这一点,我们必须"/tmpfiles"从URL中删除,其余的将是与根文件夹相比的相对路径"/tmp",如果我们加入,则根目录将给出:

/tmp/example.txt
2020-07-02