You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go http.FileServer 配置非根路径时出现意外404错误的问题求助

Go http.FileServer 配置非根路径时出现意外404错误的问题求助

我现在遇到一个头疼的问题,想在Go里启动两个文件服务器:一个用来提供ui文件夹里的index.html,另一个用来提供files文件夹里的各类静态文件,代码写出来是这样的:

package main

import (
	"log"
	"net/http"
)

func main() {
	srv := http.NewServeMux()

	// 第一个文件服务器:处理根路径请求
	uiServer := http.FileServer(http.Dir("./ui"))
	srv.Handle("/", uiServer)

	// 第二个文件服务器:处理/files路径请求
	staticFilesServer := http.FileServer(http.Dir("./files"))
	srv.Handle("/files", staticFilesServer)

	if err := http.ListenAndServe(":8080", srv); err != nil {
		log.Fatal(err)
	}
}

两个文件服务器的定义方式完全一致,第一个(uiServer)能正常响应请求,但第二个访问localhost:8080/files的时候却一直返回404错误。

为了排查问题,我把第一个正常工作的文件服务器去掉,简化成了下面的代码:

package main

import (
	"log"
	"net/http"
)

func main() {
	srv := http.NewServeMux()

	staticFilesServer := http.FileServer(http.Dir("./files"))
	srv.Handle("/files", staticFilesServer)

	if err := http.ListenAndServe(":8080", srv); err != nil {
		log.Fatal(err)
	}
}

结果访问localhost:8080/files依然是404。可如果把Handle的路径改成/,它就能正常读取files文件夹里的内容了,但这不是我想要的效果。我就是想弄明白,到底能不能在非根路径下用FileServer提供服务?如果可以的话,正确的配置方式应该是什么样的?

我的文件夹结构如下:

  • main.go
  • ui
    • index.html
  • files
    • file1.txt
    • file2.csv
    • file3.img

备注:内容来源于stack exchange,提问作者Mohammad Reza Karimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 08:45:29