search
HomeBackend DevelopmentGolanggolang request redirection problem (redundant error)

golang 请求重定向问题(多余的错误)

When using golang to make network requests, you may occasionally encounter request redirection problems. This problem may be caused by redundant errors. PHP editor Xigua will tell you how to solve this problem to ensure the smooth progress of network requests. Let’s take a look!

Question content

I'm getting a very strange behavior from golang.

I want to do something with a post request and then redirect the request. Depends on random factors...whether it works or not.

When it doesn't work, I get this error:

"http: redundant response. WriteHeader call from..."

The deeper the function, the less likely the redirection will work.

  • As far as I know, I only redirected once (or zero times...)
  • I don't write the header before redirecting.
  • The only thing I did to the writer before redirecting was put it into a map.

I don't want to copy all the code here, so I'll summarize it.

The handler handles POST requests, passing the request data in a map named demand.

Then parse the request to get the form value and save it into demand It is sent to the channel.

The demand graph is passed from the channel to the following function:

func answer_login(demand map[string]any) map[string]any {
    writer := demand["writer"].(http.ResponseWriter)
    request := demand["request"].(*http.Request)
    http.Redirect(writer, request, "/", 302) // <- if it is here it works (at95 %)
    // some mundane code (printing stuff, really)
    .
    .
    .
    // http.Redirect(writer, request, "/", 302) // <- if it is here it works (only at 20 %)
    ...

If I press F5, it eventually redirects correctly. I tried simply writing something in writer.Write([]byte("same issues")), same issue.

I'm on Linux and have tried different browsers.

Question: Is this a (known) bug?

Is there any solution?

(Force writing to client)

Thank you

Solution

I finally understood the problem and found a solution.
question:

Therefore, writer requests are processed and redirected in a different scope function than the actual processing function. and when the actualhandling function ends. Certain contextual factors cause a writer request to expire: you can no longer redirect or respond to the request. This is what is written in the documentation:

https://pkg.go.dev/net/http p>

One possible explanation for why it works sometimes is... maybe the "channel transfer, processing and redirection" happens fast enough (sometimes) and the actual handler function hasn't been closed yet .

Blocking handler functions before processing data defeats the purpose of parallel asynchronous processing. So I ended up nesting everything inside a handler function.
Smart people are welcome to correct me or share better explanations about context and ResponseWriters.

The above is the detailed content of golang request redirection problem (redundant error). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Type Assertions and Type Switches with Go InterfacesType Assertions and Type Switches with Go InterfacesMay 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Using errors.Is and errors.As for Error Inspection in GoUsing errors.Is and errors.As for Error Inspection in GoMay 02, 2025 am 12:11 AM

Go language error handling becomes more flexible and readable through errors.Is and errors.As functions. 1.errors.Is is used to check whether the error is the same as the specified error and is suitable for the processing of the error chain. 2.errors.As can not only check the error type, but also convert the error to a specific type, which is convenient for extracting error information. Using these functions can simplify error handling logic, but pay attention to the correct delivery of error chains and avoid excessive dependence to prevent code complexity.

Performance Tuning in Go: Optimizing Your ApplicationsPerformance Tuning in Go: Optimizing Your ApplicationsMay 02, 2025 am 12:06 AM

TomakeGoapplicationsrunfasterandmoreefficiently,useprofilingtools,leverageconcurrency,andmanagememoryeffectively.1)UsepprofforCPUandmemoryprofilingtoidentifybottlenecks.2)Utilizegoroutinesandchannelstoparallelizetasksandimproveperformance.3)Implement

The Future of Go: Trends and DevelopmentsThe Future of Go: Trends and DevelopmentsMay 02, 2025 am 12:01 AM

Go'sfutureisbrightwithtrendslikeimprovedtooling,generics,cloud-nativeadoption,performanceenhancements,andWebAssemblyintegration,butchallengesincludemaintainingsimplicityandimprovingerrorhandling.

Understanding Goroutines: A Deep Dive into Go's ConcurrencyUnderstanding Goroutines: A Deep Dive into Go's ConcurrencyMay 01, 2025 am 12:18 AM

GoroutinesarefunctionsormethodsthatrunconcurrentlyinGo,enablingefficientandlightweightconcurrency.1)TheyaremanagedbyGo'sruntimeusingmultiplexing,allowingthousandstorunonfewerOSthreads.2)Goroutinesimproveperformancethrougheasytaskparallelizationandeff

Understanding the init Function in Go: Purpose and UsageUnderstanding the init Function in Go: Purpose and UsageMay 01, 2025 am 12:16 AM

ThepurposeoftheinitfunctioninGoistoinitializevariables,setupconfigurations,orperformnecessarysetupbeforethemainfunctionexecutes.Useinitby:1)Placingitinyourcodetorunautomaticallybeforemain,2)Keepingitshortandfocusedonsimpletasks,3)Consideringusingexpl

Understanding Go Interfaces: A Comprehensive GuideUnderstanding Go Interfaces: A Comprehensive GuideMay 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

Recovering from Panics in Go: When and How to Use recover()Recovering from Panics in Go: When and How to Use recover()May 01, 2025 am 12:04 AM

Use the recover() function in Go to recover from panic. The specific methods are: 1) Use recover() to capture panic in the defer function to avoid program crashes; 2) Record detailed error information for debugging; 3) Decide whether to resume program execution based on the specific situation; 4) Use with caution to avoid affecting performance.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software