frankenphp

package module
v1.13.1 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 41 Imported by: 35

README

FrankenPHP: modern app server for PHP

FrankenPHP

FrankenPHP is a modern application server for PHP built on top of the Caddy web server.

FrankenPHP gives superpowers to your PHP apps thanks to its stunning features: Early Hints, worker mode, real-time capabilities, hot reloading, automatic HTTPS, HTTP/2, and HTTP/3 support...

FrankenPHP works with any PHP app and makes your Laravel and Symfony projects faster than ever thanks to their official integrations with the worker mode.

FrankenPHP can also be used as a standalone Go library to embed PHP in any app using net/http.

Learn more on frankenphp.dev and in this slide deck:

Slides

Getting started

Install script

On Linux and macOS, copy this line into your terminal to automatically install an appropriate version for your platform:

curl https://frankenphp.dev/install.sh | sh

On Windows, run this in PowerShell:

irm https://frankenphp.dev/install.ps1 | iex
Standalone binary

We provide FrankenPHP binaries for Linux, macOS and Windows containing PHP 8.5.

Linux binaries are statically linked, so they can be used on any Linux distribution without installing any dependency. macOS binaries are also self-contained. They contain most popular PHP extensions. Windows archives contain the official PHP binary for Windows.

Download FrankenPHP

rpm packages

Our maintainers offer rpm packages for all systems using dnf. To install, run:

sudo dnf install https://rpm.henderkes.com/static-php-1-0.noarch.rpm
sudo dnf module enable php-zts:static-8.5 # 8.2-8.5 available
sudo dnf install frankenphp

Installing extensions: sudo dnf install php-zts-<extension>

For extensions not available by default, use PIE:

sudo dnf install pie-zts
sudo pie-zts install asgrim/example-pie-extension
deb packages

Our maintainers offer deb packages for all systems using apt. To install, run:

VERSION=85 # 82-85 available
sudo curl https://pkg.henderkes.com/api/packages/${VERSION}/debian/repository.key -o /etc/apt/keyrings/static-php${VERSION}.asc
echo "deb [signed-by=/etc/apt/keyrings/static-php${VERSION}.asc] https://pkg.henderkes.com/api/packages/${VERSION}/debian php-zts main" | sudo tee -a /etc/apt/sources.list.d/static-php${VERSION}.list
sudo apt update
sudo apt install frankenphp

Installing extensions: sudo apt install php-zts-<extension>

For extensions not available by default, use PIE:

sudo apt install pie-zts
sudo pie-zts install asgrim/example-pie-extension
apk packages

Our maintainers offer apk packages for all systems using apk. To install, run:

