axios4go

package module
v0.6.7 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2026 License: Apache-2.0 Imports: 13 Imported by: 3

README

axios4go

Go Reference Go Report Card Release OpenSSF Best Practices License

axios4go is a Go HTTP client library inspired by Axios (a promise based HTTP client for node.js), providing a simple and intuitive API for making HTTP requests. It offers features like JSON handling, configurable instances, and support for various HTTP methods.

Table of Contents

Features

  • Simple and intuitive API
  • Support for GET, POST, PUT, DELETE, HEAD, OPTIONS, and PATCH methods
  • JSON request and response handling
  • Configurable client instances
  • Global and per-request timeout management
  • Redirect management
  • Basic authentication support
  • Customizable request options
  • Promise-like asynchronous requests
  • Request and response interceptors
  • Upload and download progress tracking
  • Proxy support
  • Configurable max content length and body length
  • Response caching with pluggable storage backends

Installation

To install axios4go, use go get:

go get -u github.com/rezmoss/axios4go

Note: Requires Go 1.13 or later.

Usage

Making a Simple Request
package main

import (
    "fmt"

    "github.com/rezmoss/axios4go"
)

func main() {
    resp, err := axios4go.Get("https://api.example.com/data")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    fmt.Printf("Status Code: %d\n", resp.StatusCode)
    fmt.Printf("Body: %s\n", string(resp.Body))
}
Using Request Options
resp, err := axios4go.Get("https://api.example.com/data", &axios4go.RequestOptions{
    Headers: map[string]string{
        "Authorization": "Bearer token",
    },
    Params: map[string]string{
        "query": "golang",
    },
})
Making POST Requests
body := map[string]interface{}{
    "name": "John Doe",
    "age":  30,
}
resp, err := axios4go.Post("https://api.example.com/users", body)
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
fmt.Printf("Status Code: %d\n", resp.StatusCode)
fmt.Printf("Body: %s\n", string(resp.Body))
Using Async Requests
axios4go.GetAsync("https://api.example.com/data").
    Then(func(response *axios4go.Response) {
        fmt.Printf("Status Code: %d\n", response.StatusCode)
        fmt.Printf("Body: %s\n", string(response.Body))
    }).
    Catch(func(err error) {
        fmt.Printf("Error: %v\n", err)
    }).
    Finally(func() {
        fmt.Println("Request completed")
    })
Creating a Custom Client
client := axios4go.NewClient("https://api.example.com")

resp, err := client.Request(&axios4go.RequestOptions{
    Method: "GET",
    URL:    "/users",
    Headers: map[string]string{
        "Authorization": "Bearer token",
    },
})
if err != nil {
    fmt.Printf("Error: %v\n", err)
    return
}
fmt.Printf("Status Code: %d\n", resp.StatusCode)
fmt.Printf("Body: %s\n", string(resp.Body))
Using Interceptors
options := &axios4go.RequestOptions{
    InterceptorOptions: axios4go.InterceptorOptions{
        RequestInterceptors: []func(*http.Request) error{
            func(req *http.Request) error {
                req.Header.Set("X-Custom-Header", "value")
                return nil
            },
        },
        ResponseInterceptors: []func(*http.Response) error{
            func(resp *http.Response) error {
                fmt.Printf("Response received with status: %d\n", resp.StatusCode)
                return nil
            },
        },
    },
}

resp, err := axios4go.Get("https://api.example.com/data", options)
Handling Progress
options := &axios4go.RequestOptions{
    OnUploadProgress: func(bytesRead, totalBytes int64) {
        fmt.Printf("Upload progress: %d/%d bytes\n", bytesRead, totalBytes)
    },
    OnDownloadProgress: func(bytesRead, totalBytes int64) {
        fmt.Printf("Download progress: %d/%d bytes\n", bytesRead, totalBytes)
    },
}

