app

package
v0.0.0-...-7f880ae Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetHandlerName

func GetHandlerName(handler HandlerFunc) string

func ParseByteRange

func ParseByteRange(byteRange []byte, contentLength int) (startPos, endPos int, err error)

ParseByteRange parses 'Range: bytes=...' header value.

It follows https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 .

func ServeFile

func ServeFile(ctx *RequestContext, path string)

ServeFile returns HTTP response containing compressed file contents from the given path.

HTTP response may contain uncompressed file contents in the following cases:

  • Missing 'Accept-Encoding: gzip' request header.
  • No write access to directory containing the file.

Directory contents is returned if path points to directory.

Use ServeFileUncompressed is you don't need serving compressed file contents.

func ServeFileUncompressed

func ServeFileUncompressed(ctx *RequestContext, path string)

ServeFileUncompressed returns HTTP response containing file contents from the given path.

Directory contents is returned if path points to directory.

ServeFile may be used for saving network traffic when serving files with good compression ratio.

func SetConcurrentHandlerNameOperator

func SetConcurrentHandlerNameOperator()

func SetHandlerName

func SetHandlerName(handler HandlerFunc, name string)

func SetHandlerNameOperator

func SetHandlerNameOperator(o HandlerNameOperator)

Types

type ClientIP

type ClientIP func(ctx *RequestContext) string

func ClientIPWithOption

func ClientIPWithOption(opts ClientIPOptions) ClientIP

ClientIPWithOption used to generate custom ClientIP function and set by engine.SetClientIPFunc

type ClientIPOptions

type ClientIPOptions struct {
	RemoteIPHeaders []string
	TrustedCIDRs    []*net.IPNet
}

type Context

type Context = RequestCtx

type FS

type FS struct {

	// Path to the root directory to serve files from.
	Root string

	// List of index file names to try opening during directory access.
	//
	// For example:
	//
	//     * index.html
	//     * index.htm
	//     * my-super-index.xml
	//
	// By default the list is empty.
	IndexNames []string

	// Index pages for directories without files matching IndexNames
	// are automatically generated if set.
	//
	// Directory index generation may be quite slow for directories
	// with many files (more than 1K), so it is discouraged enabling
	// index pages' generation for such directories.
	//
	// By default index pages aren't generated.
	GenerateIndexPages bool

	// Transparently compresses responses if set to true.
	//
	// The server tries minimizing CPU usage by caching compressed files.
	// It adds CompressedFileSuffix suffix to the original file name and
	// tries saving the resulting compressed file under the new file name.
	// So it is advisable to give the server write access to Root
	// and to all inner folders in order to minimize CPU usage when serving
	// compressed responses.
	//
	// Transparent compression is disabled by default.
	Compress bool

	// Enables byte range requests if set to true.
	//
	// Byte range requests are disabled by default.
	AcceptByteRange bool

	// Path rewriting function.
	//
	// By default request path is not modified.
	PathRewrite PathRewriteFunc

	// PathNotFound fires when file is not found in filesystem
	// this functions tries to replace "Cannot open requested path"
	// server response giving to the programmer the control of server flow.
	//
	// By default PathNotFound returns
	// "Cannot open requested path"
	PathNotFound HandlerFunc

	// Expiration duration for inactive file handlers.
	//
	// FSHandlerCacheDuration is used by default.
	CacheDuration time.Duration

	// Suffix to add to the name of cached compressed file.
	//
	// This value has sense only if Compress is set.
	//
	// FSCompressedFileSuffix is used by default.
	CompressedFileSuffix string
	// contains filtered or unexported fields
}

FS represents settings for request handler serving static files from the local filesystem.

It is prohibited copying FS values. Create new values instead.

func (*FS) NewRequestHandler

func (fs *FS) NewRequestHandler() HandlerFunc

NewRequestHandler returns new request handler with the given FS settings.

The returned handler caches requested file handles for FS.CacheDuration. Make sure your program has enough 'max open files' limit aka 'ulimit -n' if FS.Root folder contains many files.

Do not create multiple request handlers from a single FS instance - just reuse a single request handler.

type HandlerFunc

type HandlerFunc func(c context.Context, ctx *RequestContext)

type HandlerNameOperator

type HandlerNameOperator interface {
	SetHandlerName(handler HandlerFunc, name string)
	GetHandlerName(handler HandlerFunc) string
}

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain defines a HandlerFunc array.

type PathRewriteFunc

type PathRewriteFunc func(ctx *RequestContext) []byte

PathRewriteFunc must return new request path based on arbitrary ctx info such as ctx.Path().

Path rewriter is used in FS for translating the current request to the local filesystem path relative to FS.Root.

The returned path must not contain '/../' substrings due to security reasons, since such paths may refer files outside FS.Root.

