
php小编香蕉发现,在使用Go语言开发Web端应用时,有时会遇到一个常见的问题:当我们尝试访问Web端点时,却收到一个404错误,提示找不到静态index.html文件。这个问题可能会让开发者感到困惑,特别是对于初学者来说。那么,我们应该如何解决这个问题呢?接下来,我们将详细介绍解决方案,帮助你顺利解决这个问题。
这是我的代码:
package main
import (
"fmt"
"log"
"net/http"
)
const customport = "3001"
func main() {
fileserver := http.fileserver(http.dir("./static"))
port:= fmt.sprintf(":%s", customport)
http.handle("/", fileserver)
fmt.printf("starting front end service on port %s", port)
err := http.listenandserve(port, nil)
if err != nil {
log.panic(err)
}
}
顶级文件夹是 microservices 并设置为 go 工作区。该网络服务将是众多服务之一。它位于以下文件夹中:
microservices
|--frontend
|--cmd
|--web
|--static
|--index.html
|--main.go我位于顶级微服务文件夹中,我以以下方式启动它:go run ./frontend/cmd/web。它启动正常,没有错误。但是当我转到 chrome 并输入 http://localhost:3001 时,我得到 404 页面未找到。即使 http://localhost:3001/index.html 也会给出 404 页面未找到。我刚刚学习 go,不知道为什么找不到 ./static 文件夹?
立即学习“前端免费学习笔记(深入)”;
根据您的命令,路径必须是./frontend/cmd/web/static,而不仅仅是./static。那不是便携式的;路径随工作目录而变化。
考虑嵌入静态目录。否则,您必须使路径可配置(标志、环境变量等)
嵌入的缺点是您必须在对静态文件进行任何更改后重建程序。
您还可以使用混合方法。如果设置了标志(或其他),则使用它从磁盘提供服务,否则使用嵌入式文件系统。该标志在开发过程中很方便,并且嵌入式文件系统使部署变得容易,因为您只需复制程序二进制文件。
package main
import (
"embed"
"flag"
"io/fs"
"net/http"
"os"
)
//go:embed web/static
var embeddedAssets embed.FS
func main() {
var staticDir string
flag.StringVar(&staticDir, "static-dir", staticDir, "Path to directory containing static assets. If empty embedded assets are used.")
flag.Parse()
var staticFS fs.FS = embeddedAssets
if staticDir != "" {
staticFS = os.DirFS(staticDir)
}
http.Handle("/", http.FileServer(http.FS(staticFS)))
// ...
}
以上就是Go Web端点找不到静态index.html文件的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号