VERSION=85 # 82-85 available
echo "https://pkg.henderkes.com/api/packages/${VERSION}/alpine/main/php-zts" | sudo tee -a /etc/apk/repositories
KEYFILE=$(curl -sJOw '%{filename_effective}' https://pkg.henderkes.com/api/packages/${VERSION}/alpine/key)
sudo mv ${KEYFILE} /etc/apk/keys/ &&
sudo apk update &&
sudo apk add frankenphp

Installing extensions: sudo apk add php-zts-<extension>

For extensions not available by default, use PIE:

sudo apk add pie-zts
sudo pie-zts install asgrim/example-pie-extension
Homebrew

FrankenPHP is also available as a Homebrew package for macOS and Linux.

brew install dunglas/frankenphp/frankenphp

Installing extensions: Use PIE.

Usage

To serve the content of the current directory, run:

frankenphp php-server

You can also run command-line scripts with:

frankenphp php-cli /path/to/your/script.php

For the deb and rpm packages, you can also start the systemd service:

sudo systemctl start frankenphp
Docker

Alternatively, Docker images are available:

docker run -v .:/app/public \
    -p 80:80 -p 443:443 -p 443:443/udp \
    dunglas/frankenphp

Go to https://localhost, and enjoy!

[!TIP]

Do not attempt to use https://127.0.0.1. Use https://localhost and accept the self-signed certificate. Use the SERVER_NAME environment variable to change the domain to use.

Docs

Examples and skeletons

Documentation

Overview

Package frankenphp embeds PHP in Go projects and provides a SAPI for net/http.

This is the core of the FrankenPHP app server, and can be used in any Go program.

Index

Examples

Constants

View Source
const (
	StopReasonCrash = iota
	StopReasonRestart
	StopReasonBootFailure // worker crashed before reaching frankenphp_handle_request
)

Variables

View Source
var (
	ErrInvalidRequest     = errors.New("not a FrankenPHP request")
	ErrAlreadyStarted     = errors.New("FrankenPHP is already started")
	ErrInvalidPHPVersion  = errors.New("FrankenPHP is only compatible with PHP 8.2+")
	ErrZendSignals        = errors.New(`FrankenPHP is not compatible with Zend Signals, recompile PHP with the "--disable-zend-signals" configuration option`)
	ErrMainThreadCreation = errors.New("error creating the main thread")
	ErrScriptExecution    = errors.New("error during PHP script execution")
	ErrNotRunning         = errors.New("server is not registered, you must first call frankenphp.Init() with the WithServer() option")

	ErrInvalidRequestPath         = ErrRejected{"invalid request path", http.StatusBadRequest}
	ErrInvalidContentLengthHeader = ErrRejected{"invalid Content-Length header", http.StatusBadRequest}
	ErrMaxWaitTimeExceeded        = ErrRejected{"maximum request handling time exceeded", http.StatusServiceUnavailable}
)
View Source
var EmbeddedAppPath string

EmbeddedAppPath contains the path of the embedded PHP application (empty if none). It can be set at build time using -ldflags to override the default extraction path:

go build -ldflags "-X github.com/dunglas/frankenphp.EmbeddedAppPath=/app" ...

When set, the embedded app is extracted to this fixed path instead of a temp directory with a checksum suffix. This is useful when the app contains pre-compiled artifacts (e.g. OPcache file cache) that reference absolute paths and need a predictable extraction location.

View Source
var (
	ErrInvalidSplitPath = errors.New("split path contains non-ASCII characters")
)
View Source
var (
	ErrMaxThreadsReached = errors.New("max amount of overall threads reached")
)

Functions

func AddPHPInfoEntry added in v1.13.0

func AddPHPInfoEntry(key, value string)

AddPHPInfoEntry adds an entry to the frankenphp section of phpinfo().

func CallPHPCallable added in v1.11.0

func CallPHPCallable(cb unsafe.Pointer, params []any) any

EXPERIMENTAL: CallPHPCallable executes a PHP callable with the given parameters. Returns the result of the callable as a Go any, or nil if the call failed.

func ExecuteScriptCLI

func ExecuteScriptCLI(script string, args []string) int

ExecuteScriptCLI executes the PHP script passed as parameter. It returns the exit status code of the script.

Example
package main

import (
	"log"
	"os"

	"github.com/dunglas/frankenphp"
)

func main() {
	if len(os.Args) <= 1 {
		log.Println("Usage: my-program script.php")
		os.Exit(1)
	}

	os.Exit(frankenphp.ExecuteScriptCLI(os.Args[0], os.Args))
}

func GoMap added in v1.9.1

func GoMap[T any](arr unsafe.Pointer) (map[string]T, error)

EXPERIMENTAL: GoMap converts a zend_array to an unordered Go map

func GoPackedArray added in v1.9.1

func GoPackedArray[T any](arr unsafe.Pointer) ([]T, error)

EXPERIMENTAL: GoPackedArray converts a zend_array to a Go slice

func GoString added in v1.8.0

func GoString(s unsafe.Pointer) string

EXPERIMENTAL: GoString copies a zend_string to a Go string.

func GoValue added in v1.10.0

func GoValue[T any](zval unsafe.Pointer) (T, error)

EXPERIMENTAL: GoValue converts a PHP zval to a Go value

Zval having the null, bool, long, double, string and array types are currently supported. Arrays can currently only be converted to any[] and AssociativeArray[any]. Any other type will cause an error. More types may be supported in the future.

func Init

func Init(options ...Option) error

Init starts the PHP runtime and the configured workers.

func IsPacked added in v1.11.0

func IsPacked(arr unsafe.Pointer) bool

IsPacked determines if the given zend_array is a packed array (list). Returns false if the array is nil or not packed.

func NewRequestWithContext

func NewRequestWithContext(r *http.Request, opts ...RequestOption) (*http.Request, error)

NewRequestWithContext creates a new FrankenPHP request context.

FrankenPHP does not strip request headers whose name contains an underscore or a dot. Because CGI maps dashes to underscores ("Foo-Bar" becomes the HTTP_FOO_BAR variable) and PHP maps dots to underscores when registering variables ("Foo.Bar" also becomes HTTP_FOO_BAR), a client-supplied "Foo_Bar" or "Foo.Bar" header is indistinguishable from the legitimate "Foo-Bar" in $_SERVER and can spoof it. This affects any such header an application or upstream proxy trusts (forwarded-for, auth, etc.). Drop headers containing an underscore or a dot before calling this function, unless you explicitly need (and whitelist) them. The Caddy-based server and reverse proxies such as nginx (underscores_in_headers off) already do this.

func PHPAssociativeArray added in v1.9.1

func PHPAssociativeArray[T any](arr AssociativeArray[T]) unsafe.Pointer

EXPERIMENTAL: PHPAssociativeArray converts a Go AssociativeArray to a zend_array

func PHPMap added in v1.9.1

func PHPMap[T any](arr map[string]T) unsafe.Pointer

EXPERIMENTAL: PHPMap converts an unordered Go map to a zend_array

func PHPPackedArray added in v1.9.1

func PHPPackedArray[T any](slice []T) unsafe.Pointer

EXPERIMENTAL: PHPPackedArray converts a Go slice to a PHP zval with a zend_array value.

func PHPString added in v1.8.0

func PHPString(s string, persistent bool) unsafe.Pointer

EXPERIMENTAL: PHPString converts a Go string to a zend_string with copy. The string can be non-persistent (automatically freed after the request by the ZMM) or persistent. If you choose the second mode, it is your repsonsability to free the allocated memory.

func PHPValue added in v1.10.0

func PHPValue(value any) unsafe.Pointer

EXPERIMENTAL: PHPValue converts a Go any to a PHP zval

nil, bool, int, int64, float64, string, []any, and map[string]any are currently supported. Any other type will cause a panic. More types may be supported in the future.

func RegisterExtension added in v1.8.0

func RegisterExtension(me unsafe.Pointer)

RegisterExtension registers a new PHP extension.

func RestartWorkers added in v1.5.0

func RestartWorkers()

RestartWorkers attempts to restart all workers gracefully. All workers must be restarted at the same time to prevent issues with opcache resetting. Blocks until every worker thread has yielded; force-kill is armed after a grace period to wake threads parked in blocking syscalls so a stuck sleep doesn't make this hang for the full duration of the syscall.

func ServeHTTP

func ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) error

