douyan8070 2016-03-03 19:44
浏览 59
已采纳

转至http:/ static和/ static /的区别

I have a terrible confusion concerning http.FileServer and slashes.

I need to serve a script to a html page. In the directory I'm working I have the page index.html and I have a static directory with myscript.js inside of it.

First question: is it correct to write

<script src="/static/myscript.js"></script>

? I have also seen src="static/myscript.js" and I don't know if there is a reason for using one or the other (but I guess it influences the handler we have to write on the server).

Let's suppose we settle for the first version. Second question: on the server side, I want to register the handler for directory static. Inspired by this example, I do:

fs := http.FileServer(http.Dir("./static"))
http.Handle("/static", http.StripPrefix("/static", fs))

but I get a 404. However, if I use:

fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

with the ending slashes, it works fine!

I'm really new to web servers, so I would appreciate any explanation that includes what are the actual addresses passed around by functions. For example, I don't know (and I can't figure it out from the net/http documentation ) what is the address that is passed to the handler when serving a /static request. I guess it's /static/myscript.js since we are using http.StripPrefix but I have no actual way of proving it.

  • 写回答

1条回答 默认 最新

  • duanbiaoshu2021 2016-03-03 22:44
    关注

    http.Handle("/static", http.StripPrefix("/static", fs)) registers a fixed name pattern.

    http.Handle("/static/", http.StripPrefix("/static/", fs)) registers a rooted subtree pattern.

    The former matches only requests where URL.path = "/static". The latter matches every path that starts with "/static/". The 404 indicates that it could not match any pattern for the given request, not that the requested file wasn't found. (It does not even get to execute the FileServer's handler!)


    And to answer your first question:

    <script src="/static/myscript.js"></script>
    

    URLs starting with a slash / are absolute. That means it does not matter on what page you are, it will always append to the domain name e.g. example.com/some/page + /static/myscript.js = example.com/static/myscript.js

    <script src="static/myscript.js"></script>
    

    Is a relative path. That means it will be appended to URL of the currently visited page e.g. example.com/some/page + static/myscript.js = example.com/some/page/static/myscript.js

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效