gpt4 book ai didi

http - 为什么我不能将正文添加到 http 重定向?

转载 作者:IT王子 更新时间:2023-10-29 02:25:36 26 4
gpt4 key购买 nike

这是我尝试过的:

w.WriteHeader(301)
w.Write([]byte("Redirecting..."))
w.Header().Set("Location", "/myredirecturl")
w.Header().Set("Content-Length", contentLength) // I thought this might help

由于某些奇怪的原因,它不会添加 Location header 。
为什么golang的http包不能加body和重定向?

最佳答案

这记录在 net/http 中包裹:

type ResponseWriter

type ResponseWriter interface {
// Header returns the header map that will be sent by WriteHeader.
// Changing the header after a call to WriteHeader (or Write) has
// no effect.
Header() Header

// Write writes the data to the connection as part of an HTTP reply.
// If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
// before writing the data. If the Header does not contain a
// Content-Type line, Write adds a Content-Type set to the result of passing
// the initial 512 bytes of written data to DetectContentType.
Write([]byte) (int, error)

// WriteHeader sends an HTTP response header with status code.
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).
// Thus explicit calls to WriteHeader are mainly used to
// send error codes.
WriteHeader(int)
}

以上说明在调用 Write()WriteHeader() 后不能更改 Header()。您应该将代码更改为以下内容:

w.Header().Set("Location", "/myredirecturl")
w.WriteHeader(301)
w.Write('Redirecting...')

关于http - 为什么我不能将正文添加到 http 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404024/

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