登录
首页 >  Golang >  Go问答

index.html文件在嵌入式目录中的位置是什么?

来源:stackoverflow

时间:2024-03-06 22:03:27 343浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《index.html文件在嵌入式目录中的位置是什么?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我正在尝试将静态站点(和 spa)嵌入到我的 go 代码中。我的项目的高层结构是

.
├── web.go
└── spa/
    └── index.html

我的目的是让 http://localhost:8090/ 服务 index.html

执行此操作的相关代码是

//go:embed spa
var spa embed.FS

log.Info("starting api server")
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.FS(spa)))
log.Fatal(http.ListenAndServe(":8090", r))

当访问http://localhost:8090/时,我得到

  • 带有单个链接 spa 的目录列表页面
  • 点击此链接后,我会看到 404 页面未找到

我应该如何设置?


正确答案


使用 gorilla mux,您需要指定路径前缀:

package main

import (
    "embed"
    "fmt"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

//go:embed spa
var spa embed.fs

func main() {
    log.println("starting api server")
    r := mux.newrouter()
    r.pathprefix("/spa/").handler(http.stripprefix("/", http.fileserver(http.fs(spa))))
    log.fatal(http.listenandserve(":8090", r))
}

这会将向 /spa/* 的请求路由到处理程序。然后,您必须去除前缀 /,因为 spa 目录的内容具有 spa/ 前缀,而没有前导 /

b, _ := spa.readfile("spa/index.html")
    fmt.println(string(b)) // file contents

总结一下:

http://localhost:8090/spa/index.html 被路由到 r.pathprefix("/spa/") 处理程序。虽然路线是 /spa/index.html,但去掉第一个 / 会得到 spa/index.html,这最终与嵌入变量中的文件路径匹配。

嵌入目录中的文件路径以 //go:embed 指令中使用的路径为前缀。 index.html 的嵌入式文件系统路径是​spa/index.html

Create a sub file systemspa 目录为根目录并为该文件系统提供服务。 index.html在子文件系统中的路径为index.html

sub, _ := fs.sub(spa, "spa")
r.handle("/", http.fileserver(http.fs(sub)))

https://pkg.go.dev/io/fs#Sub

Run an example on the playground

此方法适用于任何多路复用器,包括 gorilla mux。这是 gorilla 的代码,其中 r*mux.router

sub, _ := fs.Sub(spa, "spa")
r.PathPrefix("/").Handler(http.FileServer(http.FS(sub)))

Run an example on the playground

好了,本文到此结束,带大家了解了《index.html文件在嵌入式目录中的位置是什么?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>