duanlvxi8652 2014-09-28 04:39
浏览 10
已采纳

如何在Go服务器中设置HTTP预告片?

I want to compute the entity tag for a response by hashing the response body as it's written out. By the time I compute the entity tag, it's too late to add the entity tag to the response header. I'd like to add the entity tag to the trailer. I see the the net/http package has support for writing trailers, but I cannot figure out how to use them.

The trailer code is in https://golang.org/src/pkg/net/http/transfer.go. How do I set a trailer from my application?

  • 写回答

1条回答 默认 最新

  • dtcaw02086 2014-09-28 04:59
    关注

    use a bytes.Buffer, and wrap it to hash in the same time, something like:

    type HashedBuffer struct {
        h hash.Hash
        b bytes.Buffer
    }
    
    func NewHashedBuffer(h hash.Hash) *HashedBuffer {
        return &HashedBuffer{h: h}
    }
    
    func (h *HashedBuffer) Write(p []byte) (n int, err error) {
        n, err = h.b.Write(p)
        h.h.Write(p)
        return
    }
    
    func (h *HashedBuffer) Output(w http.ResponseWriter) {
        w.Header().Set("ETag", hex.EncodeToString(h.h.Sum(nil)))
        h.b.WriteTo(w)
    }
    
    //handler
    func Handler(w http.ResponseWriter, r *http.Request) {
        hb := NewHashedBuffer(sha256.New())
        hb.Write([]byte("stuff"))
        hb.Output(w)
    }
    

    As of right now, you can't set trailer headers, there's an open issue about it.

    There's a workaround, hijack the connection (from the above issue) :

    // TODO: There's no way yet for the server to set trailers
    // without hijacking, so do that for now, just to test the client.
    // Later, in Go 1.4, it should be be implicit that any mutations
    // to w.Header() after the initial write are the trailers to be
    // sent, if and only if they were previously declared with
    // w.Header().Set("Trailer", ..keys..)
    w.(Flusher).Flush()
    conn, buf, _ := w.(Hijacker).Hijack()
    t := Header{}
    t.Set("Server-Trailer-A", "valuea")
    t.Set("Server-Trailer-C", "valuec") // skipping B
    buf.WriteString("0
    ")            // eof
    t.Write(buf)
    buf.WriteString("
    ") // end of trailers
    buf.Flush()
    conn.Close()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效