The returned path may refer to ctx members. For example, ctx.Path().

func NewPathSlashesStripper

func NewPathSlashesStripper(slashesCount int) PathRewriteFunc

NewPathSlashesStripper returns path rewriter, which strips slashesCount leading slashes from the path.

Examples:

  • slashesCount = 0, original path: "/foo/bar", result: "/foo/bar"
  • slashesCount = 1, original path: "/foo/bar", result: "/bar"
  • slashesCount = 2, original path: "/foo/bar", result: ""

The returned path rewriter may be used as FS.PathRewrite .

func NewVHostPathRewriter

func NewVHostPathRewriter(slashesCount int) PathRewriteFunc

NewVHostPathRewriter returns path rewriter, which strips slashesCount leading slashes from the path and prepends the path with request's host, thus simplifying virtual hosting for static files.

Examples:

  • host=foobar.com, slashesCount=0, original path="/foo/bar". Resulting path: "/foobar.com/foo/bar"

  • host=img.aaa.com, slashesCount=1, original path="/images/123/456.jpg" Resulting path: "/img.aaa.com/123/456.jpg"

type RequestContext

type RequestContext = RequestCtx

func (*RequestContext) ClientIP

func (ctx *RequestContext) ClientIP() string

ClientIP attempts to parse the headers in the order of [X-Forwarded-For, X-Real-IP]. It calls RemoteIP() under the hood. If it cannot satisfy the requirements, use engine.SetClientIPFunc to inject your own implementation.

func (*RequestContext) File

func (ctx *RequestContext) File(filepath string)

File writes the specified file into the body stream in an efficient way.

func (*RequestContext) Get

func (ctx *RequestContext) Get(key string) (value interface{}, exists bool)

Get returns the value for the given key, ie: (value, true). If the value does not exist it returns (nil, false)

func (*RequestContext) GetStatusCode

func (ctx *RequestContext) GetStatusCode() int

func (*RequestContext) IfModifiedSince

func (ctx *RequestContext) IfModifiedSince(lastModified time.Time) bool

IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since' value from the request header.

The function returns true also 'If-Modified-Since' request header is missing.

func (*RequestContext) JSON

func (ctx *RequestContext) JSON(code int, obj interface{})

JSON serializes the given struct as JSON into the response body.

It also sets the Content-Type as "application/json".

func (*RequestContext) NotModified

func (ctx *RequestContext) NotModified()

NotModified resets response and sets '304 Not Modified' response status code.

func (*RequestContext) Path

func (ctx *RequestContext) Path() []byte

Path returns requested path.

The path is valid until returning from RequestHandler.

func (*RequestContext) RemoteAddr

func (ctx *RequestContext) RemoteAddr() net.Addr

RemoteAddr returns client address for the given request.

If address is nil, it will return zeroTCPAddr.

func (*RequestContext) Render

func (ctx *RequestContext) Render(code int, r render.Render)

Render writes the response headers and calls render.Render to render data.

func (*RequestContext) Set

func (ctx *RequestContext) Set(key string, value interface{})

Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.

func (*RequestContext) SetBodyStream

func (ctx *RequestContext) SetBodyStream(bodyStream io.Reader, bodySize int)

SetBodyStream sets response body stream and, optionally body size.

bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.

If bodySize is >= 0, then bodySize bytes must be provided by bodyStream before returning io.EOF.

If bodySize < 0, then bodyStream is read until io.EOF.

See also SetBodyStreamWriter.

func (*RequestContext) SetBodyString

func (ctx *RequestContext) SetBodyString(body string)

SetBodyString sets response body to the given value.

func (*RequestContext) SetContentType

func (ctx *RequestContext) SetContentType(contentType string)

SetContentType sets response Content-Type.

func (*RequestContext) SetError

func (ctx *RequestContext) SetError(err e.ApiError)

func (*RequestContext) SetStatusCode

func (ctx *RequestContext) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*RequestContext) WriteString

func (ctx *RequestContext) WriteString(s string) (int, error)

WriteString appends s to response body.

type RequestCtx

type RequestCtx struct {
	context.Context

	// netpoll
	Response protocol.Response
	Request  protocol.Request

	Paths param.Params
	// contains filtered or unexported fields
}

func (*RequestCtx) Abort

func (ctx *RequestCtx) Abort()

func (*RequestCtx) AbortWithMsg

func (ctx *RequestCtx) AbortWithMsg(msg string, statusCode int)

func (*RequestCtx) ComputeAction

func (ctx *RequestCtx) ComputeAction()

func (*RequestCtx) GetAcceptEncoding

func (ctx *RequestCtx) GetAcceptEncoding() string

func (*RequestCtx) GetAction

func (ctx *RequestCtx) GetAction() string

func (*RequestCtx) GetBody

