gpt4 book ai didi

python/flask send_from_directory() 的 Golang 替代方案

转载 作者:数据小太阳 更新时间:2023-10-29 03:04:38 24 4
gpt4 key购买 nike

我有这个图片网址:

/book/cover/Computer_Science.png

但是图片所在的位置居然存在

/uploads/img/Computer_Science.png

我正在使用 Gin 框架。在 Gin 或内置的 Golang 函数中是否有类似 Flask 的 send_from_directory() 的命令?

如果没有,您能分享一下如何做的片段吗?

谢谢!

最佳答案

使用 Gin 的 Context.File提供文件内容。此方法内部调用 http.ServeFile内置函数。代码片段将是:

import "path/filepath"


// ...
router := gin.Default()
// ...

router.GET("/book/cover/:filename", func(c *gin.Context) {
rootDir := "/uploads/img/"
name := c.Param("filename")
filePath, err := filepath.Abs(rootDir + name)
if err != nil {
c.AbortWithStatus(404)
}

//Only allow access to file/directory under rootDir
//The following code is for ilustration since HasPrefix is deprecated.
//Replace with correct one when https://github.com/golang/dep/issues/296 fixed
if !filepath.HasPrefix(filePath, rootDir) {
c.AbortWithStatus(404)
}

c.File(filePath)
})

更新

正如 zerkms 所指出的,路径名必须在传递给 Context.File 之前被清理。代码片段中添加了简单的 sanitizer 。请适应您的需求。

关于python/flask send_from_directory() 的 Golang 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44347100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com