这是我尝试过的:
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/