使用golang服务器阻止访问文件夹中的文件

时间:2016-11-21 09:34:27

标签: go server

我在golang中处理文件夹路径的服务器是这样的:

  <cf:enumeration name="EmployeeStatus" namespace="DemoLoadByEnum">
    <cf:enumerationValue name="Employeed" />
    <cf:enumerationValue name="Released" />
  </cf:enumeration>

但是在这个文件夹中有私有图像,并且不可能访问文件。那么我如何保护图像访问并防止任何人访问文件夹的内容。

就像那样:

enter image description here

2 个答案:

答案 0 :(得分:2)

FileServer()上的一个小包装器解决了你的问题,现在你必须添加某种逻辑来进行授权,看起来你有独特的名字,这很好,所以我只是过滤图像名称你创建了一个名字地图,现在你可以添加一些更像动态的东西(如密钥/商店(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)
}

https://play.golang.org/p/ehrd_AWXim

答案 1 :(得分:1)

如果您想使用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))
}