栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Golang io.copy在请求正文中两次

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Golang io.copy在请求正文中两次

您不能直接执行此操作,但可以编写在io.Copy上执行哈希处理的包装器

// this works for either a reader or writer, //  but if you use both in the same time the hash will be wrong.type Hasher struct {    io.Writer    io.Reader    hash.Hash    Size uint64}func (h *Hasher) Write(p []byte) (n int, err error) {    n, err = h.Writer.Write(p)    h.Hash.Write(p)    h.Size += uint64(n)    return}func (h *Hasher) Read(p []byte) (n int, err error) {    n, err = h.Reader.Read(p)    h.Hash.Write(p[:n]) //on error n is gonna be 0 so this is still safe.    return}func (h *Hasher) Sum() string {    return hex.EnpreToString(h.Hash.Sum(nil))}func (h *UploadHandle) Read() (io.Reader, string, int64, error) {    var b bytes.Buffer    hashedReader := &Hasher{Reader: h.Contents, Hash: sha1.New()}    n, err := io.Copy(&b, hashedReader)    if err != nil {        return nil, "", 0, err    }    return &b, hashedReader.Sum(), n, nil}

//由于我完全忘记了

io.TeeReader
存在,因此根据@Dustin的评论更新了版本。

func (h *UploadHandle) Read() (io.Reader, string, int64, error) {    var b bytes.Buffer    hash := sha1.New()    n, err := io.Copy(&b, io.TeeReader(h.Contents, hash))    if err != nil {        return nil, "", 0, err    }    return &b, hex.EnpreToString(hash.Sum(nil)), n, nil}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484293.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号