Go fix "Connection reset by Peer" or "EOF" issue

Source: Internet
Author: User
Tags connection reset
This is a creation in Article, where the information may have evolved or changed.

Problem

I have written an HTTP client program code as follows:

// create a requestreq, err := http.NewRequest(method, url, body)if err != nil {    return nil, err}// send JSON to firebaseresp, err := http.DefaultClient.Do(req)if err != nil {    return nil, err}if resp.StatusCode != http.StatusOK {    return nil, fmt.Errorf("Bad HTTP Response: %v", resp.Status)}defer resp.Body.Close()b, err := ioutil.ReadAll(resp.Body)if err != nil {    return nil, err}

The following error occurs almost every time after you send the server multiple times:

ERROR 10108 socket.cpp:985 0x7fffe81426e0 recvmsg(62, 1): (104, "Connection reset by peer")WARN 10108 server.cpp:467  0x7fffe80abd60-2 Unexpected SocketException

Reason

Before you solve the problem, you need to know some background knowledge about how go implements connection: There are two processes, one for reading and one for writing (that is, Readloop and Writeloop). In most cases, Readloop detects if the socket is closed and shuts down connection as appropriate. If a new request arrives before Readloop detects a shutdown, it generates an EOF error and interrupts execution instead of closing the previous request. This is also the case when I execute a new connection, when the execution of this program exits, and again when the server does not know I have closed the connection, so the connection is reset, if I do not quit the program and use the For loop multiple send, the old connection is not closed, the new connection will be reported EOF.

Solution

To add a property setting to req:

req.Close = true

It prevents the connection from being reused and effectively prevents the problem, which is the short connection to HTTP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.