What is causing the "Connection reset by peer" error in the Go server?

Issue

I have written a basic web server in Go, but it can’t seem to handle any requests properly and instead all I get is "Recv failure: Connection reset by peer".

I’m happy that the server does indeed start and stop correctly, and I can see it listening on port 8080 that I’ve configured. I’ve also ruled out issues with parsing the YAML config file – it’s definitely getting getting parsed in to http.Server{}.

I’m not really sure what else to check, and struggling to find anything that’s pointing me in the right direction.

I’ll also apologise in advance, as I know I’m pasting a large amount of code below, but I really don’t know what and where the error is coming from.

Given that the server is running, when I hit the "/" endpoint/route, I’d expect to get "Hello from Go!" returned back.

directory structure

❯ tree . | grep -iE 'cmd|server.go|go.mod|go.sum|server.yaml'
├── cmd
│   └── server.go
├── go.mod
├── go.sum
└── server.yaml

server.go

package main

import (
    "context"
    "errors"
    "fmt"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"

    "gopkg.in/yaml.v3"
)

type Config struct {
    Port            string `yaml:"Port"`
    ReadTimeout     int    `yaml:"ReadTimeout"`
    WriteTimeout    int    `yaml:"WriteTimeout"`
    IdleTimeout     int    `yaml:"IdleTimeout"`
    ShutdownTimeout int    `yaml:"ShutdownTimeout"`
    ErrorLog        string `yaml:"ErrorLog"`
}

func main() {
    if len(os.Args) != 2 {
        log.Fatal("Missing arguments")
    }

    configFile, err := os.Open(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    defer configFile.Close()

    // TODO: Implement a custom ServeMux + routes

    serverConfig := Config{}
    yamlDecoder := yaml.NewDecoder(configFile)
    err = yamlDecoder.Decode(&serverConfig)
    if err != nil {
        log.Fatal(err)
    }

    errorLogFile, err := os.OpenFile(serverConfig.ErrorLog, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
    if err != nil {
        log.Fatal(err)
    }
    defer errorLogFile.Close()
    errorLog := log.New(errorLogFile, "ERROR : ", log.LstdFlags|log.Lshortfile)

    server := &http.Server{
        Addr:         fmt.Sprintf(":%s", serverConfig.Port),
        ReadTimeout:  time.Duration(serverConfig.ReadTimeout),
        WriteTimeout: time.Duration(serverConfig.WriteTimeout),
        IdleTimeout:  time.Duration(serverConfig.IdleTimeout),
        ErrorLog:     errorLog,
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello from Go!")
    })

    log.Println("Starting the server...")
    go func() {
        err := server.ListenAndServe()
        if !errors.Is(err, http.ErrServerClosed) {
            log.Fatal(err)
        }
        log.Println("Stopped serving new connections")
    }()
    log.Println("Server started")

    sigChan := make(chan os.Signal, 1)
    signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
    <-sigChan

    ctx, shutdown := context.WithTimeout(context.Background(), time.Duration(serverConfig.ShutdownTimeout)*time.Second)
    defer shutdown()

    err = server.Shutdown(ctx)
    if err != nil {
        log.Fatal(err)
    }
    log.Println("Server gracefully stopped")
}

error message

❯ curl -v localhost:8080/
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
>
* Recv failure: Connection reset by peer
* Closing connection 0
curl: (56) Recv failure: Connection reset by peer

Solution

As mentioned in the comments, the issue is related to the timeout values being so short – 5 nanoseconds each. This is because time.Duration is represented as the elapsed time between two instants as an int64 nanosecond count. So I needed to convert that in to seconds, to get what I was expecting.

From the docs:

"A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years."

Reference

Solution:

server := &http.Server{
    Addr:         fmt.Sprintf(":%s", serverConfig.Port),
    ReadTimeout:  time.Duration(serverConfig.ReadTimeout) * time.Second,
    WriteTimeout: time.Duration(serverConfig.WriteTimeout) * time.Second,
    IdleTimeout:  time.Duration(serverConfig.IdleTimeout) * time.Second,
    ErrorLog:     errorLog,
}

Answered By – Sam Wood

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.