ServeHTTP executes a PHP script according to the given context.

Example
package main

import (
	"log"
	"net/http"
	"strings"

	"github.com/dunglas/frankenphp"
)

func main() {
	if err := frankenphp.Init(); err != nil {
		panic(err)
	}
	defer frankenphp.Shutdown()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Drop headers whose name contains an underscore or a dot: CGI maps
		// dashes to underscores and PHP maps dots to underscores, so "Foo_Bar"
		// and "Foo.Bar" would both be indistinguishable from "Foo-Bar" in
		// $_SERVER and could spoof any header an app or proxy trusts.
		// Whitelist any you genuinely need.
		for name := range r.Header {
			if strings.ContainsAny(name, "_.") {
				delete(r.Header, name)
			}
		}

		req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot("/path/to/document/root", false))
		if err != nil {
			panic(err)
		}

		if err := frankenphp.ServeHTTP(w, req); err != nil {
			panic(err)
		}
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}
Example (Workers)
package main

import (
	"log"
	"net/http"

	"github.com/dunglas/frankenphp"
)

func main() {
	if err := frankenphp.Init(
		frankenphp.WithWorkers("worker1", "worker1.php", 4,
			frankenphp.WithWorkerEnv(map[string]string{"ENV1": "foo"}),
			frankenphp.WithWorkerWatchMode([]string{}),
			frankenphp.WithWorkerMaxFailures(0),
		),
		frankenphp.WithWorkers("worker2", "worker2.php", 2,
			frankenphp.WithWorkerEnv(map[string]string{"ENV2": "bar"}),
			frankenphp.WithWorkerWatchMode([]string{}),
			frankenphp.WithWorkerMaxFailures(0),
		),
	); err != nil {
		panic(err)
	}
	defer frankenphp.Shutdown()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		req, err := frankenphp.NewRequestWithContext(r, frankenphp.WithRequestDocumentRoot("/path/to/document/root", false))
		if err != nil {
			panic(err)
		}

		if err := frankenphp.ServeHTTP(w, req); err != nil {
			panic(err)
		}
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func Shutdown

func Shutdown()

Shutdown stops the workers and the PHP runtime.

func Validate added in v1.13.0

func Validate(options ...Option) error

Validate reports whether Init() would accept a configuration, without starting anything: the thread budget, the worker files, and the names and scopes workers may take. A host replacing a running configuration should call it before stopping the one in place, since Init() only reports these errors once the previous runtime is gone.

func WithExtensionWorkers added in v1.10.0

func WithExtensionWorkers(name, fileName string, numThreads int, options ...WorkerOption) (Workers, Option)

EXPERIMENTAL: WithExtensionWorkers allow extensions to create workers.

A worker script with the provided name, fileName and thread count will be registered, along with additional configuration through WorkerOptions.

Workers are designed to run indefinitely and will be gracefully shut down when FrankenPHP shuts down.

Extension workers count as worker threads: they come on top of num_threads, and Init() returns an error when max_threads has no room for them. Don't be greedy.

Types

type AssociativeArray added in v1.9.1

type AssociativeArray[T any] struct {
	Map   map[string]T
	Order []string
}

AssociativeArray represents a PHP array with ordered key-value pairs

func GoAssociativeArray added in v1.9.1

func GoAssociativeArray[T any](arr unsafe.Pointer) (AssociativeArray[T], error)

EXPERIMENTAL: GoAssociativeArray converts a zend_array to a Go AssociativeArray

type ErrRejected added in v1.10.0

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

func (ErrRejected) Error added in v1.10.0

func (e ErrRejected) Error() string

type FrankenPHPDebugState added in v1.5.0

type FrankenPHPDebugState struct {
	ThreadDebugStates   []ThreadDebugState
	ReservedThreadCount int
}

EXPERIMENTAL: FrankenPHPDebugState prints the state of all PHP threads - debugging purposes only

func DebugState added in v1.5.0

func DebugState() FrankenPHPDebugState

EXPERIMENTAL: DebugState prints the state of all PHP threads - debugging purposes only

type Metrics added in v1.3.0

type Metrics interface {
	// StartWorker collects started workers
	StartWorker(name string)
	// ReadyWorker collects ready workers
	ReadyWorker(name string)
	// StopWorker collects stopped workers
	StopWorker(name string, reason StopReason)
	// TotalWorkers collects expected workers
	TotalWorkers(name string, num int)
	// TotalThreads collects total threads
	TotalThreads(num int)
	// StartRequest collects started requests
	StartRequest()
	// StopRequest collects stopped requests
	StopRequest()
	// StopWorkerRequest collects stopped worker requests
	StopWorkerRequest(name string, duration time.Duration)
	// StartWorkerRequest collects started worker requests
	StartWorkerRequest(name string)
	Shutdown()
	QueuedWorkerRequest(name string)
	DequeuedWorkerRequest(name string)
	QueuedRequest()
	DequeuedRequest()
}

Metrics reports what the workers and the threads of a FrankenPHP instance are doing. An implementation that also satisfies OpcacheMetrics is told about opcache restarts as well.

type OpcacheMetrics added in v1.13.0

type OpcacheMetrics interface {
	OpcacheRestart(reason string)
}

OpcacheMetrics is the optional part of a Metrics implementation that counts the restarts of opcache's shared memory, by reason, where the build reports them (ZTS, PHP 8.4 and up). An implementation passed to WithMetrics() that lacks it only misses the counter, the restart is logged either way.

type Option

type Option func(h *opt) error

Option instances allow to configure FrankenPHP.

func WithContext added in v1.10.0

func WithContext(ctx context.Context) Option

WithContext sets the main context to use.

func WithHotReload added in v1.11.0

func WithHotReload(topic string, hub *mercure.Hub, patterns []string) Option

WithHotReload sets files to watch for file changes to trigger a hot reload update.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger configures the global logger to use.

func WithMaxIdleTime added in v1.12.0

func WithMaxIdleTime(maxIdleTime time.Duration) Option

WithMaxIdleTime configures the max time an autoscaled thread may be idle before being deactivated.

func WithMaxRequests added in v1.12.3

func WithMaxRequests(maxRequests int) Option

EXPERIMENTAL: WithMaxRequests sets the default max requests before restarting a PHP thread (0 = unlimited). Applies to regular and worker threads.

func WithMaxThreads added in v1.5.0

func WithMaxThreads(maxThreads int) Option

WithMaxThreads limits how many threads may run at once, workers included. A negative value derives that limit from the memory available.

func WithMaxWaitTime added in v1.5.0

func WithMaxWaitTime(maxWaitTime time.Duration) Option

WithMaxWaitTime configures the max time a request may be stalled waiting for a thread.

func WithMetrics added in v1.3.0

func WithMetrics(m Metrics) Option

func WithNumThreads

func WithNumThreads(numThreads int) Option

WithNumThreads configures the number of PHP threads to start for the requests no worker serves. Worker threads come on top of it.

func WithPhpIni added in v1.5.0

func WithPhpIni(overrides map[string]string) Option

WithPhpIni configures user defined PHP ini settings.

func WithServer added in v1.13.0

func WithServer(s *Server) Option

WithServer starts FrankenPHP with the given Server instance. After registering, it will be possible to call Server.ServeHTTP()

func WithWorkers

func WithWorkers(name, fileName string, num int, options ...WorkerOption) Option

WithWorkers configures the PHP workers to start

type PHPConfig

type PHPConfig struct {
	Version                PHPVersion
	ZTS                    bool
	ZendSignals            bool
	ZendMaxExecutionTimers bool
}

func Config

func Config() PHPConfig

type PHPThread added in v1.13.0

type PHPThread struct {
	Request *http.Request
	// contains filtered or unexported fields
}

EXPERIMENTAL: PHPThread exposes a PHP thread's request context.

func Thread added in v1.13.0

func Thread(index uint) (*PHPThread, bool)

EXPERIMENTAL: Thread retrieves a PHP thread by its index. Returns nil and false if the system is not running or no thread exists at the given index.

func (*PHPThread) IsRequestDone added in v1.13.0

func (p *PHPThread) IsRequestDone() bool

EXPERIMENTAL: IsRequestDone determines whether the request associated with the PHPThread has been closed.

func (*PHPThread) Pin added in v1.13.0

func (p *PHPThread) Pin(pointer any)

EXPERIMENTAL: Pin pins a Go object, preventing it from being moved or freed by the garbage collector until the Pinner.Unpin method has been called.

type PHPVersion

type PHPVersion struct {
	MajorVersion   int
	MinorVersion   int
	ReleaseVersion int
	ExtraVersion   string
	Version        string
	VersionID      int
}

func Version

func Version() PHPVersion

Version returns infos about the PHP version.

type PreparedEnv added in v1.1.1

type PreparedEnv = map[string]string

func PrepareEnv added in v1.1.1

func PrepareEnv(env map[string]string) PreparedEnv

type PrometheusMetrics added in v1.3.0

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

func NewPrometheusMetrics added in v1.3.0

func NewPrometheusMetrics(registry prometheus.Registerer) *PrometheusMetrics

func (*PrometheusMetrics) DequeuedRequest added in v1.5.0

func (m *PrometheusMetrics) DequeuedRequest()

func (*PrometheusMetrics) DequeuedWorkerRequest added in v1.5.0

func (m *PrometheusMetrics) DequeuedWorkerRequest(name string)

func (*PrometheusMetrics) OpcacheRestart added in v1.13.0

func (m *PrometheusMetrics) OpcacheRestart(reason string)

func (*PrometheusMetrics) QueuedRequest added in v1.5.0

func (m *PrometheusMetrics) QueuedRequest()

func (*PrometheusMetrics) QueuedWorkerRequest added in v1.5.0

func (m *PrometheusMetrics) QueuedWorkerRequest(name string)

func (*PrometheusMetrics) ReadyWorker added in v1.3.0

func (m *PrometheusMetrics) ReadyWorker(name string)

func (*PrometheusMetrics) Shutdown added in v1.3.0

func (m *PrometheusMetrics) Shutdown()

func (*PrometheusMetrics) StartRequest added in v1.3.0

func (m *PrometheusMetrics) StartRequest()

func (*PrometheusMetrics) StartWorker added in v1.3.0

func (m *PrometheusMetrics) StartWorker(name string)

func (*PrometheusMetrics) StartWorkerRequest added in v1.3.0

func (m *PrometheusMetrics) StartWorkerRequest(name string)

func (*PrometheusMetrics) StopRequest added in v1.3.0

func (m *PrometheusMetrics) StopRequest()

func (*PrometheusMetrics) StopWorker added in v1.3.0

func (m *PrometheusMetrics) StopWorker(name string, reason StopReason)

func (*PrometheusMetrics) StopWorkerRequest added in v1.3.0

func (m *PrometheusMetrics) StopWorkerRequest(name string, duration time.Duration)

func (*PrometheusMetrics) TotalThreads added in v1.3.0

func (m *PrometheusMetrics) TotalThreads(num int)

func (*PrometheusMetrics) TotalWorkers added in v1.3.0

func (m *PrometheusMetrics) TotalWorkers(string, int)

type RequestOption

type RequestOption func(h *frankenPHPContext) error

RequestOption instances allow to configure a FrankenPHP Request.

func WithMercureHub added in v1.10.0

func WithMercureHub(hub *mercure.Hub) RequestOption

WithMercureHub sets the mercure.Hub to use to publish updates

func WithOriginalRequest added in v1.4.0

func WithOriginalRequest(r *http.Request) RequestOption

func WithRequestBodyTimeout added in v1.12.5

func WithRequestBodyTimeout(timeout time.Duration) RequestOption

WithRequestBodyTimeout sets an idle timeout on request body reads: a stalled (slow POST) client is cut off while a steady upload of any size succeeds. Zero (the default) disables it. Requires a ResponseWriter that exposes a read deadline (net/http and Caddy do); otherwise the read has no timeout.

func WithRequestDocumentRoot

func WithRequestDocumentRoot(documentRoot string, resolveSymlink bool) RequestOption

WithRequestDocumentRoot sets the root directory of the PHP application. if resolveSymlink is true, oath declared as root directory will be resolved to its absolute value after the evaluation of any symbolic links. Due to the nature of PHP opcache, root directory path is cached: when using a symlinked directory as root this could generate errors when symlink is changed without PHP being restarted; enabling this directive will set $_SERVER['DOCUMENT_ROOT'] to the real directory path.

func WithRequestEnv

func WithRequestEnv(env map[string]string) RequestOption

WithRequestEnv set CGI-like environment variables that will be available in $_SERVER. Values set with WithEnv always have priority over automatically populated values.

func WithRequestLogger

func WithRequestLogger(logger *slog.Logger) RequestOption

WithRequestLogger sets the logger associated with the current request

func WithRequestPreparedEnv added in v1.1.1

func WithRequestPreparedEnv(env PreparedEnv) RequestOption

func WithRequestResolvedDocumentRoot added in v1.2.5

func WithRequestResolvedDocumentRoot(documentRoot string) RequestOption

WithRequestResolvedDocumentRoot is similar to WithRequestDocumentRoot but doesn't do any checks or resolving on the path to improve performance.

func WithRequestSplitPath

func WithRequestSplitPath(splitPath []string) (RequestOption, error)

WithRequestSplitPath contains a list of split path strings.

The path in the URL will be split into two, with the first piece ending with the value of splitPath. The first piece will be assumed as the actual resource (CGI script) name, and the second piece will be set to PATH_INFO for the CGI script to use.

Split paths can only contain ASCII characters. Comparison is case-insensitive.

Future enhancements should be careful to avoid CVE-2019-11043, which can be mitigated with use of a try_files-like behavior that 404s if the FastCGI path info is not found.

func WithWorkerName added in v1.6.0

func WithWorkerName(name string) RequestOption

WithWorkerName sets the worker that should handle the request

type Server added in v1.13.0

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

Server represents a preconfigured server block requests and workers can be scoped to a Server

func NewServer added in v1.13.0

func NewServer(root string, options ...ServerOption) (*Server, error)

NewServer creates a Server that can be registered via WithServer(). name is a human-readable identifier used to attribute workers, metrics and logs to this server; when empty, it defaults to the index the server gets at registration time.

func (*Server) Name added in v1.13.0

func (s *Server) Name() string

Name returns the human-readable name of the server. It is empty until registration if none was passed to NewServer().

func (*Server) ServeHTTP added in v1.13.0

func (s *Server) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request, opts ...RequestOption) error

