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

Dan*_*nte 32 http url-rewriting url-routing go server

main.go

package main

import (
    "net/http"
)

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

目录结构:

%GOPATH%/src/project_name/main.go
%GOPATH%/src/project_name/static/..files and folders ..
Run Code Online (Sandbox Code Playgroud)

即使在阅读完文档后,我也无法理解http.StripPrefix这里究竟是做什么的.

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

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

icz*_*cza 38

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

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

/static/example.txt
Run Code Online (Sandbox Code Playgroud)

StripPrefix/static/修改后的请求剪切并转发给返回的处理程序,http.FileServer()以便它将看到所请求的资源

/example.txt
Run Code Online (Sandbox Code Playgroud)

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"))))
Run Code Online (Sandbox Code Playgroud)

说明:

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

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

/tmp/example.txt
Run Code Online (Sandbox Code Playgroud)

  • 对于阅读此内容的任何人,请确保在`/ tmpfiles /`中使用尾部斜杠,否则您将遇到不好的时间. (4认同)
  • 为了澄清和传播正确的常识,句柄中的`/tmpfile/` 很重要,但在 StripPrefix 中不重要,比如说`http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles", http.FileServer (http.Dir("/tmp"))))` 也可以 (2认同)

小智 5

假使,假设

我有一个档案

/home/go/src/js/kor.js
Run Code Online (Sandbox Code Playgroud)

然后,告诉fileserve服务本地目录

fs := http.FileServer(http.Dir("/home/go/src/js"))
Run Code Online (Sandbox Code Playgroud)

示例1-Filerserver根目录的根URL

现在文件服务器将"/"请求作为"/home/go/src/js"+"/"

http.Handle("/", fs)
Run Code Online (Sandbox Code Playgroud)

是的,http://localhost/kor.js请求告诉Fileserver,kor.js

"/home/go/src/js" +  "/"  + "kor.js".
Run Code Online (Sandbox Code Playgroud)

我们有kor.js文件。

Example2-自定义URL到文件服务器根目录

但是,如果添加其他请求名称。

http.Handle("/static/", fs)
Run Code Online (Sandbox Code Playgroud)

现在文件服务器将"/static/"请求作为"/home/go/src/js"+"/static/"

是的,http://localhost/static/kor.js请求告诉Fileserver,kor.js

"/home/go/src/js" +  "/static/"  + "kor.js".
Run Code Online (Sandbox Code Playgroud)

我们收到404错误。

示例3-使用以下命令自定义url到Fileserver根目录

因此,我们在Fileserver接收请求网址之前先修改请求网址 http.StripPrefix("/tmpfiles/", ...

stripPrefixFileserver /取而代之之后/static/

"/home/go/src/js" +  "/"  + "kor.js".
Run Code Online (Sandbox Code Playgroud)

得到 kor.js