next

package
v0.0.0-...-446cb24 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2021 License: MIT Imports: 22 Imported by: 0

README

Next

该模块实现了与php-fpm进程通信的功能,将http请求转发给php-fpm进程处理。

// CreateHandler 创建服务处理器
func CreateHandler(params *Config, network, address string) http.Handler {
    fpmAddr := address
    if network == "unix" {
        fpmAddr = fmt.Sprintf("%s:%s", network, address)
    }

    rootDir := filepath.Dir(params.EndpointFile)

    conf := next.Config{
        EndpointFile:    params.EndpointFile,
        ServerIP:        params.ServiceIP,
        ServerPort:      params.ServicePort,
        SoftwareName:    "php-server",
        SoftwareVersion: "0.0.1",
        Rules:           []next.Rule{next.NewPHPRule(rootDir, []string{fpmAddr})},
        RequestLogHandler: func(rc *next.RequestContext) {
            var message bytes.Buffer
            if err := params.AccessLogTemplate.Execute(&message, rc); err != nil {
                log.Module("server").Errorf("invalid log format: %s", err.Error())
            } else {
                if params.Debug {
                    log.Module("server.request").
                        WithContext(rc.ToMap()).Debugf(message.String())
                } else {
                    log.Module("server.request").Debugf(message.String())
                }
            }
        },
    }

    return next.CreateHttpHandler(&conf)
}


http.HandleFunc("/", CreateHandler(config, network, address).ServeHTTP)
srv := &http.Server{Handler: http.DefaultServeMux}
go func() {
    if err := srv.Serve(listener); err != nil {
        log.Debugf("The http server has stopped: %v", err)
    }
}()

该模块大部分代码是从Caddy中提取出来的,参考 https://github.com/mholt/caddy/tree/master/caddyhttp/fastcgi

Documentation

Index

Constants

View Source
const (
	// BeginRequest is the begin request flag.
	BeginRequest uint8 = iota + 1
	// AbortRequest is the abort request flag.
	AbortRequest
	// EndRequest is the end request flag.
	EndRequest
	// Params is the parameters flag.
	Params
	// Stdin is the standard input flag.
	Stdin
	// Stdout is the standard output flag.
	Stdout
	// Stderr is the standard error flag.
	Stderr
	// Data is the data flag.
	Data
	// GetValues is the get values flag.
	GetValues
	// GetValuesResult is the get values result flag.
	GetValuesResult
	// UnknownType is the unknown type flag.
	UnknownType
	// MaxType is the maximum type flag.
	MaxType = UnknownType
)
View Source
const (
	// Responder is the responder flag.
	Responder uint8 = iota + 1
	// Authorizer is the authorizer flag.
	Authorizer
	// Filter is the filter flag.
	Filter
)
View Source
const (
	// RequestComplete is the completed request flag.
	RequestComplete uint8 = iota
	// CantMultiplexConns is the multiplexed connections flag.
	CantMultiplexConns
	// Overloaded is the overloaded flag.
	Overloaded
	// UnknownRole is the unknown role flag.
	UnknownRole
)
View Source
const (
	// MaxConns is the maximum connections flag.
	MaxConns string = "MAX_CONNS"
	// MaxRequests is the maximum requests flag.
	MaxRequests string = "MAX_REQS"
	// MultiplexConns is the multiplex connections flag.
	MultiplexConns string = "MPXS_CONNS"
)
View Source
const FCGIHeaderLen uint8 = 8

FCGIHeaderLen describes header length.

View Source
const FCGIKeepConn uint8 = 1

FCGIKeepConn describes keep connection mode.

View Source
const FCGIListenSockFileno uint8 = 0

FCGIListenSockFileno describes listen socket file number.

View Source
const FCGINullRequestID uint8 = 0

FCGINullRequestID describes the null request ID.

View Source
const Version1 uint8 = 1

Version1 describes the version.

Variables

View Source
var (

	// ErrIndexMissingSplit describes an index configuration error.
	ErrIndexMissingSplit = errors.New("configured index file(s) must include split value")
)

Functions

func CreateHTTPHandler

func CreateHTTPHandler(config *Config) http.Handler

CreateHTTPHandler create a http handler for request processing

func IndexFile

func IndexFile(root http.FileSystem, fpath string, indexFiles []string) (string, bool)

IndexFile looks for a file in /root/fpath/indexFile for each string in indexFiles. If an index file is found, it returns the root-relative path to the file and true. If no index file is found, empty string and false is returned. fpath must end in a forward slash '/' otherwise no index files will be tried (directory paths must end in a forward slash according to HTTP).

All paths passed into and returned from this function use '/' as the path separator, just like URLs. IndexFle handles path manipulation internally for systems that use different path separators.

Types

type Config

type Config struct {
	EndpointFile         string
	ServerIP             string
	ServerPort           int
	SoftwareName         string
	SoftwareVersion      string
	RequestLogHandler    RequestLogHandler
	ErrorResponseHandler ErrorResponseHandler
	Rules                []Rule
}

Config config object for create a handler

type ErrorResponseHandler

type ErrorResponseHandler func(w http.ResponseWriter, r *http.Request, code int, err error)

type FCGIClient

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

FCGIClient implements a FastCGI client, which is a standard for interfacing external applications with Web servers.

func Dial

func Dial(network, address string) (fcgi *FCGIClient, err error)

Dial connects to the fcgi responder at the specified network address, using default net.Dialer. See func net.Dial for a description of the network and address parameters.

func DialContext

func DialContext(ctx context.Context, network, address string) (fcgi *FCGIClient, err error)

DialContext is like Dial but passes ctx to dialer.Dial.

