Lian is a high-performance, production-ready HTTP client library for Go, designed with best practices in mind, offering a clean and intuitive API while providing powerful features for modern microservices architectures.
- Fluent Chainable API: Clean and readable method chaining for request configuration
- Automatic Compression: Built-in support for gzip, brotli, zstd, and deflate decompression
- Request Compression: Optional zstd compression for request bodies with dictionary support and instance pooling
- Automatic Retry: Configurable automatic retry with exponential backoff and jitter for transient errors
- Structured Logging: Uses standard library
slogby default, supports custom logger implementations - OpenTelemetry Support: Built-in distributed tracing integration with configurable propagation formats (W3C, B3)
- Context-Aware: Full support for standard
context.Contextpropagation - Customizable Header Mapping: Flexible configuration for authentication and tenant headers
- Automatic Response Unmarshaling: Directly unmarshal JSON responses into structs
- Debugging Tools: Request/response dumping and HTTP trace capabilities
- Connection Pooling: Optimized HTTP client with configurable connection pooling
- No Framework Lock-In: Works with any Go web framework (Gin, Echo, Fiber, standard library, etc.)
go get github.com/cdyue/lianpackage main
import (
"context"
"fmt"
"github.com/cdyue/lian"
)
func main() {
// Simple GET request
resp := lian.Get("https://jsonplaceholder.typicode.com/posts/1")
if resp.IsError() {
panic(resp.Error())
}
// Parse JSON response
var post map[string]interface{}
if err := resp.JSON(&post); err != nil {
panic(err)
}
fmt.Printf("Post Title: %s\n", post["title"])
}user := map[string]interface{}{
"name": "John Doe",
"email": "john@example.com",
}
resp := lian.NewRequest().
SetJSONBody(user).
SetBearerToken("your-auth-token").
Post("https://api.example.com/users")
if resp.IsSuccess() {
fmt.Println("User created successfully!")
}import "time"
// Create a custom HTTP client with specific settings
client := lian.NewClient(
lian.WithTimeout(10 * time.Second),
lian.WithInsecure(), // Skip TLS certificate verification (use carefully!)
lian.WithMaxIdleConns(200),
)
// Use the custom client for requests
req := lian.NewRequest().SetClient(client)
resp := req.Get("https://api.example.com/data")Lian provides flexible configuration for core headers like authentication, tenant ID, etc.
// Customize header names globally
lian.SetDefaultAuthHeaderName("X-Access-Token")
lian.SetDefaultTenantIDHeaderName("X-Organization-ID")
lian.SetDefaultUserIDHeaderName("X-Current-User-ID")
// Custom value extractor functions (for integrating with your existing context)
lian.SetDefaultTenantIDExtractor(func(ctx context.Context) string {
// Example: Extract tenant ID from Gin context
if ginCtx, ok := ctx.Value("gin.Context").(*gin.Context); ok {
return ginCtx.GetString("tenant_id")
}
return ""
})// Customize headers for a specific request
customMapping := lian.HeaderMapping{
AuthHeader: "X-API-Key",
TenantIDHeader: "X-Company-ID",
// Leave other fields empty to disable extraction
}
req := lian.NewRequest().
SetHeaderMapping(customMapping).
FromContext(ctx).
Get("https://api.example.com/data")// In your middleware, store headers in context
ctx := context.Background()
ctx = lian.SetHeaderToContext(ctx, "Authorization", "Bearer token123")
ctx = lian.SetHeaderToContext(ctx, "X-Tenant-Id", "acme-corp")
// Later when making requests, headers are automatically extracted
resp := lian.NewRequest().
FromContext(ctx).
Get("https://api.example.com/protected")import (
"log/slog"
"os"
)
// Use a custom slog instance
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
lian.SetLogger(logger)
// Or implement the Logger interface for full customization
type CustomLogger struct {
// Your logger implementation
}
func (l *CustomLogger) Info(msg string, args ...interface{}) { /* ... */ }
func (l *CustomLogger) Debug(msg string, args ...interface{}) { /* ... */ }
func (l *CustomLogger) Warn(msg string, args ...interface{}) { /* ... */ }
func (l *CustomLogger) Error(msg string, args ...interface{}) { /* ... */ }
lian.SetLogger(&CustomLogger{})// Enable request/response dumping
req := lian.NewRequest().
EnableDumpRequest(). // Log full request details
EnableDumpResponse(). // Log full response details
EnableHTTPTrace(). // Log HTTP connection details (DNS, TCP, TLS, etc.)
Get("https://api.example.com/debug")Lian supports automatic retry for transient errors with configurable exponential backoff and jitter.
Important: By default, retry is only applied to idempotent methods (GET, HEAD, OPTIONS). Non-idempotent methods (POST, PATCH, PUT, DELETE) are NOT retried to avoid duplicate side effects. To enable retry for these methods, explicitly call
AllowNonIdempotentRetry()β pair it with anIdempotency-Keyheader when possible.
import "time"
// Enable retry for a specific request
resp := lian.NewRequest().
SetRetry(2). // 2 retries (3 total attempts)
SetRetryConfig(2, 50*time.Millisecond, 1.5, 0.1). // custom config
SetRetryableStatuses(429, 503). // custom status codes for this request
SetMaxRetryBackoff(10 * time.Second). // cap backoff at 10s
Get("https://api.example.com/data")
// Retry for POST (non-idempotent) β explicitly opt in
resp := lian.NewRequest().
SetRetry(2).
AllowNonIdempotentRetry().
SetHeader("Idempotency-Key", "unique-key-123").
SetJSONBody(payload).
Post("https://api.example.com/orders")- Retryable status codes: 429, 500, 502, 503, 504
- Base interval: 100ms
- Backoff factor: 2.0 (exponential)
- Jitter: 20%
- Max backoff: 30s
- Non-idempotent methods: NOT retried by default
Lian provides enhanced zstd support with instance pooling and pre-trained dictionary support for improved performance and compression ratios.
// Create client with custom zstd settings
client := lian.NewClient(
lian.WithZstdCompressionLevel(int(zstd.BestSpeed)), // compression level
lian.WithZstdDictionary(myPreTrainedDictionary), // use pre-trained dictionary
lian.WithZstdPooling(true), // enable encoder/decoder pooling (default true)
)// Enable zstd compression with custom level and dictionary
resp := lian.NewRequest().
EnableZstdCompressionWithLevel(int(zstd.BestCompression)).
SetZstdCompressionLevel(int(zstd.BestCompression)).
SetZstdDictionary(requestSpecificDict).
Post("https://api.example.com/upload").
SetJSONBody(largePayload)Lian has built-in OpenTelemetry distributed tracing support (enabled by default, no additional build tags required).
// Disable OpenTelemetry tracing globally for all requests
lian.DisableOtelTrace()
// Re-enable OpenTelemetry tracing globally
lian.EnableOtelTrace()// Disable tracing for a specific request
req := lian.NewRequest().
DisableOtelTrace().
Get("https://api.example.com/debug")
// Force enable tracing for a specific request even when globally disabled
req := lian.NewRequest().
EnableOtelTraceForRequest().
Get("https://api.example.com/debug")Lian automatically creates client spans, propagates trace headers, and records all HTTP events to your OpenTelemetry collector when tracing is enabled.
Lian supports configurable trace propagation formats, defaulting to W3C Trace Context with optional B3 support.
// Global configuration
lian.SetTracePropagationFormats(lian.TracePropagationW3C, lian.TracePropagationB3) // Enable both W3C and B3
// Or use convenience methods
lian.EnableB3TracePropagation() // Only use B3 single header format
lian.EnableCompositeTracePropagation() // Use both W3C and B3 (for migration scenarios)
// Per-request override (chainable)
resp := lian.Get("https://api.example.com/data").
SetTracePropagationFormats(lian.TracePropagationB3Multi). // Use B3 multi-header format for this request
Send()
// Configuration via functional options when creating Request
req := lian.NewRequest(
lian.WithB3TracePropagation(),
lian.WithTimeout(10*time.Second),
)Supported propagation formats:
TracePropagationW3C(default): W3C Trace Context format (traceparentandtracestateheaders)TracePropagationB3: B3 single header format (b3header)TracePropagationB3Multi: B3 multi-header format (X-B3-TraceId,X-B3-SpanId, etc.)
Note: To use B3 propagation formats, you need to install the optional dependency:
go get go.opentelemetry.io/contrib/propagators/b3@v1.42.0To use the stable standard library encoding/json, modify the imports in:
response.go: Changeencoding/json/v2toencoding/jsonbody.go: Changeencoding/json/v2toencoding/json
Then build normally:
go build ./...Build with the JSON v2 experiment enabled:
GOEXPERIMENT=jsonv2 go build ./...lian.Get(url string) *Responselian.Post(url string) *Responselian.Put(url string) *Responselian.Delete(url string) *Responselian.Patch(url string) *Responselian.Do(method, url string, body interface{}, headers map[string]string) *Response
WithTimeout(d time.Duration) OpFunc- Set overall request timeout (default: 62s)WithInsecure() OpFunc- Disable TLS certificate verificationWithDisableCompression() OpFunc- Disable response compression (transport level)WithDisableKeepAlive() OpFunc- Disable connection keep-aliveWithMaxIdleConns(n int) OpFunc- Set maximum number of idle connections (default: 200)WithIdleConnTimeout(d time.Duration) OpFunc- Set idle connection timeout (default: 55s)
Clone() *Request- Deep-copy the request (independent headers, body, etc.)SetHeader(key, value string) *RequestSetQueryParam(key, value string) *RequestSetJSONBody(v interface{}) *RequestSetFormBody(v interface{}) *RequestSetRawBody(body io.Reader, contentType string) *RequestSetBearerToken(token string) *RequestSetBasicAuth(username, password string) *RequestSetTimeout(timeout time.Duration) *Request- Set per-request timeoutSetRetry(maxRetries int) *Request- Enable retry for this requestSetRetryConfig(maxRetries int, interval time.Duration, backoffFactor float64, jitter float64) *Request- Set full retry configurationSetMaxRetryBackoff(d time.Duration) *Request- Cap exponential backoff (default 30s)SetRetryableStatuses(statuses ...int) *Request- Set custom retryable status codesAllowNonIdempotentRetry() *Request- Allow retry for POST/PATCH/PUT/DELETE (disabled by default)EnableZstdCompression() *Request- Enable zstd compression for request bodyEnableZstdCompressionWithLevel(level int) *Request- Enable zstd compression with custom levelSetZstdCompressionLevel(level int) *Request- Set zstd compression levelSetZstdDictionary(dict []byte) *Request- Set pre-trained zstd dictionary for this requestSetTracePropagationFormats(formats ...string) *Request- Set trace propagation formats for this requestEnableB3TracePropagation() *Request- Enable B3 single header propagation formatEnableCompositeTracePropagation() *Request- Enable both W3C and B3 propagation formatsDisableOtelTrace() *Request- Disable tracing for this requestEnableOtelTraceForRequest() *Request- Force enable tracing for this requestDisableTracePropagation() *Request- Disable trace header injectionDisableCompression() *Request- Disable response decompressionEnableDumpRequest() *Request- Log full request detailsEnableDumpResponse() *Request- Log full response detailsEnableHTTPTrace() *Request- Log HTTP connection details (DNS, TCP, TLS, etc.)SetResult(v any) *Request- Auto-unmarshal success response into vSetErrorResult(v any) *Request- Auto-unmarshal error response into vSetErrorStatusCodes(codes ...int) *Request- Custom status codes treated as errorDisableAutoUnmarshal() *Request- Skip auto-unmarshal, return raw bodyMarkAsAsync() *Request- Mark as async (span kind = Producer)EnableB3TracePropagation() *Request- Enable B3 single header propagation formatEnableCompositeTracePropagation() *Request- Enable both W3C and B3 propagation formats
resp.StatusCode() intresp.IsSuccess() boolresp.IsError() boolresp.Bytes() ([]byte, error)resp.String() (string, error)resp.JSON(v interface{}) errorresp.Save(w io.Writer) (int64, error)
MIT License