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.

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

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了