Skip to content

Middleware System Guide

Overview

Middleware is an interceptor in HttpServer's request/response processing pipeline, allowing custom logic to execute before requests reach controllers and after responses are sent to clients.

Request Flow:
┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│   Request   │ -> │    Pre      │ -> │ Controller  │ -> │   Post      │ -> Response
│   Arrives   │    │ Middleware  │    │   Handler   │    │ Middleware  │
└─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘

Middleware Types

TypeClassExecution Timing
Pre-MiddlewarecHttpServerRouteBeforeBefore route matching
Post-MiddlewarecHttpServerRouterAfterAfter controller processing

Pre-Middleware (RouteBefore)

Basic Structure

vb
' cAuthMiddleware.cls
Option Explicit

Public Sub Entry(ctx As cHttpServerContext)
    ' Middleware logic
    
    ' Terminate subsequent processing
    ' ctx.fIsAbort = True
    
    ' Skip other middleware
    ' ctx.fIsSkipNextMiddleWare = True
End Sub

Common Middleware Examples

1. Login Verification Middleware

vb
' cAuthCheckMiddleware.cls
Option Explicit

Public Sub Entry(ctx As cHttpServerContext)
    ' Exclude login endpoints
    If ctx.Request.PathInfo = "/login" Then Exit Sub
    If ctx.Request.PathInfo = "/register" Then Exit Sub
    
    ' Check session
    If Not ctx.Session.Exists("user_id") Then
        ctx.Response.State401 "Please login first"
        ctx.fIsAbort = True  ' Terminate subsequent processing
    End If
End Sub

2. IP Blacklist Middleware

vb
' cIPBlacklistMiddleware.cls
Option Explicit

Dim Blacklist As Scripting.Dictionary

Private Sub Class_Initialize()
    Set Blacklist = New Scripting.Dictionary
    Blacklist("192.168.1.100") = True
    Blacklist("10.0.0.50") = True
End Sub

Public Sub Entry(ctx As cHttpServerContext)
    Dim clientIP As String
    clientIP = ctx.ClientInfo.IP
    
    If Blacklist.Exists(clientIP) Then
        ctx.Response.State403 "Your IP has been blocked"
        ctx.fIsAbort = True
    End If
End Sub

3. Request Logging Middleware

vb
' cRequestLogMiddleware.cls
Option Explicit

Public Sub Entry(ctx As cHttpServerContext)
    Dim log As String
    log = Now & " " & _
          ctx.ClientInfo.IP & " " & _
          ctx.Request.MethodName & " " & _
          ctx.Request.PathInfo
    
    ' Write to log file
    Call WriteLog(log)
    
    ' Record start time in context (for calculating response time)
    ctx.fStartTime = Timer
End Sub

Private Sub WriteLog(msg As String)
    Dim f As Integer
    f = FreeFile
    Open "C:\Logs\access.log" For Append As #f
    Print #f, msg
    Close #f
End Sub

4. CORS Preflight Handling

vb
' cCorsMiddleware.cls
Option Explicit

Public Sub Entry(ctx As cHttpServerContext)
    ' Handle OPTIONS preflight request
    If ctx.Request.Method = ReqOptions Then
        ctx.Response.Header("Access-Control-Allow-Origin") = "*"
        ctx.Response.Header("Access-Control-Allow-Methods") = "GET, POST, PUT, DELETE, OPTIONS"
        ctx.Response.Header("Access-Control-Allow-Headers") = "Content-Type, Authorization"
        ctx.Response.Text ""
        ctx.fIsAbort = True
    End If
End Sub

5. Rate Limiting

vb
' cRateLimitMiddleware.cls
Option Explicit

Dim RequestCounts As Scripting.Dictionary
Dim LastReset As Date

Private Sub Class_Initialize()
    Set RequestCounts = New Scripting.Dictionary
    LastReset = Now
End Sub

Public Sub Entry(ctx As cHttpServerContext)
    ' Reset count every minute
    If DateDiff("n", LastReset, Now) >= 1 Then
        Set RequestCounts = New Scripting.Dictionary
        LastReset = Now
    End If
    
    Dim clientIP As String
    clientIP = ctx.ClientInfo.IP
    
    ' Count requests
    If Not RequestCounts.Exists(clientIP) Then
        RequestCounts(clientIP) = 0
    End If
    RequestCounts(clientIP) = RequestCounts(clientIP) + 1
    
    ' Limit to 100 per minute
    If RequestCounts(clientIP) > 100 Then
        ctx.Response.State429 "Too many requests, please try again later"
        ctx.fIsAbort = True
    End If
End Sub

Middleware Registration and Priority

vb
Private Sub Form_Load()
    Set Server = New cHttpServer
    
    ' Register middleware (in priority order)
    Call Server.RouteBefore.Add("cors", New cCorsMiddleware)          ' First to execute
    Call Server.RouteBefore.Add("ratelimit", New cRateLimitMiddleware) ' Second to execute
    Call Server.RouteBefore.Add("ipblacklist", New cIPBlacklistMiddleware) ' Third to execute
    Call Server.RouteBefore.Add("requestlog", New cRequestLogMiddleware)   ' Fourth to execute
    Call Server.RouteBefore.Add("authcheck", New cAuthCheckMiddleware)     ' Fifth to execute
    
    ' Register controllers
    Call Server.Router.Reg("Api", New cApiController)
    Call Server.Router.Add("/api/data", "Api@Data")
    
    Call Server.Start(8080)
End Sub

Context Control Flags

FlagDescription
ctx.fIsAbortSet to True to terminate entire request processing
ctx.fIsSkipNextMiddleWareSet to True to skip subsequent middleware

Post-Middleware (RouteAfter)

Post-middleware is used for processing after response is sent (current version is a reserved interface).

vb
' cResponseLogMiddleware.cls
Option Explicit

Public Sub Entry(ctx As cHttpServerContext)
    ' Calculate response time
    If ctx.fStartTime > 0 Then
        Dim elapsed As Double
        elapsed = Timer - ctx.fStartTime
        
        ' Log slow requests
        If elapsed > 1 Then
            Call WriteSlowLog(ctx.Request.PathInfo & " took " & elapsed & " seconds")
        End If
    End If
End Sub

Context Extension

Custom properties can be added to context for sharing between middleware and controllers:

vb
' cHttpServerContext extension module

' Set in middleware
Public Sub AuthMiddleware(ctx As cHttpServerContext)
    If IsValidToken Then
        ctx.fUserId = GetUserIdFromToken()
        ctx.fUserRole = GetUserRole()
    End If
End Sub

' Use in controller
Public Sub GetData(ctx As cHttpServerContext)
    ' Get info set by middleware
    Dim userId As String
    userId = ctx.fUserId
    
    ' Return different data based on role
    If ctx.fUserRole = "admin" Then
        ' Return all data
    Else
        ' Return partial data
    End If
End Sub

Middleware Chain Execution Order

Request: GET /api/users

1. cCorsMiddleware          -> Passed
2. cRateLimitMiddleware    -> Passed
3. cIPBlacklistMiddleware  -> Passed
4. cRequestLogMiddleware   -> Passed
5. cAuthCheckMiddleware    -> Check session
   └─> Not logged in -> ctx.fIsAbort = True
   
Request terminated, returns 401

Last Updated: 2026-05-17

VB6 and LOGO copyright of Microsoft Corporation