阻止访问的文件夹中有golang服务器
问题描述:
我在golang已经在服务器谁处理这样的文件夹路径:阻止访问的文件夹中有golang服务器
fs := http.FileServer(http.Dir("./assets"))
http.Handle("/Images/", fs)
http.ListenAndServe(":8000", nil)
但此文件夹中有士兵的图像,它不应该是可能的访问文件。那么我怎样才能保护图像访问并阻止任何人访问文件夹的内容。
一样,例如:
答
如果要阻止使用http
软件包的目录,也许这将是对你有用:
https://groups.google.com/forum/#!topic/golang-nuts/bStLPdIVM6w
package main import ( "net/http" "os" ) type justFilesFilesystem struct { fs http.FileSystem } func (fs justFilesFilesystem) Open(name string) (http.File, error) { f, err := fs.fs.Open(name) if err != nil { return nil, err } return neuteredReaddirFile{f}, nil } type neuteredReaddirFile struct { http.File } func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) { return nil, nil } func main() { fs := justFilesFilesystem{http.Dir("/tmp/")} http.ListenAndServe(":8080", http.FileServer(fs)) }
答
FileServer()的一个小包装解决了你的问题,现在你必须添加一些逻辑来进行授权,它看起来像你有独特的名字,这很好,所以我只是为你创建一个名称映射的图像名称,现在你可以添加一些更像key/store(memcached,redis)的动态。等等),希望你能按照意见
package main
import (
"log"
"net/http"
"strings"
)
// put the allowed hashs or keys here
// you may consider put them in a key/value store
//
var allowedImages = map[string]bool{
"key-abc.jpg": true,
"key-123.jpg": true,
}
func main() {
http.Handle("/Images/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// here we can do any kind of checking, in this case we'll just split the url and
// check if the image name is in the allowedImages map, we can check in a DB or something
//
parts := strings.Split(r.URL.Path, "/")
imgName := parts[len(parts)-1]
if _, contains := allowedImages[imgName]; !contains { // if the map contains the image name
log.Printf("Not found image: %q path: %s\n", imgName, r.URL.Path)
// if the image is not found we write a 404
//
// Bonus: we don't list the directory, so nobody can know what's inside :)
//
http.NotFound(w, r)
return
}
log.Printf("Serving allowed image: %q\n", imgName)
fileServer := http.StripPrefix("/Images/", http.FileServer(http.Dir("./assets")))
fileServer.ServeHTTP(w, r) // StripPrefix() and FileServer() return a Handler that implements ServerHTTP()
}))
http.ListenAndServe(":8000", nil)
}
+0
这不完全是我需要知道的但谢谢,我敢肯定有一天我会需要这个例子:) – Fantasim
你是说,你不希望人们访问同一个文件夹,这些图片,但其他文件? – xen
@xen我不想让人们访问文件夹中的文件与文件夹路径 – Fantasim
这是你的问题? https://groups.google.com/forum/#!topic/golang-nuts/bStLPdIVM6w – lofcek