resp, err := axios4go.Post("https://api.example.com/upload", largeData, options)
Using Proxy
options := &axios4go.RequestOptions{
    Proxy: &axios4go.Proxy{
        Protocol: "http",
        Host:     "proxy.example.com",
        Port:     8080,
        Auth: &axios4go.Auth{
            Username: "proxyuser",
            Password: "proxypass",
        },
    },
}

resp, err := axios4go.Get("https://api.example.com/data", options)
Response Caching

axios4go supports response caching to reduce network calls. Caching is opt-in and disabled by default.

Basic Usage
import (
    "time"
    "github.com/rezmoss/axios4go"
)

// Create a memory cache
cache := axios4go.NewMemoryCache(&axios4go.MemoryCacheOptions{
    MaxSize:         1000,              // Max entries (0 = unlimited)
    CleanupInterval: 5 * time.Minute,   // Cleanup expired entries
})
defer cache.Close()

// Create client with cache
client := axios4go.NewClientWithCache("https://api.example.com", &axios4go.CacheConfig{
    Cache:      cache,
    DefaultTTL: 5 * time.Minute,
})

// Enable caching for a request
resp, err := client.Request(&axios4go.RequestOptions{
    Method: "GET",
    URL:    "/users",
    Cache:  axios4go.CacheEnabled(10 * time.Minute),
})
Force Refresh
// Bypass cache and fetch fresh data
resp, err := client.Request(&axios4go.RequestOptions{
    Method: "GET",
    URL:    "/users",
    Cache: &axios4go.RequestCacheOptions{
        Enabled:      axios4go.Bool(true),
        TTL:          5 * time.Minute,
        ForceRefresh: true,
    },
})
Custom Cache Key
// Use custom key function to include headers in cache key
client := axios4go.NewClientWithCache("https://api.example.com", &axios4go.CacheConfig{
    Cache:      cache,
    DefaultTTL: 5 * time.Minute,
    KeyFunc: func(method, fullURL string, headers map[string]string) string {
        return method + ":" + fullURL + ":" + headers["Authorization"]
    },
})
Cache Statistics
stats := client.CacheStats()
fmt.Printf("Hits: %d, Misses: %d, Size: %d\n", stats.Hits, stats.Misses, stats.Size)

// Clear cache
client.ClearCache()
Custom Cache Implementation

Implement the Cache interface for custom storage (Redis, file, etc.):

type Cache interface {
    Get(key string) *CacheEntry
    Set(key string, entry *CacheEntry, ttl time.Duration)
    Delete(key string)
    Clear()
    Stats() CacheStats
}

Configuration Options

