📜  ListenAndServe (1)

📅  最后修改于: 2023-12-03 15:17:24.634000             🧑  作者: Mango

ListenAndServe

When developing a web application, it is essential to have a way to serve the application to clients. One of the most popular ways to do this in the Go programming language is by using the ListenAndServe function from the net/http package.

This function takes two arguments: a network address to listen on and a handler to handle incoming requests. The network address can be an IP address and a port number (e.g., 127.0.0.1:8080), or just a port number (e.g., :8080 for all available network interfaces). The handler is usually an instance of the http.ServeMux struct.

Here's an example of using ListenAndServe to serve a simple "Hello, World!" web page:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, World!")
	})

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}

In this example, we create a handler function that writes the string "Hello, World!" to the response writer whenever the root path ("/") is requested. We then pass nil as the second argument to ListenAndServe, which means the default server mux will be used.

If you run this program and navigate to http://localhost:8080/ in your web browser, you should see the "Hello, World!" message displayed.

ListenAndServe is a powerful function that can be used to serve any type of HTTP handler function, not just the http.ServeMux struct. It also supports TLS encryption, graceful server shutdown, and other advanced features.

In summary, ListenAndServe is a fundamental function for serving web applications in Go. If you're building a web app in Go, you'll almost certainly use this function at some point.