5. Requests and Responses

![[Pasted image 20260206012719.png]]

  • A "client" is a computer making an HTTP request (whether it's a phone, a laptop, a desktop etc.)

  • A "server" is a computer responding to an HTTP request

  • A computer can be a client, a server, both, or neither. "Client" and "server" are just words we use to describe what computers are doing within a communication system.

  • Clients send requests and receive responses

  • Servers receive requests and send responses

Example Code

main.go
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
)

const usersUrl = "https://api.boot.dev/v1/courses_rest_api/learn-http/users"

func main() {
	users, err := getUserData(usersUrl)
	if err != nil {
		log.Fatalf("error getting user data: %v", err)
	}
	fmt.Println(string(users))
}

func getUserData(url string) ([]byte, error) {
	res, err := http.Get(url)
	if err != nil {
		return nil, fmt.Errorf("error making request: %w", err)
	}
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, fmt.Errorf("error reading response: %w", err)
	}

	return data, nil
}