Middle+
How does an HTTP server work in Go?
sobes.tech AI
Answer from AI
The HTTP server in Go is based on the net/http package, which implements the HTTP protocol and provides a convenient interface for creating servers.
Main points of operation:
- The server listens on a specified address and port using
http.ListenAndServe. - Request handlers are registered to process requests, which implement the
http.Handlerinterface or have a function signature offunc(http.ResponseWriter, *http.Request). - When a request arrives, Go creates an
http.Requestobject with request information and anhttp.ResponseWriterobject for forming the response. - The handler reads data from the request, performs logic, and writes the response via
ResponseWriter. - The built-in server supports concurrent request processing using goroutines, ensuring high performance.
Example of a simple HTTP server:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", helloHandler)
http.ListenAndServe(":8080", nil)
}
This code starts a server on port 8080 that responds with "Hello, World!" to all requests.