duanbanzhi4419 2014-09-12 08:40
浏览 85
已采纳

golang上传文件err运行时错误索引超出范围

I've put together a golang func that takes an uploaded file and saves it to folder. Just before os.Create() I am getting the following error :

http: panic serving [::1]:64373: runtime error: index out of range

My golang function is:

func webUploadHandler(w http.ResponseWriter, r *http.Request) {

 file, header, err := r.FormFile("file") // the FormFile function takes in the POST input id file

 if err != nil {
    fmt.Fprintln(w, err)
    return
 }
 defer file.Close()

 // My error comes here

 messageId := r.URL.Query()["id"][0]
 out, err := os.Create("./upload/" + messageId + ".mp3")

 if err != nil {
    fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
    return
 }
 defer out.Close()

 // write the content from POST to the file
 _, err = io.Copy(out, file)
 if err != nil {
    fmt.Fprintln(w, err)
 }

 fmt.Fprintf(w,"File uploaded successfully : ")
 fmt.Fprintf(w, header.Filename)

}

any ideas? much appreciate

  • 写回答

1条回答 默认 最新

  • douweida2669 2014-09-12 08:44
    关注

    You should at least check if r.URL.Query()["id"] has actually one element.

    If len(r.URL.Query()["id"]), you could consider not accessing the index 0.

    Easier, Ainar-G suggests in the comments to use the Get() method

    Get gets the first value associated with the given key.
    If there are no values associated with the key, Get returns the empty string.
    To access multiple values, use the map directly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler