登录
首页 >  Golang >  Go问答

地图价值的消失:原因分析

来源:stackoverflow

时间:2024-03-12 11:45:26 313浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《地图价值的消失:原因分析》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在使用映射将随机字符串键存储到 *os.file 对象。用户将上传一个文件,我想在全局地图中保留对该文件的引用,以便稍后删除它。

我有一个 http 处理程序来处理上传,最后,我将一个随机密钥从操作系统 uuidgen 映射到 *os.file 类型的“logbu​​ndlefile”。

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

完成后,您将被重定向到此 sessionhandler。它将检查正文中的 id 是否有效,即映射到 *os.file。 “ok”布尔值总是返回 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)
    }
}

这是打印的输出。在 uploadhandler 中,我们可以看到有一个映射到非 nil *os.file 的字符串键。

但在会话处理程序中,相同的字符串键映射到 nil *os.file。我不知道发生了什么。

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:  Type: *os.File

解决方案


这是因为在uploadhandler中,id变量包含换行符。如果我们仔细查看日志,我们可以看到它。不知何故 type: string 文本打印在第二行。

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

idstr 进行修剪操作应该可以解决问题。

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

理论要掌握,实操不能落!以上关于《地图价值的消失:原因分析》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>