Go 中的'http:写入超过声明的 Content-Length”错误
php小编新一今天将为大家介绍一种常见的错误,即在Go语言中出现的“http:写入超过声明的Content-Length”错误。当我们在使用Go语言编写HTTP请求时,有时会遇到这个错误。这个错误的原因是我们在请求头中声明的Content-Length与实际发送的请求体长度不一致。接下来,我们将详细解释这个错误的产生原因以及如何解决它。
问题内容
我正在尝试 Go 并编写了一个应用程序来管理由工作协程处理的 HTTP 请求队列。
并发的东西似乎工作正常,但在发送回 http 响应时出现此错误:写入的内容超过声明的 Content-Length
。
完整代码如下:
package main import ( "log" "net/http" "sync" ) // Job represents a unit of work to be processed by a worker. type Job struct { r *http.Request // HTTP request to be processed w http.ResponseWriter // Response writer to send the result } // Queue manages a list of jobs to be processed by workers. type Queue struct { jobs []*Job // List of jobs in the queue mu sync.Mutex // Mutex to synchronize access to the queue cond *sync.Cond // Condition variable for signaling } var q Queue // Global instance of the queue var WORKER_POOL_SIZE = 4 // Number of workers // Push adds a job to the queue. func (q *Queue) Push(j *Job) { q.mu.Lock() defer q.mu.Unlock() q.jobs = append(q.jobs, j) q.cond.Signal() // Signal a waiting worker that a job is available log.Println("Job added to queue") } // Pop retrieves and removes a job from the queue. func (q *Queue) Pop() (*Job, bool) { q.mu.Lock() defer q.mu.Unlock() if len(q.jobs) == 0 { q.cond.Wait() // If the queue is empty, wait for a signal } job := q.jobs[0] q.jobs = q.jobs[1:] log.Println("Job removed from queue") return job, true } // handler adds a job to the queue. func handler(w http.ResponseWriter, r *http.Request) { // Create a job with the request and response. job := &Job{r, w} // Push the job onto the queue. q.Push(job) log.Println("Received request and added job to queue") } // init initializes the condition variable and starts worker goroutines. func init() { q.cond = sync.NewCond(&q.mu) for i := 0; i < WORKER_POOL_SIZE; i++ { go worker() } } // worker processes jobs from the queue. func worker() { for { job, ok := q.Pop() if ok { log.Println("Worker processing job") doWork(job) } } } // doWork simulates processing a job and sends a response. func doWork(job *Job) { // Extract the "Name" parameter from the request query. name := job.r.URL.Query().Get("Name") // Check if the name is not empty. if name != "" { // Send the name as the response. _, err := job.w.Write([]byte("Hello, " + name)) if err != nil { log.Println("Error writing response:", err) } log.Println("Response sent: Hello,", name) } else { // If the "Name" parameter is missing or empty, send an error response. http.Error(job.w, "Name parameter is missing or empty", http.StatusBadRequest) log.Println("Error: Name parameter is missing or empty") } } func main() { http.HandleFunc("/addJob", handler) log.Println("Server started and listening on :8080") err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("Error starting server:", err) } }
知道如何解决这个问题吗?另外,由于我对 go 中的并发性很陌生,你认为它可以改进吗?谢谢!
解决方法
根据 http.Handler
文档:
您的 handler
正在将请求/编写器推送到队列中,然后返回。这意味着您在处理程序返回后尝试写入 ResponseWriter
,违反了上述规定(由于没有同步,写入也可能实际发生在 return
之前或同时发生)。
有很多方法可以解决这个问题;一种技术是:
// Job represents a unit of work to be processed by a worker. type Job struct { r *http.Request // HTTP request to be processed w http.ResponseWriter // Response writer to send the result done chan struct{} // Closed when write competed } ... func handler(w http.ResponseWriter, r *http.Request) { // Create a job with the request and response. job := &Job{r, w, make(chan struct{})} // Push the job onto the queue. q.Push(job) log.Println("Received request and added job to queue") <-job.done // Wait until job has been processed } ... // worker processes jobs from the queue. func worker() { for { job, ok := q.Pop() if ok { log.Println("Worker processing job") doWork(job) close(job.done) // Notify requester that we are done } } }
这实际上取决于要求。一个常见的解决方案是仅使用通道(处理程序将请求发送到通道,多个工作人员从同一通道接收)。
以上是Go 中的'http:写入超过声明的 Content-Length”错误的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Go爬虫Colly中的Queue线程问题探讨在使用Go语言的Colly爬虫库时,开发者常常会遇到关于线程和请求队列的问题。�...

Go语言中用于浮点数运算的库介绍在Go语言(也称为Golang)中,进行浮点数的加减乘除运算时,如何确保精度是�...

Go语言中字符串打印的区别:使用Println与string()函数的效果差异在Go...

Go语言中使用RedisStream实现消息队列时类型转换问题在使用Go语言与Redis...

GoLand中自定义结构体标签不显示怎么办?在使用GoLand进行Go语言开发时,很多开发者会遇到自定义结构体标签在�...

Go语言中哪些库是大公司开发或知名开源项目?在使用Go语言进行编程时,开发者常常会遇到一些常见的需求,�...

Go语言中结构体定义的两种方式:var与type关键字的差异Go语言在定义结构体时,经常会看到两种不同的写法:一�...
