How do you serve HTTP requests in Go?
In Go, serving HTTP requests is a fundamental task that can be accomplished using the net/http package, which provides a rich set of functionalities for building web servers, handling HTTP requests and responses, and implementing HTTP middleware.
Here’s a basic example of serving HTTP requests in Go:
go 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) }
In this example, we define an HTTP handler function handler that writes the string “Hello, World!” to the response writer w. We then register the handler function with the http.HandleFunc function, specifying the URL pattern “/” for the root endpoint. Finally, we start the HTTP server using the http.ListenAndServe function, specifying the port number :8080 to listen on.
The http.HandleFunc function is used to register handler functions for specific URL patterns, while the http.ListenAndServe function starts an HTTP server and listens for incoming HTTP requests on the specified port.
In addition to serving static content and handling basic request/response operations, the net/http package in Go also provides support for more advanced features such as routing, middleware, request parsing, and response encoding. Developers can leverage these features to build robust and scalable web servers that handle a wide range of HTTP requests and implement complex business logic.
By using the net/http package and its associated functionalities, developers can build custom web servers and handle HTTP requests efficiently and effectively in Go applications.