脚本专栏 
首页 > 脚本专栏 > 浏览文章

在go文件服务器加入http.StripPrefix的用途介绍

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

例子:

http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))

当访问localhost:xxxx/tmpfiles时,会路由到fileserver进行处理

当访问URL为/tmpfiles/example.txt时,fileserver会将/tmp与URL进行拼接,得到/tmp/tmpfiles/example.txt,而实际上example.txt的地址是/tmp/example.txt,因此这样将访问不到相应的文件,返回404 NOT FOUND。

因此解决方案就是把URL中的/tmpfiles/去掉,而http.StripPrefix做的就是这个。

补充:go语言实现一个简单的文件服务器 http.FileServer

代码如下:

package main
import (
 "flag"
 "fmt"
 "github.com/julienschmidt/httprouter"
 "log"
 "net/http"
 "strings"
 "time"
)
func main() {
 root := flag.String("p", "", "file server root directory")
 flag.Parse()
 if len(*root) == 0 {
 log.Fatalln("file server root directory not set")
 }
 if !strings.HasPrefix(*root, "/") {
 log.Fatalln("file server root directory not begin with '/'")
 }
 if !strings.HasSuffix(*root, "/") {
 log.Fatalln("file server root directory not end with '/'")
 }
 p, h := NewFileHandle(*root)
 r := httprouter.New()
 r.GET(p, LogHandle(h))
 log.Fatalln(http.ListenAndServe(":8080", r))
}
func NewFileHandle(path string) (string, httprouter.Handle) {
 return fmt.Sprintf("%s*files", path), func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
 http.StripPrefix(path, http.FileServer(http.Dir(path))).ServeHTTP(w, r)
 }
}
func LogHandle(handle httprouter.Handle) httprouter.Handle {
 return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
 now := time.Now()
 handle(w, r, p)
 log.Printf("%s %s %s done in %v", r.RemoteAddr, r.Method, r.URL.Path, time.Since(now))
 }
}

准备测试文件

在go文件服务器加入http.StripPrefix的用途介绍

编译运行

在go文件服务器加入http.StripPrefix的用途介绍

用浏览器访问

在go文件服务器加入http.StripPrefix的用途介绍

在go文件服务器加入http.StripPrefix的用途介绍

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

上一篇:go语言实现sftp包上传文件和文件夹到远程服务器操作
下一篇:golang实现ftp实时传输文件的案例
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网