答案:使用 net/http 包可轻松实现静态文件服务器。通过 http.ServeFile 提供单个文件,或用 http.FileServer 服务整个目录,结合 http.StripPrefix 可添加路径前缀,如 /static/,并支持根路径重定向和日志输出。

用Golang实现一个简单的静态文件服务器非常直接,主要依赖标准库中的 net/http 包。你不需要引入任何第三方依赖,几行代码就能启动一个能提供静态文件的服务。
如果你只想提供某个特定文件(比如 index.html),可以这样写:
package main
import (
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.ListenAndServe(":8080", nil)
}
访问 http://localhost:8080 就会返回当前目录下的 index.html 文件。
更常见的是提供整个目录下的所有静态文件,比如前端资源(HTML、CSS、JS、图片等)。这时可以用 http.FileServer:
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
http.ListenAndServe(":8080", nil)
}
这段代码会把当前目录下 static 文件夹中的所有文件作为静态资源提供。比如:
如果你想通过某个前缀(如 /assets/)访问静态文件,可以用 http.StripPrefix:
http.Handle("/assets/", http.StripPrefix("/assets/", fs))
这样用户访问 /assets/image.png 时,服务器会从 static 目录查找 image.png。
加一点日志输出,方便调试:
package main
import (
"log"
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
// 可选:根路径重定向到 index.html
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/static/index.html", http.StatusFound)
return
}
})
log.Println("Server starting on :8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
这个版本:
以上就是如何用Golang实现一个简单的静态文件服务器的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号