Serve linked css and js with Go net/http

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

Serve linked css and js with Go net/http

问题

我无法使用链接的CSS和脚本文件使net/http服务HTML文件。

在我的项目文件夹结构中,我有以下文件:

site/lib/ratchet/css/ratchet.css
site/lib/ratchet/js/ratchet.js

在这个index.html文件中,我已经包含了两个文件:

<link href="../lib/ratchet/css/ratchet.css" rel="stylesheet">

<script src="../lib/ratchet/js/ratchet.js"></script>

用于服务的Go函数是:

func index(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "/Users/faruk/dev/otp/site/src/index.html")
}

在main()函数中:

r.HandleFunc("/", index).
	Methods("GET")

我使用了gorilla/mux。

我可以在浏览器中查看它,但只有HTML。两个链接的文件返回404错误。

无法使用http.ServeFile自动解析链接的CSS和JS文件来服务index.html或类似文件吗?
在Go的net/http中,有什么标准的方法来服务HTML文件?

英文:

I cannot make net/http serve html file with the linked css and script file.

I have

site/lib/ratchet/css/ratchet.css
site/lib/ratchet/js/ratchet.js

in my project folder structure, and

site/src/index.html

and in this index.html I have included two files

&lt;link href=&quot;../lib/ratchet/css/ratchet.css&quot; rel=&quot;stylesheet&quot;&gt;

&lt;script src=&quot;../lib/ratchet/js/ratchet.js&quot;&gt;&lt;/script&gt;

and Go function to serve it is:

func index(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, &quot;/Users/faruk/dev/otp/site/src/index.html&quot;)
}

in main():

r.HandleFunc(&quot;/&quot;, index).
	Methods(&quot;GET&quot;)

I make use of gorilla/mux above.

I can view it from the browser but with only html. the two linked file has been given 404.

Can not http.ServeFile intended for this purpose to automatically resolve the linked css and js files to serve the index.html or alike files?
What is the standard way to serve an html file in Go net/http?

答案1

得分: 1

你需要设置一个文件服务器来提供lib目录中的文件。Go语言的http包中有一个文件服务器。

func init() {
    http.Handle("/lib/", http.FileServer(http.Dir("/Users/faruk/dev/otp/site/")))
}
英文:

You need to setup a file server to serve the files found in your lib directory. Go has a file server in the http package

func init() {
    http.Handle(&quot;/lib/&quot;, http.FileServer(http.Dir(&quot;/Users/faruk/dev/otp/site/&quot;)))
}

huangapple
  • 本文由 发表于 2014年9月25日 04:52:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/26026259.html
匿名

发表评论

匿名网友

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

确定