在Go Web应用程序中,我有一个嵌入式FS,其中包含静态文件和模板文件.

索引函数func index(w http.ResponseWriter, r *http.Request)正在解析和执行模板.

我如何才能在/条道路上为两者服务?

GET / will serve index
GET/{anythingelse} will be served from FS

//go:embed assets
var staticFiles embed.FS

var staticFS = fs.FS(staticFiles)
htmlContent, _ := fs.Sub(staticFS, "assets")
fs := http.FileServer(http.FS(htmlContent))

mux := http.NewServeMux()
mux.Handle("GET /", fs)
mux.HandleFunc("GET /", index)

julienschmidt/httprouterrouter.NotFound.我怎样才能做到同样的事情?

推荐答案

在Go 1.22中,使用模式/{$}来匹配确切的路径/,使用模式/来匹配任何路径.

mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", index)
mux.Handle("GET /", fs)

在Go 1.22之前,请在index函数中使用if陈述:

//go:embed assets
var staticFiles embed.FS

var fs http.Handler

func index(w http.ReponseWriter, r *http.Request) {
    if r.URL.Path != "/" { 
        fs.ServeHTTP(w, r)
        return 
    }
    // insert original index code here 
}

func main() {
    staticFS := fs.FS(staticFiles)
    htmlContent, _ := fs.Sub(staticFS, "assets")
    fs = http.FileServer(http.FS(htmlContent))

    mux := http.NewServeMux()
    mux.HandleFunc("GET /", index)
    ...

Go相关问答推荐

带有Go map[字符串]字符串的持久磁盘

你能帮我优化一个golang代码关于函数CrossPointTwoRect

如何在gofr发起的服务间调用请求中添加Authorization Header?

使用Digitorus/pdfsign在GO(Golang)中签署pdf文件

MaybeReadByte对通道的使用如何在Go中提供随机行为?

由docker中的nginx提供的样式和图像在页面上不起作用

在 Go 中解组编号的 XML 标签

这是泛型的有效用例吗?

通过多阶段构建复制到 Docker 容器中时找不到文件

在密钥不存在时处理 PATCH 部分更新

判断不同 go map 类型中的重复键

整理时转换值

在 Go 中公开公共 JWK

如何将文件上传到 Google Drive,并与使用服务帐户和 Golang 的任何人共享

未定义 protoc protoc-gen-go 时间戳

转到文本/模板模板:如何根据模板本身的值数组判断值?

GoReleaser 和 ssh-agent Github 操作:为什么无法读取用户名...终端提示已禁用?

显示作为服务帐户身份验证的谷歌日历事件 - Golang App

如何在眼镜蛇(golang)中将标志作为参数传递?

如何使用带有Electron 表格 ID、Electron 表格名称、表格 ID 和值的 golang 在 googlesheet 中插入数据