【问题标题】:Cannot locate static scripts with golang server无法使用 golang 服务器定位静态脚本
【发布时间】:2015-12-03 09:11:12
【问题描述】:

我写了一个 golang 网络服务器,之前我在提供静态资源,但是在更改了我的项目结构之后,它不再有效。

这是我的项目结构

ProjectFolder/
    node_modules/
    scripts/
       test.es6.js
    server/
       handlers.go
       main.go
       routes.go
    static/
       scripts/
          test.js
          test.js.map
    Gruntfile.js
    index.html
    package.json

这是我的 index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javacript" src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script type="text/javascript" src="/static/scripts/test.js"</script>
<body>
    <div id="chart"></div>
</body>

这是我的路线。去

func NewRouter() *mux.Router {

    router := mux.NewRouter().StrictSlash(true)
    for _, route := range routes {
        router.
            Methods(route.Method).
            Path(route.Pattern).
            Name(route.Name).
            Handler(route.HandlerFunc)
    }

    for pathName, pathValue := range staticPaths {
        pathPrefix := "/" + pathName + "/"
        fmt.Println(pathPrefix)
        fmt.Println(pathValue)
        router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix, http.FileServer(http.Dir(pathValue))))
    }


    // router.PathPrefix("/static/scripts").Handler(http.FileServer(http.Dir("./static/scripts/")))
    return router
}

var staticDirectory = "/static"

var staticPaths = map[string]string{
    "scripts": staticDirectory + "/scripts/",
}

var routes = Routes{
    Route{
        "Index",
        "GET",
        "/",
        Index,
    },
}

当我点击 localhost:8200 时,我在加载 test.js 时收到 404,但 index.html 被点击。

以前,这是一个不使用 http.FileServer 来提供静态资源的问题,但我现在正在使用它。

我尝试过 index.html 中路径的其他变体

src= "static/scripts/test.js"
src= "../static/scripts/test.js"

发生了什么事?

编辑-

我已经简化了一切并尝试这样做

router.Handle("../static/scripts", http.StripPrefix("../static/scripts", http.FileServer(http.Dir("."))))

但这仍然行不通。

【问题讨论】:

  • 使用静态目录的完整路径,而不是相对路径 - 例如不是../static
  • 在你的 html 中为 javascript 使用相对路径。

标签: javascript go


【解决方案1】:

尝试以下方法:

// Create new router.
gorillaMux := mux.NewRouter()

// Match /res/ prefix to local /res/ folder.
gorillaMux.PathPrefix("/res/").Handler(http.StripPrefix("/res/", http.FileServer(http.Dir("./res/"))))

这将使http://example.com/res/js/script.js 寻找./res/js/script.js

因此,您必须在 HTML 中完全限定您的资源:@​​987654324@

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-08
    • 2018-07-15
    • 2017-12-08
    • 2017-10-10
    • 1970-01-01
    • 2021-09-07
    • 2016-10-13
    • 1970-01-01
    相关资源
    最近更新 更多