doufangpian5545 2019-04-26 00:26
浏览 8

我该如何优化执行哈希操作时读取的代码,并尝试重新开始重新读取它?

How do I make this not require a file seek? Basically, I am doing a hash, and then re-reading the file. This is not optimal. How can I optimize by either using TeeReader or another method to read in chunks so Hashing and Writing content can happen without duplication of reading.

Also, do I need to specify content length myself?

// PUT method
func (c *Client) PutFileOld(filename string, noLen bool) error {
    file, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer file.Close()

    hasher := md5.New()

    if _, err := io.Copy(hasher, file); err != nil {
        log.Fatal("Could not compute MD5")
    }

    // Lazy way to go back to the beginning since the reader has consumed our bytes
    // and we have to compute the hash
    file.Seek(0, 0)

    c.MD5 = hex.EncodeToString(hasher.Sum(nil)[:16])
    log.Printf("Uploading to: %s", fmt.Sprintf("%s/%s", c.baseURL, filename))
    baseURL, err := url.Parse(fmt.Sprintf("%s/%s", c.baseURL, filename))
    if err != nil {
        return err
    }

    log.Printf("MD5: %s - file: %s
", c.MD5, filename)
    req, err := http.NewRequest(http.MethodPut, baseURL.String(), bufio.NewReader(file))
    if err != nil {
        return err
    }
    req.Header.Set("Content-Type", "application/octet-stream")
    req.Header.Set("Content-Md5", c.MD5)
    fi, _ := file.Stat()

    // Not sure if this is needed, or if Go sets it automatically
    req.ContentLength = fi.Size()

    res, err := c.httpClient.Do(req)
    if err != nil {
        return err
    }

    dump, err := httputil.DumpResponse(res, true)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%q
", dump)
    c.StatusCode = res.StatusCode
    defer res.Body.Close()

    return nil
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 测距传感器数据手册i2c
    • ¥15 RPA正常跑,cmd输入cookies跑不出来
    • ¥15 求帮我调试一下freefem代码
    • ¥15 matlab代码解决,怎么运行
    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法