golang web 静态文件
https://blog.csdn.net/whatday/article/details/109747385
这时,请求localhost:8080/static/hello.html将会返回./public/hello.html文件。 路径/static/index.html经过处理器http.StripPrefix去掉了前缀/static得到/index.html,然后又加上了http.Dir的起始目录./public得到文件最终路径./public/hello.html。
除此之外,http.FileServer还会根据请求文件的后缀推断内容类型,更全面:
-
// src/mime/type.go -
var builtinTypesLower = map[string]string{ -
".css": "text/css; charset=utf-8", -
".gif": "image/gif", -
".htm": "text/html; charset=utf-8", -
".html": "text/html; charset=utf-8", -
".jpeg": "image/jpeg", -
".jpg": "image/jpeg", -
".js": "application/javascript", -
".mjs": "application/javascript", -
".pdf": "application/pdf", -
".png": "image/png", -
".svg": "image/svg+xml", -
".wasm": "application/wasm", -
".webp": "image/webp", -
".xml": "text/xml; charset=utf-8", -
}
如果文件后缀无法推断,http.FileServer将读取文件的前 512 个字节,根据内容来推断内容类型。感兴趣可以看一下源码src/net/http/sniff.go。
http.ServeContent
除了直接使用http.FileServer之外,net/http库还暴露了ServeContent方法。这个方法可以用在处理器需要返回一个文件内容的时候,非常易用。
例如下面的程序,根据 URL 中的file参数返回对应的文件内容:
-
package main -
import ( -
"fmt" -
"log" -
"net/http" -
"os" -
"time" -
) -
func ServeFileContent(w http.ResponseWriter, r *http.Request, name string, modTime time.Time) { -
f, err := os.Open(name) -
if err != nil { -
w.WriteHeader(500) -
fmt.Fprint(w, "open file error:", err) -
return -
} -
defer f.Close() -
fi, err := f.Stat() -
if err != nil { -
w.WriteHeader(500) -
fmt.Fprint(w, "call stat error:", err) -
return -
} -
if fi.IsDir() { -
w.WriteHeader(400) -
fmt.Fprint(w, "no such file:", name) -
return -
} -
http.ServeContent(w, r, name, fi.ModTime(), f) -
} -
func fileHandler(w http.ResponseWriter, r *http.Request) { -
query := r.URL.Query() -
filename := query.Get("file") -
if filename == "" { -
w.WriteHeader(400) -
fmt.Fprint(w, "filename is empty") -
return -
} -
ServeFileContent(w, r, filename, time.Time{}) -
} -
func main() { -
mux := http.NewServeMux() -
mux.HandleFunc("/show", fileHandler) -
server := &http.Server { -
Addr: ":8080", -
Handler: mux, -
} -
if err := server.ListenAndServe(); err != nil { -
log.Fatal(err) -
} -
}
http.ServeContent除了接受参数http.ResponseWriter和http.Request,还需要文件名name,修改时间modTime和io.ReadSeeker接口类型的参数。
modTime参数是为了设置响应的Last-Modified首部。如果请求中携带了If-Modified-Since首部,ServeContent方法会根据modTime判断是否需要发送内容。 如果需要发送内容,ServeContent方法从io.ReadSeeker接口重读取内容。*os.File实现了接口io.ReadSeeker。
使用场景
Web 开发中的静态资源都可以使用http.FileServer来处理。除此之外,http.FileServer还可以用于实现一个简单的文件服务器,浏览或下载文件:
-
package main -
import ( -
"flag" -
"log" -
"net/http" -
) -
var ( -
ServeDir string -
) -
func init() { -
flag.StringVar(&ServeDir, "sd", "./", "the directory to serve") -
} -
func main() { -
flag.Parse() -
mux := http.NewServeMux() -
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(ServeDir)))) -
server := &http.Server { -
Addr: ":8080", -
Handler: mux, -
} -
if err := server.ListenAndServe(); err != nil { -
log.Fatal(err) -
} -
}
在上面的代码中,我们构建了一个简单的文件服务器。编译之后,将想浏览的目录作为参数传给命令行选项,就可以浏览和下载该目录下的文件了:
$ ./main.exe -sd D:/code/golang
可以将端口也作为命令行选项,这样做出一个通用的文件服务器,编译之后就可以在其它机器上使用了