HTTP Advanced Features - Complete Guide with Latest Syntax
This document covers advanced HTTP capabilities in Harneet for enterprise-level web development. All examples use the latest tuple destructuring syntax for modern, clean code.
Range Requests
Support for HTTP range requests and partial content responses.
Support for HTTP range requests and partial content responses for efficient file downloads and streaming.
Examples:
Download File in Chunks with Tuple Destructuring:
| Download File in Chunks |
|---|
| package main
import http
import fmt
function downloadFileInChunks(url string, chunkSize int) {
fmt.Printf("📥 Downloading %s in %d byte chunks\n", url, chunkSize)
// First, get file size with HEAD request
var headResponse, headErr = http.Head(url)
if headErr != None {
fmt.Printf("❌ Failed to get file info: %s\n", headErr)
return
}
var contentLength = headResponse["headers"]["Content-Length"]
fmt.Printf("📊 File size: %s bytes\n", contentLength)
var downloaded = 0
var totalSize = 10000 // Simulated file size
for downloaded < totalSize {
var start = downloaded
var end = downloaded + chunkSize - 1
if end >= totalSize {
end = totalSize - 1
}
// Create request with Range header
var request, _ = http.NewRequest("GET", url, "")
var rangeHeader = "bytes=" + start + "-" + end
var rangeRequest, _ = http.SetHeader(request, "Range", rangeHeader)
var response, err = http.Do(rangeRequest)
if err != None {
fmt.Printf("❌ Chunk download failed: %s\n", err)
return
}
if response["status"] == 206 { // Partial Content
fmt.Printf("✅ Downloaded bytes %d-%d (%d bytes)\n", start, end, end-start+1)
downloaded = end + 1
} else {
fmt.Printf("❌ Server doesn't support range requests (Status: %d)\n", response["status"])
return
}
}
fmt.Printf("🎉 Download complete!\n")
}
|
Resume Interrupted Download:
| Resume Interrupted Download |
|---|
| package main
import http
import fmt
function resumeDownload(url string, existingBytes int) {
var request, _ = http.NewRequest("GET", url, "")
var rangeHeader = "bytes=" + existingBytes + "-"
var resumeRequest, _ = http.SetHeader(request, "Range", rangeHeader)
var response, err = http.Do(resumeRequest)
if err != None {
fmt.Printf("❌ Resume failed: %s\n", err)
return
}
if response["status"] == 206 {
fmt.Printf("✅ Resuming download from byte %d\n", existingBytes)
} else {
fmt.Printf("⚠️ Server doesn't support resume, starting over\n")
}
}
|
Conditional Requests
Support for If-Modified-Since, ETag, and other conditional headers for efficient caching.
ETag Validation
| ETag Validation |
|---|
| package main
import http
import fmt
// Fetch with ETag validation
function fetchWithETag(url string, cachedETag string) {
var request, _ = http.NewRequest("GET", url, "")
if cachedETag != "" {
var conditionalRequest, _ = http.SetHeader(request, "If-None-Match", cachedETag)
var response, err = http.Do(conditionalRequest)
if err != None {
fmt.Printf("❌ Request failed: %s\n", err)
return
}
if response["status"] == 304 {
fmt.Printf("✅ Content not modified - using cache\n")
return // Use cached content
}
}
// Fetch new content
var response, err = http.Get(url)
if err != None {
fmt.Printf("❌ Request failed: %s\n", err)
return
}
var newETag = response["headers"]["ETag"]
fmt.Printf("✅ New content received - ETag: %s\n", newETag)
}
|
If-Modified-Since Validation
| If-Modified-Since Validation |
|---|
| package main
import http
import fmt
function fetchIfModified(url string, lastModified string) {
var request, _ = http.NewRequest("GET", url, "")
if lastModified != "" {
request, _ = http.SetHeader(request, "If-Modified-Since", lastModified)
}
var response, err = http.Do(request)
if err != None {
fmt.Printf("❌ Request failed: %s\n", err)
return
}
if response["status"] == 304 {
fmt.Printf("✅ Content not modified since %s\n", lastModified)
} else {
var newLastModified = response["headers"]["Last-Modified"]
fmt.Printf("✅ Content updated - Last-Modified: %s\n", newLastModified)
}
}
|
Request Cancellation
Context-based request cancellation and timeout management.
Request with Timeout
| Request with Timeout |
|---|
| package main
import http
import fmt
function requestWithTimeout(url string, timeoutSeconds int) {
fmt.Printf("⏱️ Making request with %d second timeout\n", timeoutSeconds)
var request, _ = http.NewRequest("GET", url, "")
// Note: In full implementation, timeout would be set on request
var response, err = http.Do(request)
if err != None {
if err == "request timeout" or err == "context deadline exceeded" {
fmt.Printf("⏰ Request timed out after %d seconds\n", timeoutSeconds)
} else {
fmt.Printf("❌ Request failed: %s\n", err)
}
return
}
fmt.Printf("✅ Request completed within timeout - Status: %d\n", response["status"])
}
|
Cancellable Request Chain
| Cancellable Request Chain |
|---|
| package main
import http
import fmt
function cancellableRequestChain(urls array, timeoutPerRequest int) {
fmt.Printf("🔗 Processing %d URLs with %ds timeout each\n", len(urls), timeoutPerRequest)
for i, url in urls {
fmt.Printf("🔄 Request %d/%d: %s\n", i+1, len(urls), url)
var response, err = http.Get(url)
if err != None {
fmt.Printf("❌ Request %d failed: %s\n", i+1, err)
continue // Continue with next URL
}
fmt.Printf("✅ Request %d completed - Status: %d\n", i+1, response["status"])
}
}
|
Middleware Chain
Easy middleware composition through handler wrapping and function chaining.
Basic Middleware Components
| Basic Middleware Components |
|---|
| package main
import http
import fmt
// Logging middleware
function loggingMiddleware(next function) {
return function(request, response) {
var method = request["method"]
var path = request["url"]
fmt.Printf("🔄 [LOG] %s %s - Started\n", method, path)
next(request, response)
var status = response["status"]
fmt.Printf("✅ [LOG] %s %s - Completed (%d)\n", method, path, status)
}
}
// Authentication middleware
function authMiddleware(next function) {
return function(request, response) {
var authHeader = request["headers"]["Authorization"]
if authHeader == None or authHeader == "" {
fmt.Printf("❌ [AUTH] No authorization header\n")
response["status"] = 401
return
}
if authHeader == "Bearer valid-token" {
fmt.Printf("✅ [AUTH] Valid token\n")
next(request, response)
} else {
fmt.Printf("❌ [AUTH] Invalid token\n")
response["status"] = 403
}
}
}
// CORS middleware
function corsMiddleware(next function) {
return function(request, response) {
fmt.Printf("🌐 [CORS] Adding CORS headers\n")
if request["method"] == "OPTIONS" {
fmt.Printf("✅ [CORS] Preflight handled\n")
response["status"] = 200
return
}
next(request, response)
}
}
### Middleware Chain Composition
```harneet title="Middleware Chain Composition"
package main
import http
import fmt
// Compose middleware chain
function createMiddlewareChain(middlewares array, handler function) {
var result = handler
// Apply middlewares in reverse order
for middleware in middlewares {
result = middleware(result)
}
return result
}
// Example handler
function apiHandler(request, response) {
fmt.Printf("📄 [HANDLER] Processing API request\n")
response["status"] = 200
}
// Usage
var middlewares = [loggingMiddleware, corsMiddleware, authMiddleware]
var protectedHandler = createMiddlewareChain(middlewares, apiHandler)
## Request Cloning
Methods to clone and modify HTTP requests for middleware and testing.
### Request Variation Testing
```harneet title="Request Variation Testing"
package main
import http
import fmt
function testRequestVariations(baseURL string, endpoint string) {
// Test different authentication methods
var testCases = [
{"name": "No Auth", "header": "", "value": ""},
{"name": "Bearer Token", "header": "Authorization", "value": "Bearer token123"},
{"name": "API Key", "header": "X-API-Key", "value": "api-key-456"},
{"name": "Basic Auth", "header": "Authorization", "value": "Basic dXNlcjpwYXNz"}
]
for testCase in testCases {
fmt.Printf("\n🧪 Testing: %s\n", testCase["name"])
// Clone base request
var testRequest, _ = http.NewRequest("GET", baseURL + endpoint, "")
testRequest, _ = http.SetHeader(testRequest, "User-Agent", "TestClient/1.0")
// Add test-specific header
if testCase["header"] != "" {
testRequest, _ = http.SetHeader(testRequest, testCase["header"], testCase["value"])
}
var response, err = http.Do(testRequest)
if err != None {
fmt.Printf("❌ Test failed: %s\n", err)
} else {
fmt.Printf("✅ Status: %d\n", response["status"])
}
}
}
### Retry with Request Modifications
```harneet title="Retry with Request Modifications"
package main
import http
import fmt
import time
function retryWithModifications(originalURL string, maxRetries int) {
for attempt in range(maxRetries) {
var request, _ = http.NewRequest("GET", originalURL, "")
// Add retry-specific headers
request, _ = http.SetHeader(request, "X-Retry-Attempt", attempt + 1)
request, _ = http.SetHeader(request, "X-Request-ID", "req-" + (attempt + 1))
var response, err = http.Do(request)
if err == None and response["status"] < 500 {
fmt.Printf("✅ Success on attempt %d\n", attempt + 1)
return
}
fmt.Printf("⏳ Attempt %d failed, retrying...\n", attempt + 1)
}
}
## Multipart Forms
Built-in support for parsing multipart/form-data including file uploads.
### Multipart Form Upload
```harneet title="Multipart Form Upload"
package main
import http
import fmt
function uploadMultipartForm(url string, fields map, files array) {
var boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
var multipartBody = ""
// Add form fields
for key, value in fields {
multipartBody = multipartBody + "--" + boundary + "\r\n"
multipartBody = multipartBody + "Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n"
multipartBody = multipartBody + value + "\r\n"
}
// Add files
for file in files {
multipartBody = multipartBody + "--" + boundary + "\r\n"
multipartBody = multipartBody + "Content-Disposition: form-data; name=\"" + file["field"] + "\"; filename=\"" + file["name"] + "\"\r\n"
multipartBody = multipartBody + "Content-Type: " + file["type"] + "\r\n\r\n"
multipartBody = multipartBody + file["content"] + "\r\n"
}
multipartBody = multipartBody + "--" + boundary + "--\r\n"
var response, err = http.Post(url, "multipart/form-data; boundary=" + boundary, multipartBody)
if err != None {
fmt.Printf("❌ Upload failed: %s\n", err)
} else if response["status"] == 200 {
fmt.Printf("✅ Upload successful!\n")
} else {
fmt.Printf("❌ Upload failed - Status: %d\n", response["status"])
}
}
### File Upload with Validation
```harneet title="File Upload with Validation"
package main
import http
import fmt
function uploadWithValidation(url string, filename string, content string, maxSize int) {
if len(content) > maxSize {
fmt.Printf("❌ File too large: %d bytes (max: %d)\n", len(content), maxSize)
return
}
var allowedTypes = ["txt", "pdf", "jpg", "png"]
var extension = getFileExtension(filename)
var isAllowed = false
for allowedType in allowedTypes {
if extension == allowedType {
isAllowed = true
break
}
}
if !isAllowed {
fmt.Printf("❌ File type not allowed: %s\n", extension)
return
}
var fields = {"description": "File upload", "category": "document"}
var files = [{"field": "file", "name": filename, "type": "text/plain", "content": content}]
uploadMultipartForm(url, fields, files)
}
function getFileExtension(filename string) string {
// Simplified extension extraction
return "txt" // In real implementation, extract from filename
}
## Keep-Alive Control
Connection keep-alive management and configuration options.
### Optimized Client with Keep-Alive
```harneet title="Optimized Client with Keep-Alive"
package main
import http
import fmt
function createOptimizedClient(maxConnections int, keepAliveTimeout int) map {
return {
"maxConnections": maxConnections,
"keepAliveTimeout": keepAliveTimeout,
"userAgent": "OptimizedClient/1.0"
}
}
function makeOptimizedRequest(client map, url string) {
var request, _ = http.NewRequest("GET", url, "")
// Set keep-alive headers
request, _ = http.SetHeader(request, "Connection", "keep-alive")
request, _ = http.SetHeader(request, "Keep-Alive", "timeout=" + client["keepAliveTimeout"])
request, _ = http.SetHeader(request, "User-Agent", client["userAgent"])
var response, err = http.Do(request)
if err != None {
fmt.Printf("❌ Request failed: %s\n", err)
return
}
var connection = response["headers"]["Connection"]
if connection == "keep-alive" {
fmt.Printf("✅ Keep-alive connection established\n")
}
fmt.Printf("✅ Request completed - Status: %d\n", response["status"])
}
### Batch Requests with Connection Reuse
```harneet title="Batch Requests with Connection Reuse"
package main
import http
import fmt
function batchRequestsWithKeepAlive(client map, urls array) {
fmt.Printf("📦 Processing %d URLs with connection reuse\n", len(urls))
for i, url in urls {
fmt.Printf("🔄 Request %d/%d: %s\n", i+1, len(urls), url)
makeOptimizedRequest(client, url)
}
fmt.Printf("🎉 Batch complete with optimized connections\n")
}
// Usage
var client = createOptimizedClient(10, 30) // 10 connections, 30s timeout
var urls = [
"https://api.example.com/users",
"https://api.example.com/posts",
"https://api.example.com/comments"
]
batchRequestsWithKeepAlive(client, urls)
|
Integration Examples
Complete Advanced HTTP Client
| Complete Advanced HTTP Client |
|---|
| package main
import http
import json
import fmt
function createAdvancedHTTPClient() map {
return {
"timeout": 30,
"retries": 3,
"keepAlive": true,
"userAgent": "AdvancedClient/1.0"
}
}
function advancedRequest(client map, method string, url string, body string, options map) {
var request, _ = http.NewRequest(method, url, body)
// Apply client defaults
request, _ = http.SetHeader(request, "User-Agent", client["userAgent"])
// Apply conditional headers if provided
if options["etag"] != None {
request, _ = http.SetHeader(request, "If-None-Match", options["etag"])
}
if options["lastModified"] != None {
request, _ = http.SetHeader(request, "If-Modified-Since", options["lastModified"])
}
// Apply range if provided
if options["rangeStart"] != None and options["rangeEnd"] != None {
var rangeHeader = "bytes=" + options["rangeStart"] + "-" + options["rangeEnd"]
request, _ = http.SetHeader(request, "Range", rangeHeader)
}
// Retry with exponential backoff
var attempt = 0
for attempt < client["retries"] {
attempt = attempt + 1
var requestCopy, _ = http.NewRequest(method, url, body)
requestCopy, _ = http.SetHeader(requestCopy, "X-Attempt", attempt)
var response, err = http.Do(requestCopy)
if err == None {
return response, None
}
if attempt < client["retries"] {
var backoff = attempt * 2
fmt.Printf("⏳ Attempt %d failed, retrying in %d seconds...\n", attempt, backoff)
}
}
return None, "All retry attempts failed"
}
// Usage
var client = createAdvancedHTTPClient()
var options = {"etag": "\"abc123\"", "rangeStart": 0, "rangeEnd": 1023}
var response, err = advancedRequest(client, "GET", "https://api.example.com/data", "", options)
|
These advanced HTTP features provide enterprise-level capabilities for building robust web applications and APIs in Harneet with modern tuple destructuring syntax. // Check existing file size var existingSize, _ = os.FileSize(localFile)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 | if existingSize > 0 {
fmt.Printf("🔄 Resuming download from byte %d\n", existingSize)
var request, _ = http.NewRequest("GET", url, "")
var rangeRequest, _ = http.SetRange(request, existingSize, -1) // -1 means to end
var response, err = http.Do(rangeRequest)
if err != None {
fmt.Printf("❌ Resume failed: %s\n", err)
return
}
if response["status"] == 206 {
fmt.Printf("✅ Resuming download...\n")
// Append to existing file: response["body"]
} else {
fmt.Printf("⚠️ Server doesn't support resume, starting over\n")
// Start fresh download
}
}
|
} ```
Conditional Requests
Support for If-Modified-Since, ETag, and other conditional headers.
Sets conditional headers for cache validation. Examples: Cache Validation with ETag: harneet title="Cache Validation with ETag" import http import fmt function fetchWithETag(url string, cachedETag string) { var request, _ = http.NewRequest("GET", url, "") if cachedETag != "" { var conditionalRequest, _ = http.SetHeader(request, "If-None-Match", cachedETag) var response, err = http.Do(conditionalRequest) if err != None { fmt.Printf("❌ Request failed: %s\n", err) return None, "" } if response["status"] == 304 { fmt.Printf("✅ Content not modified, using cache\n") return None, cachedETag // Use cached content } } var response, err = http.Do(request) if err != None { return None, "" } var newETag = response["headers"]["ETag"] fmt.Printf("✅ New content received, ETag: %s\n", newETag) return response["body"], newETag } // Usage var cachedETag = "\"abc123\"" var content, etag = fetchWithETag("https://api.example.com/data", cachedETag)
If-Modified-Since Validation:
| If-Modified-Since Cache Validation |
|---|
| import http
import fmt
function fetchIfModified(url string, lastModified string) {
var request, _ = http.NewRequest("GET", url, "")
if lastModified != "" {
var conditionalRequest, _ = http.SetHeader(request, "If-Modified-Since", lastModified)
var response, err = http.Do(conditionalRequest)
if err != None {
fmt.Printf("❌ Request failed: %s\n", err)
return None
}
if response["status"] == 304 {
fmt.Printf("✅ Content not modified since %s\n", lastModified)
return None // Use cached content
}
}
var response, err = http.Do(request)
if err != None {
return None
}
var newLastModified = response["headers"]["Last-Modified"]
fmt.Printf("✅ Content modified, new date: %s\n", newLastModified)
return response["body"]
}
|
Request Cancellation
Context-based request cancellation for both client and server.
http.WithTimeout(request, seconds)
Sets a timeout for request cancellation.
Examples:
Request with Timeout:
| Fetch with Timeout |
|---|
| import http
import fmt
function fetchWithTimeout(url string, timeoutSeconds int) {
var request, _ = http.NewRequest("GET", url, "")
var timeoutRequest, _ = http.WithTimeout(request, timeoutSeconds)
var response, err = http.Do(timeoutRequest)
if err != None {
if err == "request timeout" {
fmt.Printf("⏰ Request timed out after %d seconds\n", timeoutSeconds)
} else {
fmt.Printf("❌ Request failed: %s\n", err)
}
return None
}
fmt.Printf("✅ Request completed within timeout\n")
return response
}
// Usage
var response = fetchWithTimeout("https://slow-api.example.com/data", 5)
|
Cancellable Request Chain:
| Fetch Multiple with Cancel |
|---|
| import http
import fmt
function fetchMultipleWithCancel(urls array, timeoutSeconds int) {
var results = []
for url in urls {
fmt.Printf("🔄 Fetching: %s\n", url)
var request, _ = http.NewRequest("GET", url, "")
var timeoutRequest, _ = http.WithTimeout(request, timeoutSeconds)
var response, err = http.Do(timeoutRequest)
if err != None {
fmt.Printf("❌ Failed to fetch %s: %s\n", url, err)
// Continue with next URL or break based on strategy
continue
}
results = append(results, {
"url": url,
"status": response["status"],
"data": response["body"]
})
fmt.Printf("✅ Completed: %s (Status: %d)\n", url, response["status"])
}
return results
}
|
Middleware Chain
Easy middleware composition through handler wrapping and function chaining.
http.Chain(middlewares, handler)
Chains multiple middleware functions around a handler.
Examples:
Logging Middleware:
| Logging Middleware |
|---|
| import http
import fmt
import time
function loggingMiddleware(next function) {
return function(request, response) {
var start = time.Now()
var method = request["method"]
var path = request["path"]
fmt.Printf("🔄 %s %s - Started\n", method, path)
// Call next handler
next(request, response)
var duration = time.Since(start)
var status = response["status"]
fmt.Printf("✅ %s %s - %d (%s)\n", method, path, status, duration)
}
}
function authMiddleware(next function) {
return function(request, response) {
var authHeader = request["headers"]["Authorization"]
if authHeader == None or authHeader == "" {
http.WriteResponse(response, 401, "application/json",
"{\"error\": \"Authorization required\"}")
return
}
// Validate token (simplified)
if !isValidToken(authHeader) {
http.WriteResponse(response, 403, "application/json",
"{\"error\": \"Invalid token\"}")
return
}
// Add user info to request context
request["user"] = getUserFromToken(authHeader)
next(request, response)
}
}
function corsMiddleware(next function) {
return function(request, response) {
// Set CORS headers
response["headers"]["Access-Control-Allow-Origin"] = "*"
response["headers"]["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
response["headers"]["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
if request["method"] == "OPTIONS" {
http.WriteResponse(response, 200, "text/plain", "")
return
}
next(request, response)
}
}
// Chain middleware
function createProtectedHandler(handler function) {
return corsMiddleware(
loggingMiddleware(
authMiddleware(handler)
)
)
}
// Usage
function apiHandler(request, response) {
var user = request["user"]
var data = {"message": "Hello " + user["name"], "protected": true}
var jsonData, _ = json.Marshal(data)
http.WriteResponse(response, 200, "application/json", jsonData)
}
var protectedHandler = createProtectedHandler(apiHandler)
http.HandleFunc(mux, "/api/protected", protectedHandler)
|
Rate Limiting Middleware:
| Rate Limiting Middleware |
|---|
| import http
import fmt
import time
// Simple in-memory rate limiter
var rateLimiter = {}
function rateLimitMiddleware(requestsPerMinute int) {
return function(next function) {
return function(request, response) {
var clientIP = request["remote_addr"]
var now = time.Now()
var minute = now / 60 // Simple minute bucket
var key = clientIP + ":" + minute
var count = rateLimiter[key]
if count == None {
count = 0
}
if count >= requestsPerMinute {
http.WriteResponse(response, 429, "application/json",
"{\"error\": \"Rate limit exceeded\"}")
return
}
rateLimiter[key] = count + 1
next(request, response)
}
}
}
// Usage
var rateLimitedHandler = rateLimitMiddleware(100)(apiHandler)
|
Request Cloning
Methods to clone and modify HTTP requests for middleware and testing.
http.CloneRequest(request)
Creates a deep copy of an HTTP request.
Examples:
Request Modification for Testing:
| Request Modification for Testing |
|---|
| import http
import fmt
function testAPIWithDifferentHeaders(baseRequest map) {
var testCases = [
{"User-Agent": "TestBot/1.0", "expected": 200},
{"User-Agent": "BadBot/1.0", "expected": 403},
{"Authorization": "Bearer valid-token", "expected": 200},
{"Authorization": "Bearer invalid-token", "expected": 401}
]
for testCase in testCases {
// Clone the base request
var testRequest, _ = http.CloneRequest(baseRequest)
// Modify headers for this test
for header, value in testCase {
if header != "expected" {
testRequest, _ = http.SetHeader(testRequest, header, value)
}
}
var response, err = http.Do(testRequest)
var expectedStatus = testCase["expected"]
if err != None {
fmt.Printf("❌ Test failed: %s\n", err)
continue
}
if response["status"] == expectedStatus {
fmt.Printf("✅ Test passed: %s = %d\n", testCase, expectedStatus)
} else {
fmt.Printf("❌ Test failed: expected %d, got %d\n", expectedStatus, response["status"])
}
}
}
// Usage
var baseRequest, _ = http.NewRequest("GET", "https://api.example.com/test", "")
testAPIWithDifferentHeaders(baseRequest)
|
Request Retry with Modifications:
| Request Retry with Modifications |
|---|
| import http
import fmt
import time
function retryWithBackoff(originalRequest map, maxRetries int) {
var attempt = 0
for attempt < maxRetries {
attempt = attempt + 1
// Clone request for this attempt
var request, _ = http.CloneRequest(originalRequest)
// Add retry headers
request, _ = http.SetHeader(request, "X-Retry-Attempt", attempt)
request, _ = http.SetHeader(request, "X-Request-ID", generateRequestID())
var response, err = http.Do(request)
if err == None and response["status"] < 500 {
fmt.Printf("✅ Request succeeded on attempt %d\n", attempt)
return response
}
if attempt < maxRetries {
var backoffSeconds = attempt * 2 // Exponential backoff
fmt.Printf("⏳ Attempt %d failed, retrying in %d seconds...\n", attempt, backoffSeconds)
time.Sleep(backoffSeconds)
}
}
fmt.Printf("❌ All %d attempts failed\n", maxRetries)
return None
}
|
Built-in support for parsing multipart/form-data including file uploads.
http.ParseMultipart(request)
Parses multipart form data from a request.
Examples:
File Upload Handler:
| File Upload Handler |
|---|
| import http
import fmt
import os
function fileUploadHandler(request, response) {
if request["method"] != "POST" {
http.WriteResponse(response, 405, "text/plain", "Method not allowed")
return
}
var contentType = request["headers"]["Content-Type"]
if !strings.Contains(contentType, "multipart/form-data") {
http.WriteResponse(response, 400, "application/json",
"{\"error\": \"Expected multipart/form-data\"}")
return
}
var multipart, err = http.ParseMultipart(request)
if err != None {
http.WriteResponse(response, 400, "application/json",
"{\"error\": \"Failed to parse multipart data\"}")
return
}
// Process form fields
var description = multipart["fields"]["description"]
var category = multipart["fields"]["category"]
// Process uploaded files
var uploadedFiles = []
for file in multipart["files"] {
var filename = file["filename"]
var content = file["content"]
var size = file["size"]
// Save file
var savedPath, saveErr = os.WriteFile("uploads/" + filename, content)
if saveErr != None {
fmt.Printf("❌ Failed to save %s: %s\n", filename, saveErr)
continue
}
uploadedFiles = append(uploadedFiles, {
"filename": filename,
"size": size,
"path": savedPath
})
fmt.Printf("✅ Saved file: %s (%d bytes)\n", filename, size)
}
var result = {
"message": "Upload successful",
"description": description,
"category": category,
"files": uploadedFiles
}
var jsonResponse, _ = json.Marshal(result)
http.WriteResponse(response, 200, "application/json", jsonResponse)
}
// Register handler
http.HandleFunc(mux, "/upload", fileUploadHandler)
|
Form Data Processing:
| Form Data Processing |
|---|
| import http
import fmt
function processFormData(request, response) {
var multipart, err = http.ParseMultipart(request)
if err != None {
http.WriteResponse(response, 400, "application/json",
"{\"error\": \"Invalid form data\"}")
return
}
// Validate required fields
var requiredFields = ["name", "email", "message"]
var missingFields = []
for field in requiredFields {
if multipart["fields"][field] == None or multipart["fields"][field] == "" {
missingFields = append(missingFields, field)
}
}
if len(missingFields) > 0 {
var errorMsg = "Missing required fields: " + strings.Join(missingFields, ", ")
http.WriteResponse(response, 400, "application/json",
"{\"error\": \"" + errorMsg + "\"}")
return
}
// Process the form
var formData = {
"name": multipart["fields"]["name"],
"email": multipart["fields"]["email"],
"message": multipart["fields"]["message"],
"timestamp": time.Now()
}
// Save to database or process as needed
fmt.Printf("📝 Form submitted by: %s (%s)\n", formData["name"], formData["email"])
var response = {"message": "Form submitted successfully", "id": generateID()}
var jsonResponse, _ = json.Marshal(response)
http.WriteResponse(response, 200, "application/json", jsonResponse)
}
|
Keep-Alive Control
Connection keep-alive management and configuration options.
http.SetKeepAlive(request, enabled, timeout)
Controls connection keep-alive behavior.
Examples:
Connection Pool Management:
| Connection Pool Management |
|---|
| import http
import fmt
function createOptimizedClient(maxConnections int, keepAliveTimeout int) {
var client = {
"maxConnections": maxConnections,
"keepAliveTimeout": keepAliveTimeout,
"connections": {}
}
return client
}
function makeOptimizedRequest(client map, url string) {
var request, _ = http.NewRequest("GET", url, "")
// Enable keep-alive with timeout
var keepAliveRequest, _ = http.SetKeepAlive(request, true, client["keepAliveTimeout"])
// Set connection pooling headers
keepAliveRequest, _ = http.SetHeader(keepAliveRequest, "Connection", "keep-alive")
keepAliveRequest, _ = http.SetHeader(keepAliveRequest, "Keep-Alive", "timeout=" + client["keepAliveTimeout"])
var response, err = http.Do(keepAliveRequest)
if err != None {
fmt.Printf("❌ Request failed: %s\n", err)
return None
}
fmt.Printf("✅ Request completed with keep-alive\n")
return response
}
// Usage
var client = createOptimizedClient(10, 30) // 10 connections, 30s timeout
// Make multiple requests that reuse connections
var urls = ["https://api.example.com/users", "https://api.example.com/posts", "https://api.example.com/comments"]
for url in urls {
var response = makeOptimizedRequest(client, url)
// Process response
}
|
Server Keep-Alive Configuration:
| Server Keep-Alive Configuration |
|---|
| import http
import fmt
function createKeepAliveServer(addr string, keepAliveTimeout int) {
var server, _ = http.NewServer(addr)
// Configure keep-alive settings
server["keepAliveTimeout"] = keepAliveTimeout
server["maxKeepAliveRequests"] = 100
server["keepAliveEnabled"] = true
return server
}
function keepAliveHandler(request, response) {
// Set keep-alive response headers
response["headers"]["Connection"] = "keep-alive"
response["headers"]["Keep-Alive"] = "timeout=30, max=100"
var data = {"message": "Keep-alive enabled", "timestamp": time.Now()}
var jsonData, _ = json.Marshal(data)
http.WriteResponse(response, 200, "application/json", jsonData)
}
// Usage
var server = createKeepAliveServer(":8080", 30)
var mux, _ = http.NewMux()
http.HandleFunc(mux, "/api/data", keepAliveHandler)
http.SetHandler(server, mux)
fmt.Println("🚀 Keep-alive server starting on :8080")
http.ListenAndServe(server)
|
Integration Examples
Complete Advanced HTTP Client:
| Complete HTTP Client Example |
|---|
| import http
import json
import fmt
import time
function createAdvancedHTTPClient() {
return {
"timeout": 30,
"retries": 3,
"keepAlive": true,
"userAgent": "AdvancedClient/1.0"
}
}
function advancedRequest(client map, method string, url string, body string, options map) {
var request, _ = http.NewRequest(method, url, body)
// Apply client defaults
request, _ = http.WithTimeout(request, client["timeout"])
request, _ = http.SetKeepAlive(request, client["keepAlive"], 30)
request, _ = http.SetHeader(request, "User-Agent", client["userAgent"])
// Apply conditional headers if provided
if options["etag"] != None {
request, _ = http.SetHeader(request, "If-None-Match", options["etag"])
}
if options["lastModified"] != None {
request, _ = http.SetHeader(request, "If-Modified-Since", options["lastModified"])
}
// Apply range if provided
if options["rangeStart"] != None and options["rangeEnd"] != None {
request, _ = http.SetRange(request, options["rangeStart"], options["rangeEnd"])
}
// Retry with exponential backoff
var attempt = 0
for attempt < client["retries"] {
attempt = attempt + 1
var requestCopy, _ = http.CloneRequest(request)
requestCopy, _ = http.SetHeader(requestCopy, "X-Attempt", attempt)
var response, err = http.Do(requestCopy)
if err == None {
return response, None
}
if attempt < client["retries"] {
var backoff = attempt * 2
fmt.Printf("⏳ Attempt %d failed, retrying in %d seconds...\n", attempt, backoff)
time.Sleep(backoff)
}
}
return None, "All retry attempts failed"
}
// Usage
var client = createAdvancedHTTPClient()
var options = {"etag": "\"abc123\"", "rangeStart": 0, "rangeEnd": 1023}
var response, err = advancedRequest(client, "GET", "https://api.example.com/data", "", options)
|
These advanced HTTP features provide enterprise-level capabilities for building robust web applications and APIs in Harneet.