atye
atye

Reputation: 109

Why is a map value becoming non-existent?

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\n", idStr, idStr)
    log.Printf("val: %v Type: %T\n\n", 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\n", id, id)
    log.Printf("val: %v Type: %T\n", 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

Upvotes: 0

Views: 88

Answers (1)

novalagung
novalagung

Reputation: 11502

It's because in the uploadHandler, the id variable contains newline. If we take a look closely on the log we can see it. somehow Type: string text is printed in the 2nd line.

2019/08/27 19:49:49 ID: BA06C157-451E-48B5-85F9-8069D9A4EFCE // <-- newline
 Type: string
2019/08/27 19:49:49 ID: BA06C157-451E-48B5-85F9-8069D9A4EFCE Type: string

Putting trim operation on the idStr should solve the problem.

idStr := strings.TrimSpace(string(id[:]))

Upvotes: 1

Related Questions