client

package module
v0.0.0-...-d0ab5de Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

README

WASM HTTP Client

A lightweight, TinyGo-compatible HTTP client for WebAssembly modules. This client provides a simple and efficient way to make HTTP requests from WASM modules using host functions.

Features

  • Simple, straightforward API
  • Support for all standard HTTP methods (GET, POST, PUT, DELETE, etc.)
  • Type-safe header management
  • Configurable buffer sizes for headers and body
  • TinyGo compatibility
  • Error handling with specific error types

Usage

Basic Examples
// Create a new client
client := NewClient()

// Simple GET request
resp, err := client.Get("https://api.example.com", nil)
if err != nil {
    // Handle error
}
fmt.Printf("Status: %d\nBody: %s\n", resp.StatusCode, resp.Body)

// POST request with headers and body
headers := make(Headers)
headers.Set("Content-Type", "application/json")
headers.Set("Authorization", "Bearer token123")

resp, err = client.Post(
    "https://api.example.com/data",
    headers,
    `{"key": "value"}`,
)
Working with Headers
headers := make(Headers)

// Add multiple values for the same header
headers.Add("Accept", "application/json")
headers.Add("Accept", "text/plain")

// Set (replace) header value
headers.Set("Content-Type", "application/json")

// Get first header value
contentType := headers.Get("Content-Type")

// Get all values for a header
accepts := headers.Values("Accept")
All Available Methods
client := NewClient()

// GET request
resp, err := client.Get(url, headers)

// POST request
resp, err := client.Post(url, headers, body)

// PUT request
resp, err := client.Put(url, headers, body)

// DELETE request
resp, err := client.Delete(url, headers)

// HEAD request
resp, err := client.Head(url, headers)

// OPTIONS request
resp, err := client.Options(url, headers)

// PATCH request
resp, err := client.Patch(url, headers, body)

// Generic request (if needed)
resp, err := client.Request(method, url, headers, body)
Response Handling
resp, err := client.Get("https://api.example.com", nil)
if err != nil {
    switch e := err.(type) {
    case *HTTPError:
        fmt.Printf("HTTP error: %s (code: %d)\n", e.Message, e.Code)
    default:
        fmt.Printf("Error: %v\n", err)
    }
    return
}

// Access response data
fmt.Printf("Status Code: %d\n", resp.StatusCode)
fmt.Printf("Body: %s\n", resp.Body)

// Access response headers
contentType := resp.Headers.Get("Content-Type")

Configuration

The client supports configurable buffer sizes for headers and body:

client := &Client{
    HeadersBufferSize: 16 * 1024,  // 16KB for headers
    BodyBufferSize:    512 * 1024, // 512KB for body
}

Default buffer sizes:

  • Headers: 8KB
  • Body: 256KB

Error Handling

The client returns specific error types for different failure scenarios:

  • StatusInvalidURL: Invalid URL format or structure
  • StatusNetworkError: Network-related errors
  • StatusTimeout: Request timed out
  • StatusNotAllowed: Host not allowed by security policy
  • StatusTooLarge: Response too large for buffer
  • StatusBadInput: Invalid input parameters
  • StatusMemoryError: Memory allocation or access error

Environment Variables (Test Program)

When using the test program, configure the HTTP request using these environment variables:

  • HTTP_METHOD: The HTTP method to use (GET, POST, etc.)
  • HTTP_URL: The target URL (required)
  • HTTP_HEADERS: Headers in "Key: Value" format, one per line
  • HTTP_BODY: Request body content

Example:

export HTTP_URL="https://api.example.com"
export HTTP_METHOD="POST"
export HTTP_HEADERS="Content-Type: application/json\nAuthorization: Bearer token123"
export HTTP_BODY='{"key": "value"}'

Documentation

Overview

Package client provides a TinyGo-compatible client for the HTTP host functions.

Index

Constants

View Source
const (
	MethodGet     uint32 = 0
	MethodPost    uint32 = 1
	MethodPut     uint32 = 2
	MethodDelete  uint32 = 3
	MethodHead    uint32 = 4
	MethodOptions uint32 = 5
	MethodPatch   uint32 = 6
)

HTTP request method constants

View Source
const (
	StatusSuccess      uint32 = 0
	StatusInvalidURL   uint32 = 1
	StatusNetworkError uint32 = 2
	StatusTimeout      uint32 = 3
	StatusNotAllowed   uint32 = 4
	StatusTooLarge     uint32 = 5
	StatusBadInput     uint32 = 6
	StatusMemoryError  uint32 = 7
)

Result codes

View Source
const (
	DefaultHeadersBufferSize = 8 * 1024   // 8KB for headers
	DefaultBodyBufferSize    = 256 * 1024 // 256KB for body
)

Default buffer sizes

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// HeadersBufferSize is the size of the buffer for response headers
	HeadersBufferSize uint32
	// BodyBufferSize is the size of the buffer for response body
	BodyBufferSize uint32
}

Client is a HTTP client for making requests using the host functions

func NewClient

func NewClient() *Client

NewClient creates a new HTTP client with default buffer sizes

func (*Client) Delete

func (c *Client) Delete(url string, headers Headers) (*Response, error)

Delete makes a DELETE request

func (*Client) Get

func (c *Client) Get(url string, headers Headers) (*Response, error)

Get makes a GET request

func (*Client) Head

func (c *Client) Head(url string, headers Headers) (*Response, error)

Head makes a HEAD request

func (*Client) Options

func (c *Client) Options(url string, headers Headers) (*Response, error)

Options makes an OPTIONS request

func (*Client) Patch

func (c *Client) Patch(url string, headers Headers, body string) (*Response, error)

Patch makes a PATCH request

func (*Client) Post

func (c *Client) Post(url string, headers Headers, body string) (*Response, error)

Post makes a POST request

func (*Client) Put

func (c *Client) Put(url string, headers Headers, body string) (*Response, error)

Put makes a PUT request

func (*Client) Request

func (c *Client) Request(method uint32, url string, headers Headers, body string) (*Response, error)

Request makes a HTTP request and returns the response

type HTTPError

type HTTPError struct {
	Code    uint32
	Message string
}

HTTPError represents an error from the HTTP client

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Headers

type Headers map[string][]string

Headers represents HTTP headers as a map

func ParseHeaders

func ParseHeaders(headerStr string) Headers

ParseHeaders parses a header string into a Headers map

func (Headers) Add

func (h Headers) Add(key, value string)

Add adds a header value for a given key

func (Headers) Get

func (h Headers) Get(key string) string

Get returns the first value for a given header key

func (Headers) Set

func (h Headers) Set(key, value string)

Set sets a header value for a given key, replacing any existing values

func (Headers) String

func (h Headers) String() string

String converts headers to a string format for internal use

func (Headers) Values

func (h Headers) Values(key string) []string

Values returns all values for a given header key

type Response

type Response struct {
	StatusCode int     // HTTP status code
	Headers    Headers // Response headers
	Body       string  // Response body
}

Response represents an HTTP response

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址