~/Concurrent Request Handling in Golang

Mar 17, 2021


Golang uses goroutines and channels to handle many concurrent requests efficiently.

To serve concurrent HTTP requests, use the net/http package. The default http.Server handles each Request in its own goroutine.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, world!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Each connection is managed by a new goroutine, so requests run in parallel. For advanced concurrency, launch goroutines yourself or use sync.WaitGroup or worker pools.

Learn more about concurrency in Go at the Concurrency Patterns in Go blog post.

Tags: [golang] [concurrency]