Table of Contents
Question content
Solution
Home Backend Development Golang 'http: writing exceeds declared Content-Length' error in Go

'http: writing exceeds declared Content-Length' error in Go

Feb 09, 2024 pm 12:50 PM
go language

Go 中的“http:写入超过声明的 Content-Length”错误

php editor Shinichi will introduce to you today a common error, that is, the "http: writing exceeds the declared Content-Length" error that occurs in the Go language. When we write HTTP requests using Go language, we sometimes encounter this error. The reason for this error is that the Content-Length we declared in the request header is inconsistent with the length of the request body actually sent. Next, we will explain in detail why this error occurs and how to solve it.

Question content

I am experimenting with Go and wrote an application to manage a queue of HTTP requests handled by a worker coroutine.

The concurrency stuff seems to be working fine, but I get this error when sending back the http response: More content was written than the declared Content-Length.

The complete code is as follows:

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)
    }
}

Copy after login

Any idea how to solve this problem? Also, since I'm very new to concurrency in go, do you think it can be improved? Thanks!

Solution

According to http.Handler document:

Your handler is pushing requests/writers to the queue and back. This means that you are trying to write to the ResponseWriter after the handler has returned, violating the above (since there is no synchronization, the write may also actually happen before or at the same time as the return).

There are many ways to solve this problem; one technique is:

// 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
        }
    }
}
Copy after login

It really depends on the requirements. A common solution is to just use channels (a handler sends the request to the channel and multiple workers receive from the same channel).

The above is the detailed content of 'http: writing exceeds declared Content-Length' error in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

How to solve the problem that custom structure labels in Goland do not take effect? How to solve the problem that custom structure labels in Goland do not take effect? Apr 02, 2025 pm 12:51 PM

Regarding the problem of custom structure tags in Goland When using Goland for Go language development, you often encounter some configuration problems. One of them is...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

See all articles