douzhi7754 2018-09-02 21:50
浏览 402
已采纳

“ http.FileServer(http.Dir…))”在单独的程序包中不起作用

Directory tree:

.
├── main.go
└── web
    ├── app.go
    └── views
        ├── index.html
        └── js
            └── app.jsx

This works:

package main

import (
    "net/http"
)

func main() {
    http.Handle("/", http.FileServer(http.Dir("./web/views")))
    http.ListenAndServe(":3000", nil)
}

But this returns 404 page not found:

main.go:

package main

import (
    "{dir with main.go}/web"
)

func main() {
    web.StartHttp()
}

app.go:

package web

import (
    "fmt"
    "net/http"
)

func StartHttp() {
    fmt.Println("STARTHTTP - CHECK 01")

    http.Handle("/", http.FileServer(http.Dir("./views")))
    http.ListenAndServe(":3000", nil)
}

The terminal prints STARTHTTP - CHECK 01, so the StartHttp() function is called, and the terminal asks to allow incoming network connections, so the http server seems to be listening on the port.

Is there some type of context not being passed to the other package?

  • 写回答

2条回答 默认 最新

  • duanke1286 2018-09-02 22:21
    关注

    Remember that Go is a compiled language; most everything the program does happens at runtime.

    In particular, in this case, the call to http.Dir() happens at runtime, and that means that the path is evaluated at runtime.

    Because the path you have given is relative, it is therefore relative to the working directory from which you run the application. The directory in which the source code resided is not relevant here.

    In one invocation to http.Dir() you give the argument ./web/views, but in the other, you give the argument ./views. It turns out that the correct path based on the directory from which you executed the program was ./web/views. When you execute the program with the wrong path, you get 404 page not found errors because the path specified did not exist in your working directory.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择