2016-11-21 116 views
0

我在golang已經在服務器誰處理這樣的文件夾路徑:阻止訪問的文件夾中有golang服務器

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

但此文件夾中有士兵的圖像,它不應該是可能的訪問文件。那麼我怎樣才能保護圖像訪問並阻止任何人訪問文件夾的內容。

一樣,例如:

enter image description here

+0

你是說,你不希望人們訪問同一個文件夾,這些圖片,但其他文件? – xen

+0

@xen我不想讓人們訪問文件夾中的文件與文件夾路徑 – Fantasim

+0

這是你的問題? https://groups.google.com/forum/#!topic/golang-nuts/bStLPdIVM6w – lofcek

回答

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

但我應該如何處理這一行:fs:= http.FileServer(http.Dir(「./ assets」))? ? – Fantasim

+1

我認爲你必須用'http.Dir(「./ assets」)代替'http.Dir(「/ tmp /」)'' –

+0

確定它可以正常工作,但是這個服務器上的api不再工作,所以我應該使2個服務器? – Fantasim

1

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

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

+0

這不完全是我需要知道的但謝謝,我敢肯定有一天我會需要這個例子:) – Fantasim

相關問題