Serve static files via http with go

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

Serve static files via http with go

问题

在我的HTML中,我试图使用以下方式包含JS:

<script src="/js/app.js"></script>

我还尝试了相对路径(从服务器位置):

<script src="js/app.js"></script>

以及相对于HTML文件的路径:

<script src="../js/app.js"></script>

我的文件结构如下:

-js
    app.js
-templates
    index.html
hub.go
main.go

main.go是服务器的代码:

func main() {
    http.HandleFunc("/", rootHandler)
    http.ListenAndServe(":8080", nil)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "Templates/index.html")
}

我是否遗漏了什么?我是否需要通过服务器提供CSS/JS文件?还是简单的HTML就可以工作?

英文:

In my html I'm trying to include JS using

&lt;script src=&quot;/js/app.js&quot;&gt;&lt;/script&gt;

I have also tried relative path (from server location)

&lt;script src=&quot;js/app.js&quot;&gt;&lt;/script&gt;

and relative from the html file
<script src="../js/app.js"></script>

My file structure

-js
    app.js
-templates
    index.html
hub.go
main.go

main.go is the server

func main() {
	http.HandleFunc(&quot;/&quot;, rootHandler)
	http.ListenAndServe(&quot;:8080&quot;, nil)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, &quot;Templates/index.html&quot;)
}

Am I missing something do I have to server css/js through server? or should the simple html work

答案1

得分: 12

为了通过HTTP提供文件,可以为一个目录定义一个FileServer,并使用http.Handle将其路由到例如"/assets/"。以下设置应该适用于您:

目录结构:

├── assets/
│   ├── js
│   └── css
├── templates/
└── main.go

main.go

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

func rootHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "templates/index.html")
}

在您的模板文件中:

<script src="/assets/js/app.js"></script>
英文:

To serve files via http, define a FileServer for a directory and route it to, for example, &quot;/assets/&quot; using http.Handle. <br/>Following setup should work for you:

directory structure:

├── assets/
│&#160;&#160; ├── js
│&#160;&#160; └── css
├── templates/
└── main.go

main.go

func main() {
    http.HandleFunc(&quot;/&quot;, rootHandler)
    http.Handle(&quot;/assets/&quot;, http.StripPrefix(&quot;/assets/&quot;, http.FileServer(http.Dir(&quot;assets&quot;))))
    http.ListenAndServe(&quot;:8080&quot;, nil)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, &quot;templates/index.html&quot;)
}

in your template file:

&lt;script src=&quot;/assets/js/app.js&quot;&gt;&lt;/script&gt;

huangapple
  • 本文由 发表于 2017年4月15日 19:39:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/43425594.html
匿名

发表评论

匿名网友

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

确定