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

转至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

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

报告相同问题?