Skip to main content

Command Palette

Search for a command to run...

HTTP Routing-এর Behind the Scenes: কার্নেল থেকে Go Backend পর্যন্ত

Published
6 min readView as Markdown
HTTP Routing-এর Behind the Scenes: কার্নেল থেকে Go Backend পর্যন্ত
I

A highly motivated and experienced full-stack developer with a proven track record of developing and deploying web applications. Skilled in a range of programming languages and frameworks, as well as database technologies. Comfortable working in a fast-paced environment and able to adapt to new technologies quickly. A team player who is also able to work independently when required.

HTTP routing এর পূর্ণ যাত্রা বোঝার জন্য আমাদের নেটওয়ার্ক কার্নেল থেকে শুরু করে high-level web framework পর্যন্ত সম্পূর্ণ স্ট্যাক বুঝতে হবে। আসুন দেখি একটি HTTP request কীভাবে কার্নেল থেকে শুরু করে Go backend এর routing পর্যন্ত পৌঁছায়।

1. কার্নেল-লেভেল নেটওয়ার্কিং (Lowest Level)

যখন একটি HTTP request সার্ভারে আসে, সর্বপ্রথম এটি operating system কার্নেলের network stack দ্বারা process হয়:

IP & TCP প্রসেসিং

  1. NIC (Network Interface Card) প্যাকেট receive করে

  2. Device Driver প্যাকেট kernel space এ পাঠায়

  3. IP Layer প্যাকেট route করে

  4. TCP Layer packet sequence manage করে, একটি complete TCP stream বানায়

Socket Interface

  1. কার্নেল নতুন connection কে socket file descriptor হিসেবে represent করে

  2. Socket তৈরি হয়, যেটা কার্নেল space এবং user space এর মধ্যে bridge হিসেবে কাজ করে

  3. যে process port listen করছে (যেমন web server), সেটা socket থেকে data receive করে

System Calls

Web server (Go-তে) নিম্নলিখিত system calls ব্যবহার করে:

  • socket() - নতুন socket তৈরি করে

  • bind() - socket কে port এর সাথে bind করে

  • listen() - incoming connections wait করে

  • accept() - connection accept করে

  • read()/write() - data পড়ে/লেখে

