


php editor Xinyi will answer a question about golang for you: Why is the content length automatically added when processing an http request if the content of the ResponseWriter does not exceed 2kb? In fact, this is because in the HTTP protocol, the content length is a required field, which is used to tell the client the length of data to receive in order to correctly parse the response. Even if the content length is small, the server still needs to provide this field to ensure a complete communication process. In this way, the client can correctly receive and parse the content, ensuring the integrity and accuracy of requests and responses.
Question content
func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var content string ... w.Write([]byte(content)) }
If len(content) content-length will be automatically added to the response. And if it exceeds 2048, there is no content-length
, and transfer-encoding: chunked
will be added.
I can't find where to determine 2048.
I'm asking for help finding the source code where 2048 is determined.
Solution
Let's take a look at the documentation for this function in the http.responsewriter
interface, for reference only Clarity:
[i] If the total size of all written data is below a few kb and there are no flush calls, the content-length header is automatically added.
First, we can see that the number may not be exactly 2048 (2 kb), but is within the "few kb" range we would expect. Secondly, we can see that this behavior is related to the flush
method, which is documented in the flusher
interface:
flush sends all buffered data to the client.
The flusher interface is implemented by responsewriter and allows http handlers to flush buffered data to the client.
The default http/1.x and http/2 responsewriter implementations support flushers, but responsewriter wrappers may not. Handlers should always test this functionality at runtime.
As it says, your responsewriter
may support data buffering and flushing. This means that when you write data to the response writer, it is not immediately transferred over the connection. Instead, it is written to the buffer first. Each time the buffer becomes too full for more writes, the entire buffer will be transferred when the servehttp
method returns. This ensures that even if you do a lot of tiny writes, the data is transferred efficiently and all the data is eventually transferred. You can also choose to proactively clear the buffer at any time using the flush
method. http headers must be sent before the body data, but they do not need to be sent before the buffer is first emptied.
Putting all this together, you'll see that if the total amount written does not exceed the buffer size, and we never call flush
, then there is no need to send headers until all data is ready , at this point we know the length of the content. If the total amount written is greater than the buffer size, the headers must be sent before the content length is known, so responsewriter
cannot determine it automatically.
This is at net/http/server.go
. Specifically, here is the declaration of the buffer size, and nchunkedwriter
:
// This should be >= 512 bytes for DetectContentType, // but otherwise it's somewhat arbitrary. const bufferBeforeChunkingSize = 2048 // chunkWriter writes to a response's conn buffer, and is the writer // wrapped by the response.w buffered writer. // // chunkWriter also is responsible for finalizing the Header, including // conditionally setting the Content-Type and setting a Content-Length // in cases where the handler's final output is smaller than the buffer // size. It also conditionally adds chunk headers, when in chunking mode. // // See the comment above (*response).Write for the entire write flow. type chunkWriter struct {
Source code link for 1.19.5. Please note that the source code may change with each go version.
The above is the detailed content of If golang http ResponseWriter does not exceed 2kb, why is the content length automatically added?. For more information, please follow other related articles on the PHP Chinese website!

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
