Sobes.tech
Junior — Middle

Explain the main purpose and principles of operation of an HTTP server implemented in Go.

sobes.tech AI

Answer from AI

An HTTP server in Go is designed to handle incoming HTTP requests and send appropriate HTTP responses to clients (browsers, API clients, etc.). The main principle is that the server listens on a specific port, accepts requests, processes them using handlers, and returns the result.

In Go, the net/http package is used to create an HTTP server. Main components include:

  • Handler — a function or object that implements the http.Handler interface, 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 simple to implement, efficient, and highly scalable thanks to built-in support for concurrency via goroutines.