Is it possible to write to the channel after starting http.ListenAndServe?

package main

import (

func server(done chan bool, wg *sync.WaitGroup) {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

	http.ListenAndServe("localhost:8080", nil)
	done <- true

func main() {
	done := make(chan bool)
	wg := &sync.WaitGroup{}
	go server(done, wg)
	go func() {
		for d := range done {



This method involves a WaitGroup to track the server routine and a channel to signal errors. Here’s how it works:

`Govar wg sync.WaitGroup
errChan := make(chan error)

func serveHTTP() {
err := http.ListenAndServe(“:8080”, nil)
errChan ← err // Send any error encountered by the server
wg.Done() // Signal server routine completion

func main() {
go serveHTTP()

// Your main program logic here

// Wait for server to finish (error or stop)
err := <-errChan
wg.Wait() // Ensure server routine finishes completely

if err != nil {
fmt.Println(“Error:”, err)
} else {
fmt.Println(“Server stopped successfully”)

Use code with caution.


In this example, the serveHTTP function runs as a goroutine (asynchronous function). The errChan channel is used to send any error encountered by the server. The main program waits for the server routine to finish (using wg.Wait()) and then checks for errors received on the errChan.

Hi Alexcray.
In this example, errChan will only work if http.ListenAndServe returns an error. I need the channel to always be recorded.
done := make(chan bool)

Can you please be more specific on what you are trying to achieve here? ListenAndServe is a blocker and will be running forever before shutdown. If you want to pass something into the channel after starting it, you need to put it in a goroutine.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.