【问题标题】:Serve static files with Go using gorilla/mux使用 gorilla/mux 使用 Go 提供静态文件
【发布时间】:2017-11-30 23:02:12
【问题描述】:

在遵循一些教程和其他 SO 答案(herehere)之后,我正在尝试使用 Go 提供静态文件,我得到了以下代码。我已经研究了许多其他类似的问题,但答案对我不起作用。我实现的路由与大多数其他问题略有不同,所以我想知道是否存在导致问题的微妙问题,但不幸的是,我的 Go 技能还不够完善,无法看到它是什么。我的代码在下面(我已经排除了处理程序的代码,因为它不应该相关)。

router.go

package main

import (
    "net/http"

    "github.com/gorilla/mux"
)

func NewRouter() *mux.Router {
    router := mux.NewRouter().StrictSlash(true)

    for _, route := range routes {
        var handler http.Handler

        handler = route.HandlerFunc
        handler = Logger(handler, route.Name)

        router.
            Methods(route.Method).
            Path(route.Path).
            Name(route.Name).
            Handler(handler)
    }

    // This should work?
    fs := http.FileServer(http.Dir("./static"))
    router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

    return router
}

routes.go

package main

import (
    "net/http"

    "web-api/app/handlers"
)

type Route struct {
    Name        string
    Method      string
    Path        string
    HandlerFunc http.HandlerFunc
}

type Routes []Route

var routes = Routes{
    Route{
        "Index",
        "GET",
        "/",
        handlers.Index,
    },
    Route{
        "Login",
        "GET",
        "/login",
        handlers.GetLogin,
    },
    Route{
        "Login",
        "POST",
        "/login",
        handlers.PostLogin,
    },
}

ma​​in.go

...

func main() {

    router := NewRouter()

    log.Fatal(http.ListenAndServe(":8080", router))
}

我的文件结构设置为:

- app
    - main.go
    - router.go
    - routes.go
    - static/
        - stylesheets/
            - index.css

由于某种原因浏览器无法访问localhost:8080/static/stylesheets/index.css

【问题讨论】:

  • 您是否从app 目录运行应用程序?路径./static 是相对于当前工作目录的,而不是相对于源文件的。
  • 我是从 app 的父目录构建它,构建它 inside app 可以工作,谢谢!如果您将其保留为答案,我会将您的答案标记为正确。使用绝对路径可以让我从任何地方构建它吗?
  • 这与您构建应用程序的位置无关。这取决于您运行应用程序的当前工作目录。

标签: css go


【解决方案1】:

文件路径是相对于当前工作目录的,而不是相对于引用该路径的源代码文件。

应用程序的文件服务器配置假定app 目录是当前工作目录。在运行应用程序之前将目录更改为app 目录。

【讨论】: