2017-06-03 10 views
0

私はこの画像のURLを持っている:Golangパイソン/フラスコsend_from_directoryための代替()

/book/cover/Computer_Science.png 

が、画像の位置は、実際に私はジンフレームワークを使用してい

/uploads/img/Computer_Science.png 

下に存在します。 Flaskのsend_from_directory()のようなコマンドがGinまたは内蔵のGolang関数にありますか?

もしあなたがそれを行う方法のスニペットを共有することができますか?

ありがとうございます!

答えて

2

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それを渡す前にを消毒する必要があります。シンプルなサニタイザーがスニペットに追加されています。あなたのニーズに適応してください。

+0

結果正規化されたパスが予想されるディレクトリ内にあるかどうかを確認する必要があると言えるでしょう。そうでなければ、/book/cover/../../../../../ ../../ etc/passwd' – zerkms

+1

@zerkmsありがとう、ありがとうございます。私は答えを更新しました。 – putu

関連する問題