dongxun6690 2017-11-30 23:02
浏览 118
已采纳

使用大猩猩/ mux使用Go服务静态文件

I'm trying to serve static files with Go, after following a few tutorials and other SO answers (here and here) I've arrived at the below code. I have researched numerous other similar questions, but the answers aren't working for me. I'm implementing my routing slightly different than most of the other questions, so I wonder if there's a subtle issue there that's causing the problem, but unfortunately my Go skills aren't polished enough to see what it is. My code is below (I've excluded the code for the handlers as it shouldn't be relevant).

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,
    },
}

main.go

...

func main() {

    router := NewRouter()

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

My file structure is setup as:

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

For some reason the browser can't access localhost:8080/static/stylesheets/index.css

  • 写回答

1条回答 默认 最新

  • duanji5116 2017-12-01 02:52
    关注

    File paths are relative to the current working directory, not to source code file that references the path.

    The application's file server configuration assumes that the app directory is the current working directory. Change directory to the app directory before running the application.

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口