prevent access to files in folder with a golang server

三世轮回 提交于 2019-12-24 00:16:24

问题


I've a server in golang who handle folder path like that :

fs := http.FileServer(http.Dir("./assets"))
http.Handle("/Images/", fs)
http.ListenAndServe(":8000", nil)

But in this folder there are privates images, and it shouldn't be possible to access files. So how can i secure image access and prevent anybody to access content of folder.

like that for example :


回答1:


If you want to block a directory using http package, maybe this will be useful to you :

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))
}



回答2:


A little wrapper over FileServer() solves your problem, now you have to add some sort of logic to do Authorization, it looks like you have unique names, that's good, so I just filter the image name for you creating a map of names, now you can add something more dynamic like a key/store(memcached, redis. etc.) Hope you can follow the comments

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



来源:https://stackoverflow.com/questions/40716869/prevent-access-to-files-in-folder-with-a-golang-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!