gpt4 book ai didi

go - 如何在 Go 服务器中设置 HTTP 尾部?

转载 作者:IT王子 更新时间:2023-10-29 01:59:49 29 4
gpt4 key购买 nike

我想通过对写出的响应主体进行哈希处理来计算响应的实体标签。当我计算实体标签时,将实体标签添加到响应 header 已经太晚了。我想将实体标签添加到预告片中。我看到 net/http 包支持编写预告片,但我不知道如何使用它们。

预告片代码在https://golang.org/src/pkg/net/http/transfer.go中.如何从我的应用程序设置预告片?

最佳答案

2021 answer (or really go1.5+)

您需要在第一次 Write 之前预先设置尾部标题名称,然后您可以稍后添加标题。

例如(复制自 https://pkg.go.dev/net/http#example-ResponseWriter-Trailers ):

// Before any call to WriteHeader or Write, declare
// the trailers you will set during the HTTP
// response. These three headers are actually sent in
// the trailer.
w.Header().Set("Trailer", "AtEnd1, AtEnd2")
w.Header().Add("Trailer", "AtEnd3")

w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
w.WriteHeader(http.StatusOK)

w.Header().Set("AtEnd1", "value 1")
io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
w.Header().Set("AtEnd2", "value 2")
w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.

原始答案(

使用 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)
}

截至目前,您无法设置预告片标题,有一个开放的 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\r\n") // eof
t.Write(buf)
buf.WriteString("\r\n") // end of trailers
buf.Flush()
conn.Close()

关于go - 如何在 Go 服务器中设置 HTTP 尾部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26081673/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com