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

问题描述 投票:31回答:3

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)如果删除该功能,哪个URL映射到/static文件夹?

http go url-rewriting server url-routing
3个回答
33
投票

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

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

/static/example.txt

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

/example.txt

Handler返回的http.FileServer()将查找并提供相对于指定为其参数的文件夹(或更确切地说是FileSystem)的文件内容(您指定"static"为静态文件的根)。

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

另一个例子

可以在http包文档页面(here)上找到此示例:

// 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"。我们希望URL以"/tmpfiles/"开头。因此,如果有人请求"/tempfiles/example.txt",我们希望服务器发送文件"/tmp/example.txt"

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

/tmp/example.txt

3
投票

Assume that

我有一个文件

/home/go/src/js/kor.js

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

fs := http.FileServer(http.Dir("/home/go/src/js"))

Example 1 - root url to Filerserver root

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

http.Handle("/", fs)

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

"/home/go/src/js" +  "/"  + "kor.js".

我们得到了kor.js文件。

示例2 - 文件服务器根目录的自定义URL

但是,如果我们添加额外的请求名称。

http.Handle("/static/", fs)

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

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

"/home/go/src/js" +  "/static/"  + "kor.js".

我们得到404错误。

示例3 - 使用自定义URL到Fileserver root

所以,我们在Fileserver使用http.StripPrefix("/tmpfiles/", ...之前修改请求url

stripPrefix文件服务器后取/而不是/static/

"/home/go/src/js" +  "/"  + "kor.js".

得到了kor.js


1
投票

我将逐一回答这两个问题。

问题1的答案1:如果您的代码编写如下:

http.Handle("/static/", http.FileServer(http.Dir("static"))

你的根文件夹是%GOPATH%/src/project_name/static/。当您访问localhost:8080/static时,URL /static将被转发到http.FileServer()返回的处理程序。但是,根文件夹中没有名为static的目录或文件。

问题2的答案2:一般情况下,如果删除/static,则无法访问http.StripPrefix()文件夹。但是,如果您有一个名为static的目录或文件,则可以使用URL localhost:8080:/static访问它(完全不是您想要的根目录)。

顺便说一句,如果您的网址不是以/static开头,则无法访问任何内容,因为http.ServeMux不会重定向您的请求。

© www.soinside.com 2019 - 2024. All rights reserved.