Skip to content

feat(http): add HTTP router and utility functions with Bangla support - #52

Merged
AnkanSaha merged 1 commit into
mainfrom
maintainer/ankan
Jun 11, 2026
Merged

feat(http): add HTTP router and utility functions with Bangla support#52
AnkanSaha merged 1 commit into
mainfrom
maintainer/ankan

Conversation

@AnkanSaha

Copy link
Copy Markdown
Member
  • Implemented router_banao to create a new router with various HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) using Bangla keywords.
  • Added middleware support with majhe for handling requests.
  • Introduced bebohar for mounting sub-routers.
  • Implemented CORS support with cors_chharpao for handling cross-origin requests.
  • Added static file serving with file_dao.
  • Implemented redirection with ghurao and cookie management with kuki_rakho.
  • Added HTML response serving with html_uttor.
  • Introduced logging support with log_chalu.
  • Enhanced tests for new features including path parameters, query parameters, middleware, CORS, static files, redirection, cookies, and full production stack.
  • Updated version to 9.3.0.

Description

Related Issue

Fixes #

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Performance improvement
  • Code refactoring (no functional changes)
  • Test addition or modification
  • Other (please describe):

Changes Made

How Has This Been Tested?

  • Ran existing example files (./banglacode examples/*.bang)
  • Tested in REPL
  • Added new test cases
  • Tested on Linux
  • Tested on macOS
  • Tested on Windows

Test Commands

# Commands used to test
./banglacode examples/hello.bang

Screenshots (if applicable)

Checklist

Code Quality

  • My code follows the project's coding style
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • My changes generate no new warnings

Documentation

  • I have updated the documentation accordingly
  • I have updated SYNTAX.md (if adding/changing language features)
  • I have updated README.md (if needed)
  • I have added examples (if adding new features)

Testing

  • I have tested my changes thoroughly
  • Existing tests still pass
  • I have added tests that prove my fix is effective or that my feature works

Other

  • I have updated CHANGELOG.md (for notable changes)
  • My commit messages follow the project's commit message format
  • I have rebased my branch on the latest main

Additional Notes


Commit Message Format

Please ensure your commit messages follow this format:

type: short description

Longer description if needed.

Co-Authored-By: Your Name <your.email@example.com>

Types: feat, fix, docs, test, refactor, perf, chore

Need Help?

If you need help with anything, please don't hesitate to ask in the PR comments or in GitHub Discussions.

- Implemented `router_banao` to create a new router with various HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) using Bangla keywords.
- Added middleware support with `majhe` for handling requests.
- Introduced `bebohar` for mounting sub-routers.
- Implemented CORS support with `cors_chharpao` for handling cross-origin requests.
- Added static file serving with `file_dao`.
- Implemented redirection with `ghurao` and cookie management with `kuki_rakho`.
- Added HTML response serving with `html_uttor`.
- Introduced logging support with `log_chalu`.
- Enhanced tests for new features including path parameters, query parameters, middleware, CORS, static files, redirection, cookies, and full production stack.
- Updated version to 9.3.0.
@AnkanSaha AnkanSaha self-assigned this Jun 11, 2026
@github-actions

Copy link
Copy Markdown

🤖 Review Buddy - General Code Review

👥 Attention: @AnkanSaha

Oho @AnkanSaha bhai! Express.js ko Bengali dhoti pehna di? Kya baat hai! 👏

Pranaam! Aapne toh pura web framework hi bana diya BanglaCode ke liye. ana, pathano, majhe... naming toh ekdum 'top-notch' hai, lekin code dekh ke lag raha hai ki aapne logic ki thodi 'bali' chadha di hai.

Bugs aur Issues:

  1. doHTTPRequest mein har baar naya http.Client bana rahe ho? Connection pooling ka naam suna hai kabhi? Server ki saansein ful jayengi high load pe.
  2. RateLimiter mein IP-based map toh bana diya, par purane IPs ko saaf kaun karega? Aapka server memory kha-kha ke 'bolod' (saand) ban jayega aur phir crash hoga.
  3. MountSubRouter routes copy kar raha hai. Agar main original router mein baad mein route add karun, toh mounted router ko pata bhi nahi chalega. Consistency gayi tel lene!

Overall, feature list toh lambi hai, par stability thodi 'khali' (empty) hai.

Code Quality Score: 6/10 (Points for the Bengali creativity, but minus points for memory management and performance).


Generated by Review Buddy | Tone: roast | Language: hinglish

@github-actions

Copy link
Copy Markdown

⚡ Review Buddy - Performance Analysis

👥 Attention: @AnkanSaha

Arre bhai! Performance ke naam pe aapne toh 'pishi' (auntie) ki slow walk wala logic likha hai. Chalo, detail mein batata hoon kyun aapka code production mein 'dhishoom' ho jayega:

  1. The http.Client Disaster:

    client := &http.Client{}
    return client.Do(req)

    Yaar Ankan, ye kya bawasir hai? Har request pe naya client? Iska matlab har baar naya TCP connection, naya TLS handshake. Connection pooling toh gayi kachre ke dibbe mein. Isko global banao ya reuse karo, warna server request handle kam karega aur handshake zyada.

  2. GC Pressure is Real:
    buildRequestMap function ko dekho. Har single HTTP request pe aap ek bada sa object.Map banate ho, usme headers, query, params, cookies sab ghusa dete ho. Phir json_poro karke body parse karte ho. Bhai, garbage collector aapke ghar aake aapko marega itne objects dekh ke. 300 million Bengali users agar ek saath aagaye toh aapka heap memory 'Maayer Chhoy' (Mom's 6/Panic) ho jayega.

  3. The Memory Leak in RateLimiter:

    hits: make(map[string][]time.Time),

    Aapne sliding window toh bana di, lekin rl.hits se IPs delete karne ka code bhul gaye? Agar 1 lakh unique IPs aayi, toh ye map badhta hi rahega. Aapka server memory leak ka champion ban jayega. Ek cleanup routine dalo jo purane/inactive IPs ko uda de.

  4. Regex Compilation:
    compilePattern ko AddRoute mein call kiya hai, jo sahi hai. Kam se kam wahan thodi akal lagayi. Lekin FindRoute mein har baar loop chala ke route.re.FindStringSubmatch(path) karna thoda mehnga pad sakta hai agar routes 100+ ho gaye. Radix tree ya Trie ka naam suna hai? Woh use karo agar 'goti' (speed) chahiye toh.

  5. Gzip Overhead:
    sankochon_chalu (compression) hamesha achha nahi hota small payloads ke liye. Aapne bina size check kiye sab pe gzip.NewWriter thop diya hai. CPU usage unnecessarily badh jayegi.

Recommendation:

  • http.Client ko package level pe define karo with proper timeouts.
  • RateLimiter mein ek cleanup goroutine chalao.
  • Map allocation kam karne ke liye pooling use karo (though Go's interpreter mode mein ye mushkil hai).

Generated by Review Buddy | Tone: roast | Language: hinglish

@github-actions

Copy link
Copy Markdown

🔐 Review Buddy - Security Audit

👥 Attention: @AnkanSaha

Oye! Security ke maamle mein toh tumne 'khula darwaza' policy rakhi hai.

  1. CORS Default (Severity: Medium):
    cors_chharpao ka default origin * hai. Bhai, security ka 'S' bhi jaante ho? Default mein toh restrictive hona chahiye. Koi bhi random site aapke API ko call karke data nikaal legi.

  2. Path Traversal Risk (Severity: High):
    file_dao(app, "/public", "./static_dir") mein http.FileServer use kiya hai. Agar dirPath user input se link hua (halanki yahan hardcoded lag raha hai), toh path traversal ka khatra hai. Ensure karo ki http.Dir properly restricted ho.

  3. Regex Denial of Service (ReDoS) (Severity: Medium):
    Route patterns mein :id ko ([^/]+) mein convert kar rahe ho. Simple regex hai, toh filhal ReDoS ka khatra kam hai, par complex patterns allow karne se pehle sochna.

  4. Cookie Security (Severity: Medium):
    kuki_rakho mein httpOnly aur secure default false hai? Yaar, session cookies handle kar rahe ho ya bacchon ka khel? Inhe default true rakho warna XSS attacks se session steal ho jayenge.

  5. CRLF Injection (Severity: Low):

    h.Pairs["Set-Cookie"] = &object.String{Value: existing.Value + "\r\nSet-Cookie: " + cookieStr}

    Headers mein manual \r\n ghusana khatarnak ho sakta hai agar cookieStr sanitize nahi kiya gaya. Proper http.Header.Add use karo na bhai!

OWASP References:

  • A01:2021-Broken Access Control (CORS)
  • A05:2021-Security Misconfiguration (Cookies)

Generated by Review Buddy | Tone: roast | Language: hinglish

@github-actions

Copy link
Copy Markdown

📊 Review Buddy - Code Quality & Maintainability Analysis

👥 Attention: @AnkanSaha

🎯 Overall Benchmark: 55/100 (Needs Improvement)

Bhai, code quality dekh ke lag raha hai tumne 'Express.js' ko Google Translate karke Go mein chaap diya hai. Chalo, 'Bangla Express' ka post-mortem karte hain:

  1. SOLID Principles ka 'Shraadh':

    • Single Responsibility: Router struct hi sab kuch kar raha hai - routing, middleware, rate limiting, logging, compression. Isko separate handlers ya middleware objects mein todo.
    • Open/Closed: Naya functionality add karne ke liye har baar builtins_http_advanced.go ya builtins_http_router.go mein badlaav karna pad raha hai.
  2. Global State is Evil:
    routerRegistry ek global map hai. Unit testing karte waqt ye stateful chaos create karega. Dependency injection ka naam suna hai? Nahi? Koi baat nahi, Bengali mein 'ano' (bring) karke ek function bana do uske liye bhi.

  3. Inconsistent Error Handling:
    Kahin newError return kar rahe ho, kahin panic (though not explicitly seen, potential is there). Interpreter level pe error messages toh Bengali-friendly hain, par Go code mein validation thoda 'dhila' hai. extractRouter thoda repetitive lag raha hai.

  4. Naming Conventions:
    Bangla functions (ana, bodlano) are cool for users. Par internal Go code mein ridObj, rid, s jaise names use kar rahe ho? Bhai, clean code ki book padho kabhi. Variables ke naam aise rakho ki padh ke maza aaye, 'Alphabet soup' mat banao.

  5. Refactoring Suggestion:
    Router.AddRoute mein pattern compilation logic ko alag function mein dalo (kiya hai, good). Lekin Middleware handling ko execute recursive function se handle karna stack overflow ka risk de sakta hai agar middleware chain bahut lambi hui. Iterative approach better hai.

  6. Documentation:
    Documentation achhi hai, par GEMINI.md kyun delete kiya? Context loss ho jayega next time AI help lega toh.

  7. DRY (Don't Repeat Yourself):
    requireRoute function banana achha move tha, par Builtins registration mein abhi bhi bahut boilerplate hai. Maps use karke loop mein register kyu nahi karte?

Example of Refactoring:

// Current: Recursive execution
execute = func(idx int) {
    if idx < len(middlewares) {
        // ... logic
        callHandler(mw, []object.Object{reqMap, resMap, nextFn})
    }
}

// Better: Iterative or wrapped handlers (like Gin/Echo)

Generated by Review Buddy | Tone: roast | Language: hinglish

@github-actions

Copy link
Copy Markdown

💡 Review Buddy - Best Practices & Alternative Suggestions

👥 Attention: @AnkanSaha

Arre Ankan! Best practices follow karna toh 'Sotti' (sach mein) bhul gaye tum. Dekho ye examples:

1. HTTP Client Reuse

Current Code:

client := &http.Client{}
return client.Do(req)

Better Alternative:

// Global variable
var defaultHTTPClient = &http.Client{
    Timeout: time.Second * 30,
    Transport: &http.Transport{
        MaxIdleConns: 100,
        IdleConnectionTimeout: 90 * time.Second,
    },
}
// In function:
return defaultHTTPClient.Do(req)

Why: Connection pooling. Bina iske aapka server sockets exhaust kar dega within minutes under load.

2. Map Initialization with Capacity

Current Code:

pairs := make(map[string]object.Object)

Better Alternative:

pairs := make(map[string]object.Object, len(v))

Why: Performance. Agar size pata hai toh capacity pehle hi batado, warna map resize hone mein CPU cycles waste honge.

3. Middleware Execution

Current Code:

// Recursive closure `execute` inside ServeHTTP

Better Alternative:
Create a Context struct and an array of handlers, then iterate with an index.
Why: Better memory management and avoids deep recursion stacks.

4. String Concatenation in Loops

Current Code:

regexParts = append(regexParts, regexp.QuoteMeta(part))
// ... strings.Join later

Why: This is actually fine (strings.Join is good), but watch out for other places where you use + in loops.


Generated by Review Buddy | Tone: roast | Language: hinglish

@github-actions

Copy link
Copy Markdown

⚠️ Review Buddy - Final Recommendation

👥 Attention: @AnkanSaha

Recommendation: REQUEST CHANGES

Changes chahiye, bhai! Abhi approve nahi kar sakte.

Reasoning:

  • Critical Performance Issue: Creating a new http.Client for every request in anun and anun_async will kill connection pooling and lead to socket exhaustion.
  • Memory Leak Risk: The RateLimiter map grows indefinitely as it stores IP hits but never removes entries for inactive IPs.
  • Sub-router Consistency: MountSubRouter copies routes instead of referencing them, meaning changes to the sub-router post-mounting are ignored.
  • Security Risk: CORS defaults to * and cookie security options (httpOnly, secure) default to false.
  • Global State: The use of a global routerRegistry map without a clear cleanup strategy makes testing and multi-tenancy difficult.

📋 Review Checklist for Reviewers:

  • Code changes align with the PR description
  • No security vulnerabilities introduced
  • Performance considerations addressed
  • Code follows project conventions
  • Tests are adequate (if applicable)
  • Documentation updated (if needed)

🎯 Next Steps:

⚠️ Pehle suggestions address karo, phir approve karna.

Generated by Review Buddy | Tone: roast | Language: hinglish

@AnkanSaha
AnkanSaha merged commit 09529be into main Jun 11, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant