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!

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

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.

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

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

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

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

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

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.


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

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

Hot Article

Hot 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.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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
