>  기사  >  백엔드 개발  >  Go 웹 엔드포인트에서 정적 index.html 파일을 찾을 수 없습니다.

Go 웹 엔드포인트에서 정적 index.html 파일을 찾을 수 없습니다.

WBOY
WBOY앞으로
2024-02-09 11:18:171015검색

Go Web端点找不到静态index.html文件

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 웹 엔드포인트에서 정적 index.html 파일을 찾을 수 없습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 stackoverflow.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제