Middle+
Describe the structure of an HTTP request and response. How are response codes classified?
sobes.tech AI
Answer from AI
An HTTP request consists of several parts:
- Request line: contains the method (GET, POST, etc.), URI, and protocol version.
Example:
GET /index.html HTTP/1.1 - Headers: key-value pairs that convey meta-information (e.g.,
Host,User-Agent,Content-Type). - Body: optional, contains data (e.g., in POST requests).
An HTTP response also consists of:
- Status line: protocol version, status code, and status message.
Example:
HTTP/1.1 200 OK - Headers: meta-information about the response (e.g.,
Content-Type,Content-Length). - Body: content (HTML, JSON, file, etc.).
Response codes are classified by their first digit:
- 1xx (Informational): request received, processing continues.
- 2xx (Success): request successfully processed (e.g., 200 OK, 201 Created).
- 3xx (Redirection): additional action required from the client (e.g., 301 Moved Permanently).
- 4xx (Client errors): error on the client side (e.g., 404 Not Found, 400 Bad Request).
- 5xx (Server errors): error on the server side (e.g., 500 Internal Server Error).
Example of a request and response in Go:
req, _ := http.NewRequest("GET", "https://example.com", nil)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
fmt.Println("Status code:", resp.StatusCode)
This is the basic structure and classification of HTTP messages.