为什么我的 Golang 模板没有引入外部的 JavaScript 文件?

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

Why my golang template is not picking the external javascript file?

问题

我尝试了很多来自Stack Overflow的建议,但似乎都没有起作用。我无法加载外部的js文件。

我的主要函数:

package main

import (
    "encoding/json"
    "net/http"
    "fmt"
    "github.com/gorilla/mux"
    "github.com/rs/cors"
    "text/template"
)

func GetPeopleEndpoint(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    t, _ := template.ParseFiles("index2.html")
    t.Execute(w, nil)
}

func main() {
    router := mux.NewRouter()
    people = append(people, Person{ID: "1", Firstname: "Nic", Lastname: "Raboy", Address: &Address{City: "Dublin", State: "CA"}})
    people = append(people, Person{ID: "2", Firstname: "Maria", Lastname: "Raboy"})

    fmt.Println(people)

    router.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir("."))))
    router.HandleFunc("/people", GetPeopleEndpoint)

    c := cors.New(cors.Options{
        AllowedOrigins: []string{"http://localhost:3000"},
        AllowCredentials: true,
    })

    // 插入中间件
    handler := c.Handler(router)

    // handler := cors.Default().Handler(router)
    http.ListenAndServe(":12345", handler)
}

我的所有文件都在同一个目录下。

这是我的HTML代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>

  </head>
  <body>
    This is page2

    <div id='newdiv'>

    </div>
  </body>

  <script type="text/javascript" src="app2.js">
  </script>
</html>

我得到的错误是"GET http://localhost:12345/app2.js"。我不知道我在哪里犯了错误。

英文:

I tried so many suggestions from stack overflow but none seems to work. I was not able to pick the external js file.

My main function:

package main

import(
    &quot;encoding/json&quot;
    &quot;net/http&quot;
    &quot;fmt&quot;
    &quot;github.com/gorilla/mux&quot;
    &quot;github.com/rs/cors&quot;
    &quot;text/template&quot;
)  
    
func GetPeopleEndpoint(w http.ResponseWriter, req *http.Request) {
    w.Header().Set(&quot;Content-Type&quot;, &quot;text/html&quot;)
    t, _ := template.ParseFiles(&quot;index2.html&quot;)
    t.Execute(w, nil)
}

func main() {
    router := mux.NewRouter()
    people = append(people, Person{ID: &quot;1&quot;, Firstname: &quot;Nic&quot;, Lastname: &quot;Raboy&quot;, Address: &amp;Address{City: &quot;Dublin&quot;, State: &quot;CA&quot;}})
    people = append(people, Person{ID: &quot;2&quot;, Firstname: &quot;Maria&quot;, Lastname: &quot;Raboy&quot;})
    
    fmt.Println(people)
    
    router.Handle(&quot;/files/&quot;, http.StripPrefix(&quot;/files/&quot;, http.FileServer(http.Dir(&quot;.&quot;))))
    router.HandleFunc(&quot;/people&quot;, GetPeopleEndpoint)
    
    c := cors.New(cors.Options{
        AllowedOrigins: []string{&quot;http://localhost:3000&quot;},
        AllowCredentials: true,
    })
    
    // Insert the middleware
    handler := c.Handler(router)
    
    //  handler := cors.Default().Handler(router)
    http.ListenAndServe(&quot;:12345&quot;, handler)
}

All my files are in the same directory.

Here is my html:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;title&gt;&lt;/title&gt;

  &lt;/head&gt;
  &lt;body&gt;
    This is page2

    &lt;div id=&#39;newdiv&#39;&gt;

    &lt;/div&gt;
  &lt;/body&gt;

  &lt;script type=&quot;text/javascript&quot; src=&quot;app2.js&quot;&gt;
  &lt;/script&gt;
&lt;/html&gt;

The error I'm getting is "GET http://localhost:12345/app2.js". I don't know where I'm doing the mistake.

答案1

得分: 5

这行代码的意思是:

router.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir("."))))

意味着以"/files/"开头的请求将从当前目录中的文件中提供服务,并且会去掉"/files/"前缀。所以,如果你想要当前目录中的一个名为app2.js的文件,那么URL必须是/files/app2.js

