ResponseWriter中隐含了一些坑,藏在文档注释里
WriteHeader
WriteHeader只能调用一次,否则会引起http: multiple response.WriteHeader calls
WriteHeader必须在Write()之前调用,因为在Write()调用过程中,如果发现WriteHeader没有调用过,那么它会自行写入一次200作为默认header
-
对于标准Header如ContentType,Header().Set()必须在WriteHeader/Write之前调用,否则不会生效。因为按照写入顺序,是 Header -> StatusHeader -> Body -> Trailer Header.
注释如下:// Changing the header map after a call to WriteHeader (or
// Write) has no effect unless the modified headers are
// trailers.