Golang handle static folder

情到浓时终转凉″ 提交于 2020-01-30 13:16:08

问题


I'm not able to get files placed in static folder. I'm using gorilla mux package.

main.go code:

fs := http.FileServer(http.Dir("static"))
mainRouter.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
http.Handle("/", &mainRouter)

Project structure:

static
templates
--style
--javascript
--...
main.go

When I hit index page:

loclalhost:8080/cruise_schedule

I get all stylesheets and js files, but when I jump to another page:

localhost:8080/cruise_schedule/selected_cruise/e58ed042aad24b9b87fba8917c085534

I get following errors:

Refused to apply style from 'http://localhost:8080/cruise_schedule/static/style/style.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

and:

http://localhost:8080/cruise_schedule/static/javascript/resources.js 

What should I do in order to properly serve static files?


回答1:


Your Go application is not at fault here, your generated HTML output is.

Your error message says that your sub-page tries to load its CSS from http://localhost:8080/cruise_schedule/static/..., when it actually should load from http://localhost:8080/static/.... The first URL will not serve the static file since it's not below the /static prefix, and your application will probably serve its default 404 page (presumably a text/plain page).

To solve this, I'd suggest either using absolute paths for your CSS (<link href="/static/...) or using an appropriate <base> tag.



来源:https://stackoverflow.com/questions/49198742/golang-handle-static-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!