重定向静态文件请求

huangapple go评论89阅读模式
英文:

Redirect requests for static files

问题

我正在尝试提供一个静态的HTML文件,这个文件中包含指向其他资源的脚本标签。我想将HTML文件从一个目录中提供,但是将对资源的请求重定向到另一个目录。这是我目前的设置:

// server.go
import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "path"
    "time"
)

func handle(w http.ResponseWriter, r *http.Request) {
    lp := path.Join("./", "index.html")
    fmt.Println(lp)
    tmpl, err := template.ParseFiles(lp)
    if err != nil {
        log.Fatal(err)
    }
    tmpl.ExecuteTemplate(w, "index", nil)
}

func main() {
    fs := http.FileServer(http.Dir("../../app_assets/"))
    http.Handle("/assets", fs)
    http.HandleFunc("/static/", handle)

    fmt.Println("Go Server listening on port 8000")
    http.ListenAndServe(":8000", nil)
}

这是我的模板:

<!-- index.html -->
{{define "index"}}
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="assets/css/libs.css" type="text/css" />
</head>

<body>
<script type="text/javascript" src="assets/js/libs.js"></script>

<h1> Hello </h1>
</body>
</html>
{{end}}

我能够从localhost:8000/static/提供index文件,但是资源请求没有指向两级上的assets文件夹(../../)。我做错了什么?

注意:

当加载libs.js时,我在控制台中得到以下错误:

Uncaught SyntaxError: Unexpected token <

这让我相信对libs.js文件的请求被重定向到了HTML标记。

这是怎么发生的?

注意2:

当我浏览对libs.js的请求结果时,我看到的是HTML标记。即使使用了下面建议的StripPrefix方法。我做错了什么?

英文:

I'm trying to serve a static html file, and this file has script tags that point to other resources. I want to serve the html file from one directory but then redirect requests for assets to another directory. This is how I'm setting it up now:

// server.go
import (
    &quot;fmt&quot;
    &quot;html/template&quot;
    &quot;log&quot;
    &quot;net/http&quot;
    &quot;path&quot;
    &quot;time&quot;
)

func handle(w http.ResponseWriter, r *http.Request) {
    lp := path.Join(&quot;./&quot;, &quot;index.html&quot;)
    fmt.Println(lp)
    tmpl, err := template.ParseFiles(lp)
    if err != nil {
        log.Fatal(err)
    }
    tmpl.ExecuteTemplate(w, &quot;index&quot;, nil)
}

func main() {
    fs := http.FileServer(http.Dir(&quot;../../app_assets/&quot;))
    http.Handle(&quot;/assets&quot;, fs)
    http.HandleFunc(&quot;/static/&quot;, handle)

    fmt.Println(&quot;Go Server listening on port 8000&quot;)
    http.ListenAndServe(&quot;:8000&quot;, nil)
}

Here is my template:

&lt;!-- index.html --&gt;
{{define &quot;index&quot;}}
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot; /&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;assets/css/libs.css&quot; type=&quot;text/css&quot; /&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;assets/js/libs.js&quot;&gt;&lt;/script&gt;

&lt;h1&gt; Hello &lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;
{{end}}

I'm able to serve the index file from localhost:8000/static/, but asset requests are not going to the assets folder two levels up (../../). What am I doing wrong?

NOTE:

I'm getting this error in the console when libs.js is loaded:

Uncaught SyntaxError: Unexpected token &lt;

This leads me to believe that the request for the libs.js file is being redirected to the html markup.

How is this happening?

NOTE 2:

When I browse the result of the request for libs.js, I see the html markup. Even after using StripPrefix as advised below. What am I doing wrong?

答案1

得分: 0

所以我知道这有点令人困惑,但你想将fs := http.FileServer(http.Dir("../../assets/"))更改为fs := http.FileServer(http.Dir("../.."))

原因是路径“assets”已经在请求中指定,所以按照你的写法,实际上指向的是../../assets/assets/*

希望这能帮到你!

哦,为了防止另一个错误,Handle()函数的路径应该以斜杠结尾。我差点忘记提醒你这一点。

编辑

为了适应你的其他需求(使用某种重定向),你需要使用http.StripPrefix处理程序。https://golang.org/pkg/net/http/#StripPrefix

对于你的用例,你可以使用以下代码准备服务器:

fs := http.FileServer(http.Dir("../../app_assets"))
http.Handle("/assets/", http.StripPrefix("/assets/", fs))

这样可以实现文件系统服务的URL重写。

英文:

So I know it's a bit confusing, but you want to change fs := http.FileServer(http.Dir(&quot;../../assets/&quot;)) to be fs := http.FileServer(http.Dir(&quot;../..&quot;))

The reason is that the path for "assets" is already specified in the request so as you have it, it is really pointing to ../../assets/assets/*

Hope that helps!

oh and just to prevent another error, that Handle() functions should be written with a trailing slash in the path. I almost forgot to catch that.

EDIT

To adjust my answer for your other need (using some sort of redirect) you'd have to use the http.StripPrefix handler https://golang.org/pkg/net/http/#StripPrefix

For your use case you would prepare your server with the following code:

fs := http.FileServer(http.Dir(&quot;../../app_assets&quot;))
http.Handle(&quot;/assets/&quot;, http.StripPrefix(&quot;/assets/&quot;, fs))

This lets you do url rewrites for file system serving.

答案2

得分: 0

在你的HTML中,当你指定CSS和JS的src属性时,你使用了src=&quot;assets/js/libs.js&quot;。这使得这些文件相对于当前路径进行请求。所以请求会发送到http://localhost:8000/static/assets/js/libs.js

由于这里有/static前缀,它将由你的/static处理程序处理,因此HTML文件被提供。

要使其发送到/assets处理程序,需要在src前加上/

&lt;script type=&quot;text/javascript&quot; src=&quot;/assets/js/libs.js&quot;&gt;&lt;/script&gt;

现在服务器将在../../app_assets/assets/js/libs.js位置查找该文件。

如果你希望它是../../app_assets/js/libs.js,你可以在服务器端使用StripPrefix来从URL中去除assets部分。

fs := http.StripPrefix(&quot;/assets/&quot;, http.FileServer(http.Dir(&quot;../../app_assets/&quot;)))
http.Handle(&quot;/assets/&quot;, fs)
英文:

In your html when you specify the src attributes of your css and js you have src=&quot;assets/js/libs.js&quot;. This makes those files to be requested relative to the current path. So the request goes to http://localhost:8000/static/assets/js/libs.js.

Since this has the /static prefix it will be handled by your /static handler and hence the html file is served.

To make it go to /assets handler, specify the src with a / prefixed.

&lt;script type=&quot;text/javascript&quot; src=&quot;/assets/js/libs.js&quot;&gt;&lt;/script&gt;

Now the server will look for the file at ../../app_assets/assets/js/libs.js.

If you want it to be ../../app_assets/js/libs.js, you can use StripPrefix to take out the assets part from the url in the server.

fs := http.StripPrefix(&quot;/assets/&quot;, http.FileServer(http.Dir(&quot;../../app_assets/&quot;)))
http.Handle(&quot;/assets/&quot;, fs)

huangapple
  • 本文由 发表于 2016年3月26日 06:24:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/36229031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定