我想通过在写出响应主体时对其进行哈希处理来计算响应的实体标签。到我计算实体标签时,将实体标签添加到响应标头为时已晚。我想将实体标签添加到预告片中。我看到net / http包支持编写预告片,但我不知道如何使用它们。
预告片代码位于https://golang.org/src/pkg/net/http/transfer.go中。如何在应用程序中设置预告片?
使用bytes.Buffer,然后将其包装为散列,例如:
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) }
截至目前,您无法设置预告片标头,这是一个未解决的问题。
有一种解决方法,劫持连接(来自上述问题):
// 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\r\n") // eof t.Write(buf) buf.WriteString("\r\n") // end of trailers buf.Flush() conn.Close()