func (ctx *RequestCtx) GetBody() (body []byte)

func (*RequestCtx) GetConn

func (ctx *RequestCtx) GetConn() network.Conn

func (*RequestCtx) GetContentEncoding

func (ctx *RequestCtx) GetContentEncoding() string

func (*RequestCtx) GetContentLength

func (ctx *RequestCtx) GetContentLength() int64

func (*RequestCtx) GetContext

func (ctx *RequestCtx) GetContext() context.Context

func (*RequestCtx) GetData

func (ctx *RequestCtx) GetData() interface{}

func (*RequestCtx) GetError

func (ctx *RequestCtx) GetError() e.ApiError

func (*RequestCtx) GetHandlers

func (ctx *RequestCtx) GetHandlers() HandlersChain

func (*RequestCtx) GetMethod

func (ctx *RequestCtx) GetMethod() string

func (*RequestCtx) GetParams

func (ctx *RequestCtx) GetParams() map[string][]string

func (*RequestCtx) GetPath

func (ctx *RequestCtx) GetPath() string

func (*RequestCtx) GetReader

func (ctx *RequestCtx) GetReader() network.Reader

func (*RequestCtx) GetResponseWriterAndRequest

func (ctx *RequestCtx) GetResponseWriterAndRequest() (http.ResponseWriter, *http.Request)

func (*RequestCtx) GetRouteTemplate

func (ctx *RequestCtx) GetRouteTemplate() string

func (*RequestCtx) GetWriter

func (ctx *RequestCtx) GetWriter() network.Writer

func (*RequestCtx) HeaderGet

func (ctx *RequestCtx) HeaderGet(key string) string

func (*RequestCtx) Host

func (ctx *RequestCtx) Host() []byte

Host returns requested host.

The host is valid until returning from RequestHandler.

func (*RequestCtx) IsAbort

func (ctx *RequestCtx) IsAbort() bool

func (*RequestCtx) IsEnableTrace

func (ctx *RequestCtx) IsEnableTrace() bool

func (*RequestCtx) IsHead

func (ctx *RequestCtx) IsHead() bool

IsHead returns true if the request method is HEAD.

func (*RequestCtx) IsNetpoll

func (ctx *RequestCtx) IsNetpoll() bool

func (*RequestCtx) IsRestful

func (ctx *RequestCtx) IsRestful() bool

func (*RequestCtx) Method

func (ctx *RequestCtx) Method() []byte

func (*RequestCtx) Next

func (ctx *RequestCtx) Next(c context.Context)

Next increments the handler index and executes the next handler in the chain. After the next handler completes, control returns to the calling middleware. If Abort() was called or an error was set, Next() returns immediately without executing further handlers. This follows the Hertz/Gin recursive model: each handler must call Next() to proceed to the next one.

func (*RequestCtx) Reset

func (ctx *RequestCtx) Reset()

func (*RequestCtx) SetAction

func (ctx *RequestCtx) SetAction(action string)

func (*RequestCtx) SetConn

func (ctx *RequestCtx) SetConn(conn network.Conn) *RequestCtx

func (*RequestCtx) SetContext

func (ctx *RequestCtx) SetContext(c context.Context) *RequestCtx

func (*RequestCtx) SetData

func (ctx *RequestCtx) SetData(v interface{})

func (*RequestCtx) SetDisableHeaderNamesNormalizing

func (ctx *RequestCtx) SetDisableHeaderNamesNormalizing(disable bool)

func (*RequestCtx) SetEnableTrace

func (ctx *RequestCtx) SetEnableTrace(b bool)

func (*RequestCtx) SetHandlers

func (ctx *RequestCtx) SetHandlers(handlers HandlersChain)

func (*RequestCtx) SetHeader

func (ctx *RequestCtx) SetHeader(key, value string)

func (*RequestCtx) SetHttpWriterAndRequest

func (ctx *RequestCtx) SetHttpWriterAndRequest(w http.ResponseWriter, r *http.Request)

func (*RequestCtx) SetMethod

func (ctx *RequestCtx) SetMethod(method []byte)

func (*RequestCtx) SetNetWorkType

func (ctx *RequestCtx) SetNetWorkType(networkType string)

func (*RequestCtx) SetPath

func (ctx *RequestCtx) SetPath(path []byte)

func (*RequestCtx) SetRouteTemplate

func (ctx *RequestCtx) SetRouteTemplate(route string)

func (*RequestCtx) URI

func (ctx *RequestCtx) URI() *protocol.URI

func (*RequestCtx) UpgradeWebsocket

func (ctx *RequestCtx) UpgradeWebsocket()

func (*RequestCtx) Write

func (ctx *RequestCtx) Write(bytes []byte) (int, error)

Directories

Path Synopsis
net

Jump to

Keyboard shortcuts

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