*How HTTP works in golang

January 30, 2025

How HTTP Works

HTTP (Hypertext Transfer Protocol) is the foundation of communication on the web. It follows a request-response model where a client (e.g., browser) sends requests to a server, which then responds with the requested resource.

HTTP Request-Response Cycle

  1. Client sends a request - This request contains a method (GET, POST, etc.), headers, and sometimes a body.
  2. Server processes the request - It interprets the request and prepares a response.
  3. Server sends a response - The response includes a status code, headers, and optionally a body.

Example: Basic HTTP Request

GET /hello HTTP/1.1
Host: example.com
User-Agent: Go-Client

Example: Basic HTTP Response

HTTP/1.1 200 OK
Content-Type: text/plain

Hello, World!

Building a Simple HTTP Server in Go

Let's implement a simple HTTP server using Go's built-in net/http package.

package main

import (
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, World!")
}

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("Server running on http://localhost:8080")
	http.ListenAndServe(":8080", nil)
}

Explanation

  • http.HandleFunc("/", handler): Registers the / route and binds it to the handler function.
  • http.ListenAndServe(":8080", nil): Starts the server on port 8080.
  • The handler function writes "Hello, World!" to the response.

HTTP Methods

HTTP supports several methods, each serving a different purpose:

| Method | Description | | ------ | ------------- | | GET | Retrieve data | | POST | Send data | | PUT | Update data | | DELETE | Remove data |

Handling Different Methods in Go

func handler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		fmt.Fprintf(w, "Received a GET request")
	case "POST":
		fmt.Fprintf(w, "Received a POST request")
	default:
		http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
	}
}

Conclusion

HTTP is a simple yet powerful protocol that powers the web. Understanding its request-response model helps developers build efficient web applications. Using Go, we can quickly set up an HTTP server to handle various types of requests.