Go 原生 http FileServer 的使用

25 min read

Go 的 http 包中提供了一个基本的文件服务器函数 FileServer,可以方便地将指定目录下的文件发送给客户端。以下是使用 FileServer 的示例:

package main

import (
    "log"
    "net/http"
)

func main() {
    // 将 ./public 目录下的文件暴露出去
    fs := http.FileServer(http.Dir("./public"))
    
    // 将文件服务器 handler 注册到 /static 路径下
    http.Handle("/static/", http.StripPrefix("/static/", fs))
    
    // 启动 http server
    log.Fatal(http.ListenAndServe(":8080", nil))
}

这段代码会启动一个 http 服务器,监听地址为 :8080。当访问 http://localhost:8080/static/somefile.txt 时,服务器会将 ./public/somefile.txt 文件发送给客户端。

在上述示例中,我们使用了 http.Dir 函数来初始化文件服务器的目录,它的参数是一个字符串类型的路径。这里我们使用了相对路径,也可以使用绝对路径。

http.FileServer 函数会返回一个 Handler 类型的对象,它可以作为参数传递给 http.Handle 函数来注册一个处理器,最后将注册好的 http.Handler 传递给 http.ListenAndServe 函数启动 http server。

如果要在服务器中隐藏目录列表,可以使用 http.FileServer 的第二个参数 http.Dir.Hidden 设置为 true

fs := http.FileServer(http.Dir("./public"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

// 隐藏 /static 目录下的目录列表
http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
    http.Error(w, "Forbidden", http.StatusForbidden)
})