在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相关问答推荐

正在使用terratest执行terraform脚本测试,但遇到错误退出状态1

CGO Linux到Windows交叉编译中的未知类型名称

[0]Func()as";请勿比较哨兵类型

使用ciph.AEAD.Seal()查看内存使用情况

关于如何使用 Service Weaver 设置多个不同侦听器的问题

有没有办法让sqlc生成可以使用pgxpool的代码

Kafka golang 生产者在错误后更改分区计数

是否需要手动调用rand.Seed?

使用Goldmark在golang中添加ChildNode会导致堆栈溢出

将 firestoreinteger_value转换为整数

在 .go 文件中运行一个函数和在 Go 模板中调用它有什么区别?

当函数返回一个函数时,为什么 Go 泛型会失败?

如何为导入的嵌入式 struct 文字提供值?

如何在自定义验证函数中获取 struct 名称

为什么 reflect.TypeOf(new(Encoder)).Elem() != reflect.TypeOf(interfaceVariable)?

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

不理解切片和指针

如何迭代在泛型函数中传递的片的并集?

Golang LinkedList 删除第一个元素

如何动态解析 Go Fiber 中的请求正文?