Junior — Middle
Selgitage HTTP-serveri põhieesmärki ja tööpõhimõtteid, mis on rakendatud Go keeles
sobes.tech AI
Vastus AI-lt
The HTTP server in Go is designed to handle incoming HTTP requests and send appropriate HTTP responses to clients (browsers, API clients, etc.). The basic principle of operation is that the server listens on a specific port, receives requests, processes them using handlers, and returns the result.
In Go, the net/http package is used to create HTTP servers. The main components are:
- Handler — a function or object that implements the
http.Handlerinterface and is responsible for processing the request. - ListenAndServe — a function that starts the server and begins listening on the specified address.
Example of a simple HTTP server in Go:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
}
func main() {
http.HandleFunc("/", helloHandler) // Register handler for path "/"
http.ListenAndServe(":8080", nil) // Start server on port 8080
}
Thus, an HTTP server in Go is easy to implement, efficient, and scales well thanks to built-in support for concurrency via goroutines.