package main
import (
"fmt"
"net/http"
"sync"
)
func server(done chan bool, wg *sync.WaitGroup) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
})
fmt.Println("SERVER...")
http.ListenAndServe("localhost:8080", nil)
done <- true
wg.Done()
}
func main() {
done := make(chan bool)
wg := &sync.WaitGroup{}
wg.Add(2)
go server(done, wg)
go func() {
for d := range done {
fmt.Println(d)
}
}()
wg.Wait()
}
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() {
wg.Add(1)
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.
content_copy
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.
Thanks!
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.