func DialWithDialerContext

func DialWithDialerContext(ctx context.Context, network, address string, dialer net.Dialer) (fcgi *FCGIClient, err error)

DialWithDialerContext connects to the fcgi responder at the specified network address, using custom net.Dialer and a context. See func net.Dial for a description of the network and address parameters.

func (*FCGIClient) Close

func (c *FCGIClient) Close()

Close closes fcgi connnection

func (*FCGIClient) Do

func (c *FCGIClient) Do(p map[string]string, req io.Reader) (r io.Reader, err error)

Do made the request and returns a io.Reader that translates the data read from fcgi responder out of fcgi packet before returning it.

func (*FCGIClient) Get

func (c *FCGIClient) Get(p map[string]string, body io.Reader, l int64) (resp *http.Response, err error)

Get issues a GET request to the fcgi responder.

func (*FCGIClient) Head

func (c *FCGIClient) Head(p map[string]string) (resp *http.Response, err error)

Head issues a HEAD request to the fcgi responder.

func (*FCGIClient) Options

func (c *FCGIClient) Options(p map[string]string) (resp *http.Response, err error)

Options issues an OPTIONS request to the fcgi responder.

func (*FCGIClient) Post

func (c *FCGIClient) Post(p map[string]string, method string, bodyType string, body io.Reader, l int64) (resp *http.Response, err error)

Post issues a POST request to the fcgi responder. with request body in the format that bodyType specified

func (*FCGIClient) PostFile

func (c *FCGIClient) PostFile(p map[string]string, data url.Values, file map[string]string) (resp *http.Response, err error)

PostFile issues a POST to the fcgi responder in multipart(RFC 2046) standard, with form as a string key to a list values (url.Values), and/or with file as a string key to a list file path.

func (*FCGIClient) PostForm

func (c *FCGIClient) PostForm(p map[string]string, data url.Values) (resp *http.Response, err error)

PostForm issues a POST to the fcgi responder, with form as a string key to a list values (url.Values)

func (*FCGIClient) Request

func (c *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Response, err error)

Request returns a HTTP Response with Header and Body from fcgi responder

func (*FCGIClient) SetReadTimeout

func (c *FCGIClient) SetReadTimeout(t time.Duration) error

SetReadTimeout sets the read timeout for future calls that read from the fcgi responder. A zero value for t means no timeout will be set.

func (*FCGIClient) SetSendTimeout

func (c *FCGIClient) SetSendTimeout(t time.Duration) error

SetSendTimeout sets the read timeout for future calls that send data to the fcgi responder. A zero value for t means no timeout will be set.

type HTTPHandler

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

HTTPHandler http request handler wrapper

func (*HTTPHandler) ServeHTTP

func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler interface

type Handler

type Handler struct {
	Rules   []Rule
	Root    string
	FileSys http.FileSystem

	// These are sent to CGI scripts in env variables
	SoftwareName    string
	SoftwareVersion string
	ServerName      string
	ServerPort      string
}

Handler is a middleware type that can handle requests as a FastCGI client.

func (Handler) ServeHTTP

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error)

ServeHTTP satisfies the httpserver.Handler interface.

type LogError

type LogError string

LogError is a non fatal error that allows requests to go through.

func (LogError) Error

func (l LogError) Error() string

Error satisfies error interface.

type RequestContext

type RequestContext struct {
	UA      string
	Method  string
	Referer string
	Headers http.Header
	URI     string
	Body    string
	Consume float64
	Code    int
	Error   string
}

RequestContext request context information

func (*RequestContext) ToMap

func (rc *RequestContext) ToMap() map[string]interface{}

ToMap convert the requestContext to a map

type RequestLogHandler

type RequestLogHandler func(rc *RequestContext)

RequestLogHandler request log handler func

type ResponseWriter

type ResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

ResponseWriter is a response wrapper

func NewResponseWriter

func NewResponseWriter(res http.ResponseWriter, writeCodeListener func(code int)) *ResponseWriter

NewResponseWriter create a new ResposneWriter wrapper

func (ResponseWriter) Header

func (w ResponseWriter) Header() http.Header

Header atisfy the http.ResponseWriter interface

func (ResponseWriter) Write

func (w ResponseWriter) Write(data []byte) (int, error)

Write send content to response

func (ResponseWriter) WriteHeader

func (w ResponseWriter) WriteHeader(statusCode int)

WriteHeader send a response code to client

type Rule

type Rule struct {
	// The base path to match. Required.
	Path string

	// Always process files with this extension with fastcgi.
	Ext string

	// Use this directory as the fastcgi root directory. Defaults to the root
	// directory of the parent virtual host.
	Root string

	// 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.
	SplitPath string

	// If the URL ends with '/' (which indicates a directory), these index
	// files will be tried instead.
	IndexFiles []string

	// Environment Variables
	EnvVars [][2]string

	// Ignored paths
	IgnoredSubPaths []string

	// The duration used to set a deadline when connecting to an upstream.
	ConnectTimeout time.Duration

	// The duration used to set a deadline when reading from the FastCGI server.
	ReadTimeout time.Duration

	// The duration used to set a deadline when sending to the FastCGI server.
	SendTimeout time.Duration
	// contains filtered or unexported fields
}

Rule represents a FastCGI handling rule. It is parsed from the fastcgi directive in the Caddyfile, see setup.go.

func NewPHPRule

func NewPHPRule(rootDir string, addresses []string) Rule

NewPHPRule create a rule for php

func (Rule) AllowedPath

func (r Rule) AllowedPath(requestPath string) bool

AllowedPath checks if requestPath is not an ignored path.

Jump to

Keyboard shortcuts

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