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条)

报告相同问题?

悬赏问题

  • ¥15 ssh登录页面的问题
  • ¥60 渗透一个指定银行app,拿到客户信息,需要什么级别
  • ¥50 关于在matlab上对曲柄摇杆机构上一点的运动学仿真
  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥20 公众号如何实现点击超链接后自动发送文字
  • ¥15 用php隐藏类名和增加类名
  • ¥15 算法设计与分析课程的提问
  • ¥15 用MATLAB汇总拟合图