axios4go supports various configuration options through the RequestOptions struct:

  • Method: HTTP method (GET, POST, etc.)
  • URL: Request URL (relative to BaseURL if provided)
  • BaseURL: Base URL for the request (overrides client's BaseURL if set)
  • Params: URL query parameters (map[string]string)
  • Body: Request body (can be string, []byte, or any JSON serializable object)
  • Headers: Custom headers (map[string]string)
  • Timeout: Request timeout in milliseconds
  • Auth: Basic authentication credentials (&Auth{Username: "user", Password: "pass"})
  • ResponseType: Expected response type (default is "json")
  • ResponseEncoding: Expected response encoding (default is "utf8")
  • MaxRedirects: Maximum number of redirects to follow
  • MaxContentLength: Maximum allowed response content length
  • MaxBodyLength: Maximum allowed request body length
  • Decompress: Whether to decompress the response body (default is true)
  • ValidateStatus: Function to validate HTTP response status codes
  • InterceptorOptions: Request and response interceptors
  • Proxy: Proxy configuration
  • OnUploadProgress: Function to track upload progress
  • OnDownloadProgress: Function to track download progress
  • Cache: Per-request cache configuration (CacheEnabled(ttl) or &RequestCacheOptions{...})

Example:

options := &axios4go.RequestOptions{
    Method: "POST",
    URL:    "/submit",
    Headers: map[string]string{
        "Content-Type": "application/json",
    },
    Body: map[string]interface{}{
        "title":   "Sample",
        "content": "This is a sample post.",
    },
    Auth: &axios4go.Auth{
        Username: "user",
        Password: "pass",
    },
    Params: map[string]string{
        "verbose": "true",
    },
    Timeout:          5000, // 5 seconds
    MaxRedirects:     5,
    MaxContentLength: 1024 * 1024, // 1MB
    ValidateStatus: func(statusCode int) bool {
        return statusCode >= 200 && statusCode < 300
    },
}

resp, err := client.Request(options)

Contributing

Contributions to axios4go are welcome! Please follow these guidelines:

  • Fork the repository and create a new branch for your feature or bug fix.
  • Ensure your code follows Go conventions and passes all tests.
  • Write tests for new features or bug fixes.
  • Submit a Pull Request with a clear description of your changes.

License

This project is licensed under the Apache License, Version 2.0. See the LICENSE file for details

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool added in v0.6.7

func Bool(v bool) *bool

Bool is a helper function to create a pointer to a bool value

func DefaultCacheKeyFunc added in v0.6.7

func DefaultCacheKeyFunc(method, fullURL string, _ map[string]string) string

DefaultCacheKeyFunc generates a cache key from method and full URL

func SetBaseURL

func SetBaseURL(baseURL string)

Types

type Auth added in v0.4.0

type Auth struct {
	Username string
	Password string
}

type Cache added in v0.6.7

type Cache interface {
	// Get retrieves a cached response by key. Returns nil if not found or expired.
	Get(key string) *CacheEntry

	// Set stores a response in the cache with the given key and TTL.
	Set(key string, entry *CacheEntry, ttl time.Duration)

	// Delete removes an entry from the cache.
	Delete(key string)

	// Clear removes all entries from the cache.
	Clear()

	// Stats returns cache statistics.
	Stats() CacheStats
}

Cache defines the interface for cache implementations. Users can implement this interface for custom storage backends (Redis, file, etc.)

type CacheConfig added in v0.6.7

type CacheConfig struct {
	// Cache is the cache implementation to use
	Cache Cache

	// DefaultTTL is the default TTL for cached responses when per-request TTL is not specified
	// A value of 0 means no default TTL (must be specified per-request)
	DefaultTTL time.Duration

	// KeyFunc is a custom function to generate cache keys
	// If nil, the default key function (Method + URL) is used
	KeyFunc CacheKeyFunc

	// CacheableMethods defines which HTTP methods can be cached
	// If nil, defaults to []string{"GET"}
	CacheableMethods []string
}

CacheConfig holds the global cache configuration for a Client

type CacheEntry added in v0.6.7

type CacheEntry struct {
	Body       []byte
	StatusCode int
	Headers    http.Header
	CreatedAt  time.Time
	ExpiresAt  time.Time
}

CacheEntry represents a cached HTTP response

func (*CacheEntry) IsExpired added in v0.6.7

func (e *CacheEntry) IsExpired() bool

IsExpired checks if the cache entry has expired

type CacheKeyFunc added in v0.6.7

type CacheKeyFunc func(method, fullURL string, headers map[string]string) string

CacheKeyFunc is a function type for generating cache keys

type CacheStats added in v0.6.7

type CacheStats struct {
	Hits   int64
	Misses int64
	Size   int64
}

CacheStats provides cache statistics

type Client

type Client struct {
	BaseURL     string
	HTTPClient  *http.Client
	Logger      Logger
	CacheConfig *CacheConfig
}

func NewClient

func NewClient(baseURL string) *Client

func NewClientWithCache added in v0.6.7

func NewClientWithCache(baseURL string, cacheConfig *CacheConfig) *Client

NewClientWithCache creates a client with cache enabled

func (*Client) CacheStats added in v0.6.7

func (c *Client) CacheStats() *CacheStats

CacheStats returns the cache statistics

func (*Client) ClearCache added in v0.6.7

func (c *Client) ClearCache()

ClearCache clears all entries in the client's cache

func (*Client) Request

func (c *Client) Request(options *RequestOptions) (*Response, error)

func (*Client) SetCache added in v0.6.7

func (c *Client) SetCache(config *CacheConfig)

SetCache sets the cache configuration for the client

type DefaultLogger added in v0.6.0

type DefaultLogger struct {
	// contains filtered or unexported fields
}

func NewDefaultLogger added in v0.6.0

func NewDefaultLogger(options LogOptions) *DefaultLogger

func (*DefaultLogger) LogError added in v0.6.0

func (l *DefaultLogger) LogError(err error, level LogLevel)

func (*DefaultLogger) LogRequest added in v0.6.0

func (l *DefaultLogger) LogRequest(req *http.Request, level LogLevel)

func (*DefaultLogger) LogResponse added in v0.6.0

func (l *DefaultLogger) LogResponse(resp *http.Response, body []byte, duration time.Duration, level LogLevel)

func (*DefaultLogger) SetLevel added in v0.6.0

func (l *DefaultLogger) SetLevel(level LogLevel)

type InterceptorOptions added in v0.3.0

type InterceptorOptions struct {
	RequestInterceptors  RequestInterceptors
	ResponseInterceptors ResponseInterceptors
}

type LogLevel added in v0.6.0

type LogLevel int
const (
	LevelNone LogLevel = iota
	LevelError
	LevelInfo
	LevelDebug
)

type LogOptions added in v0.6.0

type LogOptions struct {
	Level          LogLevel
	MaxBodyLength  int
	MaskHeaders    []string
	Output         io.Writer
	TimeFormat     string
	IncludeBody    bool
	IncludeHeaders bool
}

type Logger added in v0.6.0

type Logger interface {
	LogRequest(*http.Request, LogLevel)
	LogResponse(*http.Response, []byte, time.Duration, LogLevel)
	LogError(error, LogLevel)
	SetLevel(LogLevel)
}

func NewLogger added in v0.6.0

func NewLogger(level LogLevel) Logger

type MemoryCache added in v0.6.7

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache is a thread-safe in-memory cache implementation

func NewMemoryCache added in v0.6.7

func NewMemoryCache(opts *MemoryCacheOptions) *MemoryCache

NewMemoryCache creates a new in-memory cache

func (*MemoryCache) Clear added in v0.6.7

func (c *MemoryCache) Clear()

Clear removes all entries from the cache

func (*MemoryCache) Close added in v0.6.7

func (c *MemoryCache) Close()

Close stops the background cleanup goroutine

func (*MemoryCache) Delete added in v0.6.7

func (c *MemoryCache) Delete(key string)

Delete removes an entry from the cache

func (*MemoryCache) Get added in v0.6.7

func (c *MemoryCache) Get(key string) *CacheEntry

Get retrieves a cached response by key

func (*MemoryCache) Set added in v0.6.7

func (c *MemoryCache) Set(key string, entry *CacheEntry, ttl time.Duration)

Set stores a response in the cache

func (*MemoryCache) Stats added in v0.6.7

func (c *MemoryCache) Stats() CacheStats

Stats returns cache statistics

type MemoryCacheOptions added in v0.6.7

type MemoryCacheOptions struct {
	// MaxSize is the maximum number of entries (0 = unlimited)
	MaxSize int

	// CleanupInterval is how often to clean expired entries (default: 5 minutes)
	CleanupInterval time.Duration
}

MemoryCacheOptions configures the MemoryCache

type ProgressReader added in v0.5.0

type ProgressReader struct {
	// contains filtered or unexported fields
}

func (*ProgressReader) Read added in v0.5.0

func (pr *ProgressReader) Read(p []byte) (int, error)

type ProgressWriter added in v0.5.0

type ProgressWriter struct {
	// contains filtered or unexported fields
}

func (*ProgressWriter) Write added in v0.5.0

func (pw *ProgressWriter) Write(p []byte) (int, error)

type Promise

type Promise struct {
	// contains filtered or unexported fields
}

func DeleteAsync

func DeleteAsync(urlStr string, options ...*RequestOptions) *Promise

func GetAsync

func GetAsync(urlStr string, options ...*RequestOptions) *Promise

func HeadAsync

func HeadAsync(urlStr string, options ...*RequestOptions) *Promise

func NewPromise

func NewPromise() *Promise

func OptionsAsync

func OptionsAsync(urlStr string, options ...*RequestOptions) *Promise

func PatchAsync

func PatchAsync(urlStr string, body interface{}, options ...*RequestOptions) *Promise

func PostAsync

func PostAsync(urlStr string, body interface{}, options ...*RequestOptions) *Promise

func PutAsync

func PutAsync(urlStr string, body interface{}, options ...*RequestOptions) *Promise

func RequestAsync

func RequestAsync(method, urlStr string, options ...*RequestOptions) *Promise

func (*Promise) Catch

func (p *Promise) Catch(fn func(error)) *Promise

func (*Promise) Finally

func (p *Promise) Finally(fn func())

func (*Promise) Then

func (p *Promise) Then(fn func(*Response)) *Promise

type Proxy added in v0.4.0

type Proxy struct {
	Protocol string
	Host     string
	Port     int
	Auth     *Auth
}

type RequestCacheOptions added in v0.6.7

type RequestCacheOptions struct {
	// Enabled explicitly enables/disables caching for this request
	// If nil, caching is disabled (opt-in model)
	Enabled *bool

	// TTL sets the TTL for this specific request
	// Overrides the global DefaultTTL if set
	TTL time.Duration

	// ForceRefresh bypasses the cache and fetches fresh data
	// The fresh response will still be cached
	ForceRefresh bool

	// CustomKey allows overriding the cache key for this request
	CustomKey string
}

RequestCacheOptions holds per-request cache configuration

func CacheDisabled added in v0.6.7

func CacheDisabled() *RequestCacheOptions

CacheDisabled returns a RequestCacheOptions with caching disabled

func CacheEnabled added in v0.6.7

func CacheEnabled(ttl time.Duration) *RequestCacheOptions

CacheEnabled returns a RequestCacheOptions with caching enabled

type RequestInterceptors added in v0.3.0

type RequestInterceptors []func(*http.Request) error

type RequestOptions added in v0.2.1

type RequestOptions struct {
	Method             string
	URL                string
	BaseURL            string
	Params             map[string]string
	Body               interface{}
	Headers            map[string]string
	Timeout            int
	Auth               *Auth
	ResponseType       string
	ResponseEncoding   string
	MaxRedirects       int
	MaxContentLength   int64
	MaxBodyLength      int64
	Decompress         bool
	ValidateStatus     func(int) bool
	InterceptorOptions InterceptorOptions
	Proxy              *Proxy
	OnUploadProgress   func(bytesRead, totalBytes int64)
	OnDownloadProgress func(bytesRead, totalBytes int64)
	LogLevel           LogLevel
	Cache              *RequestCacheOptions
}

type Response

type Response struct {
	StatusCode int
	Headers    http.Header
	Body       []byte
}

func Delete

func Delete(urlStr string, options ...*RequestOptions) (*Response, error)

func Get

func Get(urlStr string, options ...*RequestOptions) (*Response, error)
func Head(urlStr string, options ...*RequestOptions) (*Response, error)

func Options

func Options(urlStr string, options ...*RequestOptions) (*Response, error)

func Patch

func Patch(urlStr string, body interface{}, options ...*RequestOptions) (*Response, error)

func Post

func Post(urlStr string, body interface{}, options ...*RequestOptions) (*Response, error)

func Put

func Put(urlStr string, body interface{}, options ...*RequestOptions) (*Response, error)

func Request

func Request(method, urlStr string, options ...*RequestOptions) (*Response, error)

func (*Response) JSON

func (r *Response) JSON(v interface{}) error

type ResponseInterceptors added in v0.3.0

type ResponseInterceptors []func(*http.Response) error

Directories

Path Synopsis
examples
caching command
download command
interceptor command
promise_style command
request_style command
simple_style command

Jump to

Keyboard shortcuts

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