2. Web Server (Go's HTTP Server)

Go এর net/http package একটি web server implement করে যা HTTP protocol handle করে:

HTTP Server Initialization

// Basic HTTP server in Go
http.ListenAndServe(":8080", handler)

এই code নিম্নলিখিত steps follow করে:

  1. TCP listener তৈরি করে (port 8080-এ)

  2. Goroutine শুরু করে যা incoming connections accept করে

  3. প্রতিটি connection এর জন্য আলাদা goroutine তৈরি করে

HTTP Parser

যখন data incoming connection থেকে আসে:

  1. Go এর net/http package raw bytes থেকে HTTP request parse করে

  2. Request তৈরি হয় যেটার structure হল:

     type Request struct {
         Method string
         URL *url.URL
         Proto string // "HTTP/1.0", "HTTP/1.1"
         Header Header
         Body io.ReadCloser
         // ...other fields
     }
    

এখানেই হচ্ছে Routing Table Matching

Go HTTP server request কে handler এর কাছে পাঠায়। Standard net/http package এর ServeMux (Go এর built-in router) এবার request কে appropriate handler এ map করে:

mux := http.NewServeMux()
mux.HandleFunc("/api/users", handleUsers)
mux.HandleFunc("/api/products", handleProducts)

ServeMux কীভাবে route match করে:

  1. URL path extract করে (/api/users/123)

  2. Longest matching prefix rule ব্যবহার করে handler খুঁজে বের করে

  3. Request object handler এর কাছে পাঠায়

3. Third-Party Router এবং Advanced Routing (Go)

Go এর built-in ServeMux basic। Real-world applications অনেক সময় advanced routing libraries ব্যবহার করে:

r := mux.NewRouter()
r.HandleFunc("/api/users/{id:[0-9]+}", getUserHandler).Methods("GET")

Gorilla Mux কীভাবে route match করে:

  1. URL path extract করে

  2. Pattern matching algorithm ব্যবহার করে path variable identify করে

  3. Regular expressions ব্যবহার করে path validate করে

  4. HTTP method এর সাথে match করে

Route Matching Algorithm - Behind the Scenes

Gorilla Mux এর ভিতরে routing table এর structure হল tree-like data structure (Radix Tree), যেটা route lookup optimize করে:

  1. Trie/Radix Tree Creation:

    • Router initialization এর সময় route patterns একটি tree structure এ organize হয়

    • প্রতিটি node হল URL path এর একটি segment

    • Path parameters (যেমন {id}) special node হিসেবে mark করা হয়

  2. Route Lookup:

    • URL path slash (/) দিয়ে split হয়

    • Tree traverse হয় segment-by-segment

    • Parameters match হলে variable extract হয়

    • Method check হয়

  3. Match Decision:

     Request: GET /api/users/123
    
     Tree Structure:
     / -> api -> users -> {id} (GET handler)
                        -> /profile (POST handler)
    

Router tree traverse করে /api/users/{id} pattern find করে, এবং id=123 capture করে, তারপর check করে method GET কি না।

4. Go HTTP Server এর Complete Request Flow

এবার আমরা সম্পূর্ণ যাত্রা একত্রে দেখি - কার্নেল থেকে Go backend router পর্যন্ত:

  1. Network Packet Arrival:

    • HTTP request TCP packet হিসেবে network interface এ আসে

    • Kernel space এ TCP/IP stack দিয়ে process হয়

  2. Socket Processing:

    • Request data kernel space থেকে Go HTTP server (user space) এ যায়

    • Go HTTP server এর listener goroutine data accept করে

  3. HTTP Parsing:

    • Raw TCP data থেকে HTTP request parse হয়

    • Headers, method, URL, body extract হয়

  4. Router Matching:

    • Router parsed URL এর সাথে registered routes compare করে

    • Gorilla Mux হলে radix tree traverse করে

    • Standard ServeMux হলে longest prefix match করে

    • URL parameters extract হয়

    • HTTP method verify হয়

  5. Handler Execution:

    • Matched handler function execute হয়

    • Handler database query, business logic perform করে

    • Response generate হয়

  6. Response Return:

    • HTTP response serialize হয়

    • TCP socket দিয়ে client এ send হয়

    • Socket connection close হয় (যদি Keep-Alive না থাকে)

5. Low-Level Implementation Example (Go)

আসুন একটি simplistic HTTP router এর implementation দেখি, যেটা demonstrate করে কীভাবে routing table match হয়:

type Route struct {
    Method      string
    Pattern     string
    HandlerFunc http.HandlerFunc
}

type Router struct {
    routes []Route
}

func (r *Router) AddRoute(method, pattern string, handler http.HandlerFunc) {
    r.routes = append(r.routes, Route{
        Method:      method,
        Pattern:     pattern,
        HandlerFunc: handler,
    })
}

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    // Here's where the matching happens!
    for _, route := range r.routes {
        // Check if method matches
        if route.Method != req.Method {
            continue
        }

        // Check if path matches (simplified)
        // In a real router, this would use a more sophisticated algorithm
        if matchPath(route.Pattern, req.URL.Path) {
            // Execute the handler
            route.HandlerFunc(w, req)
            return
        }
    }

    // No match found
    http.NotFound(w, req)
}

func matchPath(pattern, path string) bool {
    // Simplified matching - a real router would handle path parameters
    // and use more efficient data structures

    // Split pattern and path by "/"
    patternParts := strings.Split(strings.Trim(pattern, "/"), "/")
    pathParts := strings.Split(strings.Trim(path, "/"), "/")

    if len(patternParts) != len(pathParts) {
        return false
    }

    // Check each part
    for i, part := range patternParts {
        // If it's a parameter (starts with ":")
        if strings.HasPrefix(part, ":") {
            // Parameter - it matches anything
            continue
        }

        // Static part - must match exactly
        if part != pathParts[i] {
            return false
        }
    }

    return true
}

