• golang: multiple http.writeHeader calls


    背景:
    golang的http服务,读取文件,提供给client下载时候。
    出现 multiple http.writeHeader calls 错误。

    func DownloadFile(w http.ResponseWriter, r *http.Request, sequence uint64, userid string) {
        userkey := userid
        filename := r.FormValue("filename")
        if len(userkey) <= 0 || len(filename) <= 0 {
            //........
        }
        fp := fmt.Sprintf("%s%s/%s", g_sc.Rootdir, userkey, filename)
        fd, err := os.Open(fp)
        if err == nil {
            defer fd.Close()
            buf, err := ioutil.ReadAll(fd)
            if err != nil {
                //.........
            } else {
                size := len(buf)
                w.Header().Add("Content-Length", fmt.Sprintf("%d", size))
                fmt.Fprint(w, string(buf))
            }
        }
    }

    问题出现在这几行代码:

    size := len(buf)
    w.Header().Add("Content-Length", fmt.Sprintf("%d", size))
    fmt.Fprint(w, string(buf))

     
    可以做如下修改:
     
    buf := new(bytes.Buffer)
    buf.Write(...)
     
    if err {
      // you can use http.Error here, no response has been written yet
      http.Error(w, err.String, http.StatusInternalServerError)
      return
    }
     
    if err := buf.WriteTo(w); err != nil {
      log.Printf("WriteTo: %v", err)
      // you can not use http.Error here anymore. So just log the message (e.g. "broken pipe...")
    }
     或者注释这两行代码
     //size := len(buf)
     //w.Header().Add("Content-Length", fmt.Sprintf("%d", size))
    fmt.Fprint(w, string(buf))
     
     
  • 相关阅读:
    IntelliJ IDEA 自定义 Generate POJOs.groovy 生成 POJO
    MyBatisPlus入门
    Angular中内置模块和自定义模块
    Angular跳转传值(get,动态路由,js)
    Angular路由配置
    Angular数据请求(get,post)
    Angular父子组件之间通讯传值
    Angular双向数据绑定
    Angular项目分析
    Angular环境搭建
  • 原文地址:https://www.cnblogs.com/zhangqingping/p/4300808.html
Copyright © 2020-2023  润新知