duanfu3634 2019-08-28 00:24
浏览 64
已采纳

为什么地图值不存在?

I am using a map to store random string keys to *os.File objects. Users will be uploading a file and I want to hold a reference to the file in a global map so I can delete it later.

I have an http handler to process the upload and at the end, I map a random key from the OS uuidgen to "logBundleFile" which is type *os.File.

var db = map[string]*os.File{}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(5 << 30)
    file, handler, err := r.FormFile("file")
    if err != nil {
        log.Fatalf("Error retrieving the file: %v", err)
        return
    }
    defer file.Close()

    logBundleFile, err := ioutil.TempFile("", handler.Filename)
    if err != nil {
        log.Fatal(err)
    }
    defer logBundleFile.Close()

    fileBytes, err := ioutil.ReadAll(file)
    if err != nil {
        log.Fatalf("Error reading file: %v", err)
    }
    logBundleFile.Write(fileBytes)

    id, err := exec.Command("uuidgen").Output()
    idStr := string(id[:])
    //id := "1"
    if err != nil {
        log.Fatal(err)
    }
    db[idStr] = logBundleFile
    log.Printf("ID: %v Type: %T
", idStr, idStr)
    log.Printf("val: %v Type: %T

", db[idStr], db[idStr])
    http.Redirect(w, r, fmt.Sprintf("/%s", idStr), http.StatusMovedPermanently)
}

Once that is done, you get redirected to this sessionHandler. It will check if the ID in the body is valid, i.e, mapped to a *os.File. The "ok" bool is always returning false.

func sessionHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]
    log.Printf("ID: %v Type: %T
", id, id)
    log.Printf("val: %v Type: %T
", db[id], db[id])
    if val, ok := db[id]; ok {
        w.Write([]byte(fmt.Sprintf("Session %s %v", id, val)))
    } else {
        http.Redirect(w, r, "/", http.StatusMovedPermanently)
    }
}

Here is an output from the prints. In the uploadHandler, we can see that we have a string key mapped to a non-nil *os.File.

But in the session handler, the same string key maps to a nil *os.File. I don't know what is going on.

2019/08/27 19:49:49 ID: BA06C157-451E-48B5-85F9-8069D9A4EFCE
 Type: string
2019/08/27 19:49:49 val: &{0xc000160120} Type: *os.File

2019/08/27 19:49:49 ID: BA06C157-451E-48B5-85F9-8069D9A4EFCE Type: string
2019/08/27 19:49:49 val: <nil> Type: *os.File
  • 写回答

1条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 Unity 怎么创建树形菜单
      • ¥15 使用DWY100k数据集对UEA进行测试,出现报错:IndexError: index 125000 is out of bounds for axis 0 with size 95500
      • ¥15 前端vue实现根据图片url生成pdf文件
      • ¥15 RfidReader资源Q个
      • ¥20 user-agent是否是唯一的,有没有可能相同
      • ¥15 关于#开会#的问题,如何解决?(语言-c++)
      • ¥15 关于#二十四点问题#的问题
      • ¥15 运行kitex的demon出错(求大家解决)
      • ¥15 开发一个类似 typora 这样的软件需要多少钱?
      • ¥15 clearcase7.0安装包