ServeHTTP executes a PHP script on the registered server. The request will be scoped to the server instance that was registered via WithServer(). Otherwise, it is equivalent to calling ServeHTTP.

type ServerOption added in v1.13.0

type ServerOption func(*Server) error

ServerOption instances allow configuring a server.

func WithServerEnv added in v1.13.0

func WithServerEnv(env map[string]string) ServerOption

WithServerEnv sets the env for the server.

func WithServerLogger added in v1.13.0

func WithServerLogger(l *slog.Logger) ServerOption

WithServerLogger sets the logger for the server.

func WithServerName added in v1.13.0

func WithServerName(name string) ServerOption

WithServerName sets the name of the server.

func WithServerSplitPath added in v1.13.0

func WithServerSplitPath(splitPath []string) ServerOption

WIthServerSplitPath sets the split path for the server.

type StopReason added in v1.3.0

type StopReason int

type ThreadDebugState added in v1.5.0

type ThreadDebugState struct {
	Index                    int
	Name                     string
	State                    string
	IsWaiting                bool
	IsBusy                   bool
	WaitingSinceMilliseconds int64
	CurrentURI               string
	CurrentMethod            string
	RequestStartedAt         int64
	RequestCount             int64
	MemoryUsage              int64
}

EXPERIMENTAL: ThreadDebugState prints the state of a single PHP thread - debugging purposes only

