net/http中 StripPrefix 详解(go 文件服务器搭建)

首先我们看下标准库文档中定义以及解释

func StripPrefix(prefix string, h Handler) Handler

StripPrefix返回一个处理器,该处理器会将请求的URL.Path字段中给定前缀prefix去除后再交由h处理。StripPrefix会向URL.Path字段中没有给定前缀的请求回复404 page not found。

// 官方提供的demo
// To serve a directory on disk (/tmp) under an alternate URL
// 在备用URL下在磁盘(/tmp)上提供目录 
// path (/tmpfiles/), use StripPrefix to modify the request
// 路径(/tmpfiles/),使用StripPrefix修改请求
// URL's path before the FileServer sees it:
// 文件服务器看到它之前的URL路径:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))

翻译过来的参数签名是这样的

http.Handle("url/Prefix", http.StripPrefix("/Prefix", http.FileServer(http.Dir("/now"))))
// 等于是访问到的url/now路径

同时 Go很轻易就可以搭建一个文件服务器

http.Handle("/", http.StripPrefix("/file", http.FileServer(http.Dir("./static"))))
// 访问 127.0.0.1:8888/file/hello -> hello world
// 文件目录
// - main.go
// - static
// -/- hello
http.ListenAndServe(":8888", nil)
posted @ 2020-11-02 15:03  Binb  阅读(1477)  评论(0编辑  收藏  举报