fcgx

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2025 License: MIT Imports: 16 Imported by: 0

README

fcgx

A minimal, robust, and modern FastCGI client library for Go.

fcgx is designed for integrating with PHP-FPM and other FastCGI servers, aiming for idiomatic Go, high testability, and correct protocol handling. It supports context, deadlines, timeouts, and structured error handling.

Part of the PHPeek project - Tools for PHP monitoring and observability in Go.

Features

  • Idiomatic, thread-safe Go API
  • Context and timeout support on all requests
  • Structured sentinel errors for robust error handling (errors.Is)
  • Manual and reliable FastCGI protocol handling
  • Designed for integration with PHP-FPM status, pool metrics, and more
  • Well-suited for Kubernetes, Docker, and production monitoring

Quick Example

import (
    "context"
    "github.com/gophpeek/fcgx"
    "io"
    "time"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()

    client, err := fcgx.DialContext(ctx, "unix", "/var/run/php-fpm.sock")
    if err != nil {
        panic(err)
    }
    defer client.Close()

    params := map[string]string{
        "SCRIPT_FILENAME": "/usr/share/phpmyadmin/index.php",
        "SCRIPT_NAME":     "/index.php",
        "REQUEST_METHOD":  "GET",
        "SERVER_PROTOCOL": "HTTP/1.1",
        "REMOTE_ADDR":     "127.0.0.1",
    }

    resp, err := client.Get(ctx, params)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    println(string(body))
}

Error Handling

fcgx returns strong sentinel errors for key error categories:

  • ErrClientClosed
  • ErrTimeout
  • ErrContextCancelled
  • ErrUnexpectedEOF
  • ErrInvalidResponse
  • ErrWrite, ErrRead

Use errors.Is to match error causes in your code.

Authors

License

MIT

Documentation

Overview

Package fcgx provides a minimal, robust, and modern FastCGI client library for Go.

This package is designed for integrating with PHP-FPM and other FastCGI servers, aiming for idiomatic Go code, high testability, and correct protocol handling. It supports context, deadlines, timeouts, and structured error handling.

Example usage:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

client, err := fcgx.DialContext(ctx, "unix", "/var/run/php-fpm.sock")
if err != nil {
	panic(err)
}
defer client.Close()

params := map[string]string{
	"SCRIPT_FILENAME": "/usr/share/phpmyadmin/index.php",
	"SCRIPT_NAME":     "/index.php",
	"REQUEST_METHOD":  "GET",
	"SERVER_PROTOCOL": "HTTP/1.1",
	"REMOTE_ADDR":     "127.0.0.1",
}

resp, err := client.Get(ctx, params)
if err != nil {
	panic(err)
}
defer resp.Body.Close()

body, err := fcgx.ReadBody(resp)
if err != nil {
	panic(err)
}
fmt.Println(string(body))

Index

Constants

View Source
const (
	// FastCGI protocol constants
	FCGI_HEADER_LEN = 8 // FastCGI record header length in bytes

)

Variables

View Source
var (
	ErrClientClosed     = errors.New("fcgx: client closed")
	ErrTimeout          = errors.New("fcgx: timeout")
	ErrContextCancelled = errors.New("fcgx: context cancelled")
	ErrUnexpectedEOF    = errors.New("fcgx: unexpected EOF")
	ErrInvalidResponse  = errors.New("fcgx: invalid response")
	ErrPHPFPM           = errors.New("fcgx: php-fpm error")
	ErrConnect          = errors.New("fcgx: connect error")
	ErrWrite            = errors.New("fcgx: write error")
	ErrRead             = errors.New("fcgx: read error")
)

Functions

func ReadBody

func ReadBody(resp *http.Response) ([]byte, error)

ReadBody reads and returns the actual response body as a []byte. It also strips any HTTP headers if present (as in FastCGI/PHP-FPM responses). It closes the response body after reading.

func ReadJSON

func ReadJSON(resp *http.Response, out any) error

ReadJSON reads and unmarshals the actual response body as JSON into out. It also strips any HTTP headers if present (as in FastCGI/PHP-FPM responses). It closes the response body after reading.

Types

type Client

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

Client represents a FastCGI client connection. It maintains state for communicating with a FastCGI server (typically PHP-FPM). All methods are thread-safe and can be called concurrently.

func Dial

func Dial(network, address string) (*Client, error)

Dial establishes a connection to the FastCGI server at the specified network address using default configuration options.

func DialContext

func DialContext(ctx context.Context, network, address string) (*Client, error)

DialContext establishes a connection to the FastCGI server at the specified network address with the given context using default configuration.

func DialContextWithConfig

func DialContextWithConfig(ctx context.Context, network, address string, config *Config) (*Client, error)

DialContextWithConfig establishes a connection to the FastCGI server with context and custom configuration.

func DialWithConfig

func DialWithConfig(network, address string, config *Config) (*Client, error)

DialWithConfig establishes a connection to the FastCGI server with custom configuration.

func (*Client) Close

func (c *Client) Close() error

Close closes the FastCGI connection.

func (*Client) DoRequest

func (c *Client) DoRequest(ctx context.Context, params map[string]string, body io.Reader) (*http.Response, error)

func (*Client) Get

func (c *Client) Get(ctx context.Context, params map[string]string) (*http.Response, error)

func (*Client) Post

func (c *Client) Post(ctx context.Context, params map[string]string, body io.Reader, contentLength int) (*http.Response, error)

type Config

type Config struct {
	// MaxWriteSize controls the maximum size of data chunks sent to the FastCGI server.
	// Default: 65500 bytes (slightly under 64KB for protocol safety)
	MaxWriteSize int

	// ConnectTimeout sets the timeout for establishing initial connections.
	// Default: 5 seconds
	ConnectTimeout time.Duration

	// RequestTimeout sets a default timeout for requests when context has no deadline.
	// Default: 30 seconds
	RequestTimeout time.Duration
}

Config holds configuration options for FastCGI client behavior. Zero values provide sensible defaults for most use cases.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sensible defaults for most use cases

Jump to

Keyboard shortcuts

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