type WorkerOption added in v1.8.0

type WorkerOption func(*workerOpt) error

WorkerOption instances allow configuring FrankenPHP worker.

func WithWorkerEnv added in v1.8.0

func WithWorkerEnv(env map[string]string) WorkerOption

WithWorkerEnv sets environment variables for the worker

func WithWorkerMatcher added in v1.13.0

func WithWorkerMatcher(matcherFunc func(*http.Request) bool) WorkerOption

WithWorkerMatcher sets a request matcher for this worker if the matcher returns true, the worker will be used to handle the request if no request matcher is set, matching happens only by path (filename == root + request path)

func WithWorkerMaxFailures added in v1.8.0

func WithWorkerMaxFailures(maxFailures int) WorkerOption

WithWorkerMaxFailures sets the maximum number of consecutive failures before panicking

func WithWorkerMaxThreads added in v1.10.0

func WithWorkerMaxThreads(num int) WorkerOption

WithWorkerMaxThreads sets the max number of threads for this specific worker

func WithWorkerMercureHub added in v1.11.0

func WithWorkerMercureHub(hub *mercure.Hub) WorkerOption

WithWorkerMercureHub sets the mercure.Hub in the worker script and used to dispatch hot reloading-related mercure.Update.

func WithWorkerOnReady added in v1.10.0