router.Handle定义了哪个处理程序将处理给定的路径。在这种情况下,路径是/files/。由于有尾部斜杠,对于以/files/开头的所有URL,将使用相同的处理程序。

http.StripPrefix是一个处理程序的包装器。它接收传入的请求,去掉给定的前缀(在这种情况下是/files/),从URL路径中删除它,然后将请求传递给传递给StripPrefix的处理程序。

http.FileServerhttp.FileSystem中提供文件服务,这里由http.Dir提供。http.Dir公开目录中的文件,这里是当前工作目录(".")。

因此,总体上来说:以/files/开头的请求将去掉/files/部分,然后在当前工作目录中查找剩下的文件路径,如果找到,就会提供服务。所以,/files/app2.js将提供./app2.js。你的HTML必须引用/files/app2.js,而不是app.js

英文:

This line:

router.Handle(&quot;/files/&quot;, http.StripPrefix(&quot;/files/&quot;, http.FileServer(http.Dir(&quot;.&quot;))))

Means that requests coming in for URLs under "/files/" will be served from files on disk in the current directory, with the "/files/" prefix removed.
So if you want a file in the current directory named app2.js, then the URL must be /files/app2.js.

router.Handle defines what handler will handle a given path. In this case, that path is /files/. Because of the trailing slash, the same handler will be used for all URLs beginning with /files/.

http.StripPrefix is a handler wrapper. It takes the incoming request, strips off the given prefix (in this case, /files/), removes it from the URL path, and then passes the request on to the handler passed to StripPrefix.

http.FileServer serves files out of a http.FileSystem, in this case provided by http.Dir. http.Dir exposes the files in a directory, in this case the current working directory (&quot;.&quot;).

So, in total: requests beginning with /files/, will have the /files/ part removed, then whatever is left, that file path will be looked for in the current working directory, and if it is found, it will be served. So, /files/app2.js will serve ./app2.js. Your HTML must reference /files/app2.js, not app.js.

答案2

得分: 0

假设你有以下目录结构:

<src-dir>
   static
   templates
   ...

并且你使用http.StripPrefix映射处理程序

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

将这一行更新为-

<script type="text/javascript" src="/static/app2.js"></script>

现在你可以通过http://localhost:12345/static/app2.js访问该文件。

英文:

Let's say you have directory structure:

&lt;src-dir&gt;
   static
   templates
   ...

And you map handler you're using http.StripPrefix

router.Handle(&quot;/static/&quot;, http.StripPrefix(&quot;/static/&quot;, http.FileServer(http.Dir(&quot;static&quot;))))

Update this line to-

&lt;script type=&quot;text/javascript&quot; src=&quot;/static/app2.js&quot;&gt;&lt;/script&gt;

Now you can access the file via http://localhost:12345/static/app2.js

答案3

得分: 0

http.FileServer(http.Dir("."))通常是一个不好的主意,因为它不仅会暴露你的.js文件,还会暴露你的.go文件,使得你的代码可以通过http请求可见。例如,http://localhost:12345/main.go会使浏览器将你的源代码作为文本传送。

最佳实践应该是将静态文件(js、css、html等)收集到单独的目录中,或者只放在一个目录中,比如一个"resources"包。

然后尝试使用以下代码:

http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir("resources"))))

这段代码将完成工作,并允许你通过"/files"前缀的URL访问所有位于"/resources"下的文件。例如:
http://localhost:12345/files/app2.js

英文:

Writing http.FileServer(http.Dir(&quot;.&quot;)) is generally a bad idea because it will expose not only your .js files but also you .go files, making you code visible via http requests. For example http://localhost:12345/main.go will make the browser deliver your source code as text.

The best practice should be to collect your static files (js, css, html...) in seperated directories, or just in one, like for example a "resources" package.

Try then with

http.Handle(&quot;/files/&quot;, http.StripPrefix(&quot;/files/&quot;, http.FileServer(http.Dir(&quot;resources&quot;))))

This code will do the work and allow you to access all your files that are under /resources with the url prefix /files. For example:
http://localhost:12345/files/app2.js

huangapple
  • 本文由 发表于 2017年6月21日 04:30:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/44662456.html
匿名

发表评论

匿名网友

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

确定