এই উদাহরণে, ServeHTTP method হল যেখানে matching হয়। আসল implementations (যেমন Gorilla Mux, Echo, Gin, ইত্যাদি) আরও efficient matching algorithms ব্যবহার করে, কিন্তু core concept একই: method + URL pattern কে handler এর সাথে match করা।

সারাংশ: HTTP Routing Matching Process

  1. Network Level: Kernel space packet handling

  2. Transport Level: TCP connection, socket operations

  3. HTTP Server Level: Request parsing, extracting method and URL

  4. Router Level: Method + URL pattern match করা routing table এ

  5. Handler Level: Matched handler execution

Go backend এর routing system এর সবচেয়ে key part হল router, যেটা structured routing table তৈরি করে এবং incoming requests এর সাথে efficient matching algorithm ব্যবহার করে match করে।

HTTP routing এর behind-the-scenes process টি নিচ থেকে উপরে - kernel থেকে application logic পর্যন্ত - একটি beautiful orchestration, যেখানে প্রতিটি layer নিজের role পালন করে, একে অপরের উপর build করে complex web systems enable করে।

2 views

More from this blog

Low Level Design: গভীর থেকে বোঝা এবং আয়ত্ত করা

ভূমিকা: কেন এই Article? তুমি হয়তো programming শিখেছ। Variable, loop, function, data structure - সব জানো। কিন্তু যখন একটা বড় system বানাতে বসো, তখন মনে হয় কোথা থেকে শুরু করব? কীভাবে organize করব? Code লিখতে লিখতে হারিয়ে যাও একটা maze-এ। এই feeling...

Oct 15, 202520 min read71
Low Level Design: গভীর থেকে বোঝা এবং আয়ত্ত করা

Go-তে Interface কীভাবে Code Decouple করে?

একটা HTTP Server দিয়ে পুরো ব্যাপারটা বুঝে নেওয়া যাক আমরা সবাই জানি Go একটা সিম্পল ল্যাঙ্গুয়েজ, কিন্তু interface নিয়ে অনেকেরই confusion থাকে। আজকে আমরা দেখব কীভাবে interface আসলে তোমার code-কে flexible এবং maintainable বানায়। একটা real-world HTT...

Oct 14, 202520 min read5
Go-তে Interface কীভাবে Code Decouple করে?

তোমার Project-এ Coupled Code কীভাবে খুঁজে বের করবে?

Coupled code খোঁজা মানে হচ্ছে তোমার codebase-এ এমন জায়গা খুঁজে বের করা যেখানে একটা অংশ আরেকটার উপর বেশি depend করছে। এটা একটা detective work — তুমি clue খুঁজবে, pattern দেখবে, এবং সমস্যা চিহ্নিত করবে। চলো step by step শিখি কীভাবে এটা করতে হয়। কেন ...

Oct 14, 202510 min read2

Go-তে Object (Struct Instance) তৈরির সম্পূর্ণ গাইড

Go programming শেখার সময় একটা জিনিস খুব তাড়াতাড়ি বুঝতে হয় - কীভাবে object তৈরি করতে হয়। অন্য language যেমন Java বা Python এ class আছে, কিন্তু Go-তে আছে struct। আর struct এর instance বানানোই হলো object তৈরি করা। আজকের এই blog এ আমরা দেখব Go-তে ob...

Oct 13, 202524 min read3
Go-তে Object (Struct Instance) তৈরির সম্পূর্ণ গাইড
I

Imran Hasan

61 posts

Full-stack developer with experience in developing and managing web applications. Skilled in React, Node.js, HTML, CSS, and JavaScript. Experience in managing website hosting and security.