func WithWorkerOnReady(f func(int)) WorkerOption

func WithWorkerOnServerShutdown added in v1.10.0

func WithWorkerOnServerShutdown(f func()) WorkerOption

WithWorkerOnServerShutdown adds a function to be called right before server shutdown. Useful for extensions.

func WithWorkerOnServerStartup added in v1.10.0

func WithWorkerOnServerStartup(f func()) WorkerOption

WithWorkerOnServerStartup adds a function to be called right after server startup. Useful for extensions.

func WithWorkerOnShutdown added in v1.10.0

func WithWorkerOnShutdown(f func(int)) WorkerOption

func WithWorkerRequestOptions added in v1.10.1

func WithWorkerRequestOptions(options ...RequestOption) WorkerOption

WithWorkerRequestOptions sets options for the main dummy request created for the worker

func WithWorkerServerScope added in v1.13.0

func WithWorkerServerScope(s *Server) WorkerOption

WithWorkerServerScope scopes the worker to a server instance. Only requests that are handled by the server instance will reach the worker.

func WithWorkerWatchMode added in v1.8.0

func WithWorkerWatchMode(watch []string) WorkerOption

WithWorkerWatchMode sets directories to watch for file changes

type Workers added in v1.10.0

type Workers interface {
	// SendRequest calls the closure passed to frankenphp_handle_request() and updates the PHP context .
	// The generated HTTP response will be written through the provided writer.
	SendRequest(rw http.ResponseWriter, r *http.Request) error
	// SendMessage calls the closure passed to frankenphp_handle_request(), passes message as a parameter, and returns the value produced by the closure.
	SendMessage(ctx context.Context, message any, rw http.ResponseWriter) (any, error)
	// NumThreads returns the number of available threads.
	NumThreads() int
}

EXPERIMENTAL: Workers allows you to register a worker.

Directories

Path Synopsis
caddy module
internal
cpu
extgen
header.go
header.go
testcli command
testserver command

Jump to

Keyboard shortcuts

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