gpt4 book ai didi

go - "http.FileServer(http.Dir...))"不能在单独的包中工作

转载 作者:IT王子 更新时间:2023-10-29 02:25:45 26 4
gpt4 key购买 nike

目录树:

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

这个有效:

package main

import (
"net/http"
)

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

但这会返回 404 页面未找到:

main.go:

package main

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

func main() {
web.StartHttp()
}

应用程序:

package web

import (
"fmt"
"net/http"
)

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

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

终端打印STARTHTTP - CHECK 01,所以调用了StartHttp()函数,终端要求允许传入网络连接,所以http服务器似乎在端口上监听。

是否有某种类型的上下文未传递给其他包?

最佳答案

请记住,Go 是一种编译型语言;程序所做的大部分事情都发生在运行时。

特别是,在这种情况下,对 http.Dir() 的调用发生在运行时,这意味着路径是在运行时评估的。

因为您提供的路径是相对的,所以它是相对于您运行应用程序的工作目录的。源代码所在目录与此处无关。

在对 http.Dir() 的一次调用中,您提供参数 ./web/views,但在另一次调用中,您提供参数 ./意见。事实证明,基于您执行程序的目录的正确路径是 ./web/views。当您使用错误的路径执行程序时,您会收到 404 page not found 错误,因为指定的路径在您的工作目录中不存在。

关于go - "http.FileServer(http.Dir...))"不能在单独的包中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52141282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com