Skip to content

HTTP Client

The HTTP client provides simple, high-level functions for making HTTP requests. These functions handle the most common HTTP operations with minimal setup required.

Basic HTTP Methods

http.Get(url)

Performs an HTTP GET request to the specified URL.

Syntax:

Get Syntax
http.Get(url) (response, error)

Parameters: - url (string) - The target URL

Returns: - response (map) - Response object with status, headers, and body - error - None on success, error message on failure

Examples:

Basic GET Request:

A basic GET request
package main
import http
import fmt

// Simple GET request
var result = http.Get("https://api.github.com/users/octocat")
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("Status Text: %s\n", response["statusText"])
    fmt.Printf("Content-Type: %s\n", response["headers"]["Content-Type"])
    fmt.Printf("Body: %s\n", response["body"])
}

API Data Fetching:

API Data Fetching
package main
import http
import json
import fmt

// Fetch user data from API
var result = http.Get("https://jsonplaceholder.typicode.com/users/1")
var response = result[0]
var err = result[1]

if err != None {
    fmt.Printf("Network Error: %s\n", err)
} else if response["status"] != 200 {
    fmt.Printf("HTTP Error: %d - %s\n", response["status"], response["statusText"])
} else {
    // Parse JSON response
    var userData, parseErr = json.Unmarshal(response["body"])
    if parseErr != None {
        fmt.Printf("JSON Parse Error: %s\n", parseErr)
    } else {
        fmt.Printf("User Name: %s\n", userData["name"])
        fmt.Printf("User Email: %s\n", userData["email"])
    }
}

Health Check Example:

Health Check Example
package main
import http
import fmt

function checkHealth(url string) {
    var result = http.Get(url + "/health")
    var response = result[0]
    var err = result[1]

    if err != None {
        fmt.Printf("❌ %s is DOWN - %s\n", url, err)
    } else if response["status"] == 200 {
        fmt.Printf("✅ %s is UP - Status: %d\n", url, response["status"])
    } else {
        fmt.Printf("⚠️  %s has issues - Status: %d\n", url, response["status"])
    }
}

// Check multiple services
checkHealth("https://api.service1.com")
checkHealth("https://api.service2.com")

http.Post(url, contentType, body)

Performs an HTTP POST request with the specified body and content type.

Syntax:

Post Syntax
http.Post(url, contentType, body) (response, error)

Parameters: - url (string) - The target URL - contentType (string) - Content-Type header value (e.g., "application/json") - body (string) - Request body content

Examples:

JSON POST Request:

JSON POST Request
package main
import http
import json
import fmt

// Create user via API
var userData = {"name": "Alice", "email": "alice@example.com", "role": "admin"}
var jsonResult, jsonErr = json.Marshal(userData)

if jsonErr != None {
    fmt.Printf("JSON Error: %s\n", jsonErr)
} else {
    var result = http.Post("https://jsonplaceholder.typicode.com/users", "application/json", jsonResult)
    var response = result[0]
    var err = result[1]

    if err != None {
        fmt.Printf("Network Error: %s\n", err)
    } else if response["status"] == 201 {
        fmt.Printf("✅ User created successfully!\n")
        fmt.Printf("Response: %s\n", response["body"])
    } else {
        fmt.Printf("❌ Failed to create user - Status: %d\n", response["status"])
    }
}

Form Data POST:

Form Data POST
package main
import http
import fmt

// Submit form data
var formData = "name=John+Doe&email=john@example.com&message=Hello+World"
var result = http.Post("https://httpbin.org/post", "application/x-www-form-urlencoded", formData)
var response = result[0]
var err = result[1]

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

API Authentication Example:

API Authentication
package main
import http
import json
import fmt

// Login request
function login(username string, password string) {
    var credentials = {"username": username, "password": password}
    var jsonData, _ = json.Marshal(credentials)

    var result = http.Post("https://api.example.com/auth/login", "application/json", jsonData)
    var response = result[0]
    var err = result[1]

    if err != None {
        return None, err
    } else if response["status"] == 200 {
        var authData, _ = json.Unmarshal(response["body"])
        return authData["token"], None
    } else {
        return None, "Login failed: " + response["statusText"]
    }
}

// Usage
var token, loginErr = login("alice", "password123")
if loginErr != None {
    fmt.Printf("Login Error: %s\n", loginErr)
} else {
    fmt.Printf("Login successful! Token: %s\n", token)
}

http.Put(url, contentType, body)

Performs an HTTP PUT request for updating resources.

Syntax:

Put Syntax
http.Put(url, contentType, body) (response, error)

Examples:

Update Resource:

Update Resource
package main
import http
import json
import fmt

// Update user profile
function updateUser(userId string, updates map) {
    var jsonData, jsonErr = json.Marshal(updates)
    if jsonErr != None {
        return jsonErr
    }

    var url = "https://jsonplaceholder.typicode.com/users/" + userId
    var result = http.Put(url, "application/json", jsonData)
    var response = result[0]
    var err = result[1]

    if err != None {
        return err
    } else if response["status"] == 200 {
        fmt.Printf("✅ User %s updated successfully\n", userId)
        return None
    } else {
        return "Update failed with status: " + response["statusText"]
    }
}

// Usage
var userUpdates = {"name": "Alice Johnson", "email": "alice.johnson@example.com"}
var updateErr = updateUser("1", userUpdates)
if updateErr != None {
    fmt.Printf("Update Error: %s\n", updateErr)
}

http.Delete(url)

Performs an HTTP DELETE request for removing resources.

Syntax:

Delete Syntax
http.Delete(url) (response, error)

Examples:

Delete Resource:

Delete Resource
package main
import http
import fmt

// Delete user account
function deleteUser(userId string) {
    var url = "https://jsonplaceholder.typicode.com/users/" + userId
    var result = http.Delete(url)
    var response = result[0]
    var err = result[1]

    if err != None {
        return "Network error: " + err
    } else if response["status"] == 200 or response["status"] == 204 {
        fmt.Printf("✅ User %s deleted successfully\n", userId)
        return None
    } else if response["status"] == 404 {
        return "User not found"
    } else {
        return "Delete failed with status: " + response["statusText"]
    }
}

// Usage
var deleteErr = deleteUser("123")
if deleteErr != None {
    fmt.Printf("Delete Error: %s\n", deleteErr)
}

http.Head(url)

Performs an HTTP HEAD request to get headers without the response body.

Syntax:

Head Syntax
http.Head(url) (response, error)

Examples:

Check Resource Metadata:

Check Resource Metadata
package main
import http
import fmt

// Check if resource exists and get metadata
function checkResource(url string) {
    var result = http.Head(url)
    var response = result[0]
    var err = result[1]

    if err != None {
        fmt.Printf("❌ Cannot reach %s: %s\n", url, err)
    } else if response["status"] == 200 {
        var headers = response["headers"]
        fmt.Printf("✅ Resource exists at %s\n", url)
        fmt.Printf("   Content-Type: %s\n", headers["Content-Type"])
        fmt.Printf("   Content-Length: %s\n", headers["Content-Length"])
        fmt.Printf("   Last-Modified: %s\n", headers["Last-Modified"])
    } else if response["status"] == 404 {
        fmt.Printf("❌ Resource not found: %s\n", url)
    } else {
        fmt.Printf("⚠️  Resource status: %d - %s\n", response["status"], response["statusText"])
    }
}

// Usage
checkResource("https://httpbin.org/json")
checkResource("https://httpbin.org/image/png")

Client Configuration

The HTTP client comes with sensible defaults:

  • Timeout: 30 seconds
  • Connection Pooling: Automatic
  • Keep-Alive: Enabled
  • Redirects: Automatic following
  • Compression: Automatic gzip handling

Error Handling

All HTTP client functions follow the same error handling pattern:

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

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

Common HTTP Status Codes

  • 200 OK - Request successful
  • 201 Created - Resource created successfully
  • 204 No Content - Success with no response body
  • 400 Bad Request - Invalid request
  • 401 Unauthorized - Authentication required
  • 403 Forbidden - Access denied
  • 404 Not Found - Resource not found
  • 500 Internal Server Error - Server error

Best Practices

1. Always Check Errors

Always Check Errors
var result = http.Get(url)
var response = result[0]
var err = result[1]

if err != None {
    // Handle network errors first
    return err
}

if response["status"] >= 400 {
    // Then handle HTTP errors
    return "HTTP Error: " + response["statusText"]
}

// Process successful response

2. Use Appropriate Content Types

Appropriate Content Types
1
2
3
4
5
6
7
8
// JSON data
http.Post(url, "application/json", jsonData)

// Form data
http.Post(url, "application/x-www-form-urlencoded", formData)

// Plain text
http.Post(url, "text/plain", textData)

3. Handle Different Response Types

Handle Response Types
1
2
3
4
5
6
7
8
var contentType = response["headers"]["Content-Type"]
if contentType == "application/json" {
    var data, _ = json.Unmarshal(response["body"])
    // Process JSON data
} else {
    // Process as plain text
    fmt.Println(response["body"])
}

Next Steps