douti9253 2017-01-16 19:45
浏览 46
已采纳

您如何在Golang中安全地提供文件

I'm new to developing web applications. I'm working with golang and would like to serve user uploaded files securely, such as allowing them to view their own files only.

Now I have saved those files to a local file system with random names. If I serve the entire directory, malicious users may view other users files. This sounds like a common use case, I wonder what's the best approach to deal with it?

  • 写回答

2条回答 默认 最新

  • dongzhiyong8577 2017-01-17 13:01
    关注

    This question in pretty vague and architectural decisions must be made to optimize data access and secure the files.

    However, here is a simple solution that might serve your use-case.

    package main
    
    import (
        "fmt"
        "mime"
        "net/http"
        "path/filepath"
    )
    
    //UserFilesMap is the map that contains
    var UserFilesMap map[string]FilePermission
    
    type FilePermission map[string]struct{}
    
    //FileServer is the function that serves files
    func FileServer(w http.ResponseWriter, r *http.Request) {
        //get the file path the user wants to access
        filename := r.URL.Path[9:]
        var uname, pass string
        var ok bool
        if uname, pass, ok = r.BasicAuth(); !ok {
            w.WriteHeader(http.StatusForbidden)
            return
        }
    
        if !(uname == "user" && pass == "1234") {
            w.WriteHeader(http.StatusForbidden)
            return
        }
    
        //Checking if user has permission to the file
        if _, ok := UserFilesMap[uname][filename]; !ok {
            w.WriteHeader(http.StatusForbidden)
            return
        }
    
        w.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(filename)))
        http.ServeFile(w, r, "files/"+filename)
    }
    
    func main() {
        UserFilesMap = make(map[string]FilePermission)
        // UserFilesMap["user"] = FilePermission{"xyz.txt": struct{}{}}
        UserFilesMap["user"] = FilePermission{"abc.txt": struct{}{}}
        http.HandleFunc("/getFile/", FileServer)
        if err := http.ListenAndServe(":8080", nil); err != nil {
            fmt.Println("Error in ListenAndServe")
        }
    }
    

    Here, I used a map to store the permissions of files. I would suggest you go for a SQL table instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)