Home >Backend Development >Golang >How Can I Detect When a Go HTTP Server Starts Listening on a Specific Port?

How Can I Detect When a Go HTTP Server Starts Listening on a Specific Port?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 09:09:12660browse

How Can I Detect When a Go HTTP Server Starts Listening on a Specific Port?

Detecting HTTP Server Listening Status in Go

When working with HTTP servers in Go, it may be necessary to monitor the server's status, specifically when it starts listening on a specific port. As the given question highlights, the standard net/http library does not offer an explicit option to track this event.

In this situation, you can directly manage the listening process and signal the listening status:

package main

import (
    "log"
    "net/http"
)

func main() {
    listener, err := net.Listen("tcp", ":8080")
    if err != nil {
        log.Fatal(err)
    }

    // Signal that the server is open for business.
    done := make(chan struct{})

    go func() {
        defer close(done)

        log.Println("Server is now listening on port :8080")

        if err := http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})); err != nil {
            log.Fatal(err)
        }
    }()

    // Wait for the "done" channel to be closed, indicating that the server has started listening.
    <-done
}

In this approach, you create a listener and then use a goroutine to handle the Serve method, which accepts connections and starts serving requests. Simultaneously, you create a channel (done) to signal the listening status. The main goroutine waits for the channel to close, which occurs when the server has started listening on the specified port.

This mechanism allows you to take appropriate actions or perform any necessary configurations once the server successfully starts listening.

The above is the detailed content of How Can I Detect When a Go HTTP Server Starts Listening on a Specific Port?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn