Skip to content

HTTP Module Overview

The HTTP module provides comprehensive HTTP client functionality by wrapping Go's powerful net/http package. This gives Harneet programs access to full-featured HTTP capabilities without reimplementing the complex networking code.

Quick Start

HTTP Quick Start
package main
import http
import fmt

// Simple GET request
var result = http.Get("https://api.example.com/data")
var response = result[0]
var err = result[1]

if err != None {
    fmt.Printf("Error: %s\n", err)
} else {
    fmt.Printf("Status: %d\n", response["status"])
    fmt.Printf("Body: %s\n", response["body"])
}

Module Import

Import HTTP Module
import http

Architecture

The HTTP module follows the facade pattern, exposing all the essential features of Go's net/http while maintaining Harneet's simple and consistent API design. All functions return (result, error) tuples following Harneet's error handling conventions.

Core Features

✅ HTTP Client Methods

  • GET requests - http.Get(url)
  • POST requests - http.Post(url, contentType, body)
  • PUT requests - http.Put(url, contentType, body)
  • DELETE requests - http.Delete(url)
  • HEAD requests - http.Head(url)

✅ Advanced Request Building

  • Custom requests - http.NewRequest(method, url, body)
  • Header management - http.SetHeader(request, key, value)
  • Request execution - http.Do(request)

✅ Response Handling

  • Status codes - response["status"]
  • Headers - response["headers"]
  • Body content - response["body"]
  • Status text - response["statusText"]

✅ Built-in Features

  • Connection pooling - Automatic via Go's http.Client
  • Timeout handling - 30-second default timeout
  • Keep-alive connections - Managed automatically
  • Compression support - Automatic gzip handling
  • Error handling - Comprehensive error reporting

Response Object Structure

All HTTP functions return a response object (map) with this structure:

Response Structure
{
    "status": 200,                    // HTTP status code (integer)
    "statusText": "200 OK",           // Full status text (string)
    "body": "response content...",    // Response body (string)
    "headers": {                      // Headers map
        "Content-Type": "application/json",
        "Content-Length": "1234",
        // ... other headers
    }
}

Error Handling Pattern

The HTTP module follows Harneet's standard error handling pattern:

Error Handling
package main
import http
import fmt
var result = http.Get("https://example.com")
var response = result[0]
var err = result[1]

if err != None {
    // Handle network errors, timeouts, etc.
    fmt.Printf("Network Error: %s\n", err)
} else if response["status"] >= 400 {
    // Handle HTTP errors
    fmt.Printf("HTTP Error %d: %s\n", response["status"], response["statusText"])
} else {
    // Success - process response
    fmt.Printf("Success: %s\n", response["body"])
}

Integration with Other Modules

The HTTP module works seamlessly with other Harneet standard library modules:

  • json - For encoding/decoding JSON request and response bodies
  • cast - For type conversions of response data
  • fmt - For formatting and displaying HTTP responses
  • log - For logging HTTP requests and responses
  • errors - For comprehensive error handling

Common Use Cases

API Client Development

API Client
1
2
3
4
5
6
7
package main
import http
// RESTful API interactions
var users = http.Get("https://api.example.com/users")[0]
var newUser = http.Post("https://api.example.com/users", "application/json", userData)[0]
var updatedUser = http.Put("https://api.example.com/users/123", "application/json", updates)[0]
var deleted = http.Delete("https://api.example.com/users/123")[0]

Authentication & Headers

Auth Headers
1
2
3
4
5
6
package main
import http
// Authenticated requests
var request = http.NewRequest("GET", "https://api.example.com/secure", "")[0]
var authRequest = http.SetHeader(request, "Authorization", "Bearer token123")[0]
var response = http.Do(authRequest)[0]

JSON API Integration

JSON API
1
2
3
4
5
6
7
8
package main
import http
import json
// JSON request/response handling
var data = {"name": "Alice", "email": "alice@example.com"}
var jsonData, _ = json.Marshal(data)
var response = http.Post("https://api.example.com/users", "application/json", jsonData)[0]
var createdUser, _ = json.Unmarshal(response["body"])

Performance Characteristics

  • Connection Reuse - Automatic HTTP keep-alive connections
  • Connection Pooling - Built-in connection pool management
  • Timeout Control - 30-second default with customization options
  • Memory Efficient - Streaming response handling
  • Thread Safe - Safe for concurrent use

Security Features

  • TLS/HTTPS Support - Automatic HTTPS handling
  • Certificate Validation - Built-in certificate verification
  • Header Security - Full control over request headers
  • Authentication Support - Bearer tokens, Basic auth, custom schemes

Next Steps

Future Enhancements

The HTTP module is designed to be easily extensible. Future enhancements may include:

  • HTTP Server - Server-side HTTP handling
  • WebSocket Support - WebSocket protocol upgrade
  • File Upload - Multipart form data handling
  • Streaming - Request/response streaming
  • Middleware - Request/response middleware chain
  • Connection Hijacking - Custom protocol support

The foundation is solid and ready for these advanced features when needed!