using http to host css, js files

1,971 views
Skip to first unread message

kevin

unread,
Oct 20, 2010, 3:05:13 AM10/20/10
to golang-nuts
I'm running a webserver on my computer using go's http package. This
is only intended to only be used locally, so I'm not worried about
security. I haven't done much on the web before, and I'm trying to
serve js and css files using this server. I'm getting the following
error when I try to include one of these files in a page that I load
from the server: "Resource interpreted as stylesheet but transferred
with MIME type text/html."

What I'm doing right now is adding a handler to an included folder:
http.HandleFunc("/inc/", SP_SERVE.SourceHandler)

And the handler:
func SourceHandler(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
fmt.Fprintf(w, "%v", err)
}
}()

fmt.Println("load source:", r.URL.Path[1:])
f, err := os.Open(r.URL.Path[1:], os.O_RDONLY, 0644)
if err != nil { panic(err) }

b := new(bytes.Buffer)
b.ReadFrom(f)

fmt.Fprintf(w, b.String())
}

and then in the html:
<script type="text/javascript" language="javascript" src="inc/
DataTables-1.7.3/media/js/jquery.dataTables.min.js"></script>

When I type in the local url: "http://localhost:8080/inc/
DataTables-1_7_3/media/js/jquery.dataTables.min.js" I can see the file
displayed correctly.

Thanks for any help.

Aleksandar Radulovic

unread,
Oct 20, 2010, 6:42:31 AM10/20/10
to golang-nuts
Hi,

Seems like you need to set the content-type header correctly when
serving .js files with your server. For Javascript it should be
"text/javascript". Same goes for css files, content-type should be
"text/css".

Try to see which headers are sent from your go server with the curl command:

$ curl -v http://localhost:8080/inc/DataTables-1_7_3/media/js/jquery.dataTables.min.js

Post the headers so we can inspect it further..

Regards,
-alex.

--
a lex 13 x
http://www.a13x.info

David Roundy

unread,
Oct 20, 2010, 8:17:22 AM10/20/10
to kevin, golang-nuts
You aren't setting the Content-Type at all, you need something like:

w.SetHeader("Content-Type", "text/html")

(only with the appropriate content types, I just copied from my code,
which happened to be html)

David

--
David Roundy

Russ Cox

unread,
Oct 20, 2010, 11:12:09 AM10/20/10
to kevin, golang-nuts
you can set the mime type.
or you can let the library do it for you:

func SourceHandler(w http.ResponseWriter, r *http.Request) {

http.ServeFile(w, r, r.URL.Path[1:])
}
http.HandleFunc("/inc/", SourceHandler)

or just:

http.Handle("/inc/", http.FileServer(".", "/"))

russ

kevin

unread,
Oct 20, 2010, 10:27:41 PM10/20/10
to golang-nuts
Thanks. Using http.ServeFile was the simplest option, so I went with
that. It's working well.
Reply all
Reply to author
Forward
0 new messages