fox

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: MIT Imports: 26 Imported by: 1

Documentation

Overview

Package fox provides a lightweight web framework for building web applications.

Index

Constants

View Source
const (
	// DebugMode indicates gin mode is debug.
	DebugMode = gin.DebugMode
	// ReleaseMode indicates gin mode is release.
	ReleaseMode = gin.ReleaseMode
	// TestMode indicates gin mode is test.
	TestMode = gin.TestMode
)
View Source
const RouteManifestVersion = "fox.route-manifest/v1"

RouteManifestVersion is the current JSON route manifest format version.

Variables

View Source
var DefaultBinder binding.Binding = binding.JSON

DefaultBinder default binder

View Source
var DefaultErrorWriter io.Writer = os.Stderr

DefaultErrorWriter is the default io.Writer used by Gin to debug errors.

View Source
var DefaultWriter io.Writer = os.Stdout

DefaultWriter is the default io.Writer used by Gin for debug output and middleware output like Logger() or Recovery(). Note that both Logger and Recovery provides custom ways to configure their output io.Writer. To support coloring in Windows use:

import "github.com/mattn/go-colorable"
gin.DefaultWriter = colorable.NewColorableStdout()
View Source
var ErrBindContextTypeMismatch = errors.New("context value type mismatch")

ErrBindContextTypeMismatch is returned when a value retrieved from the request context via a `context:"key"` tag cannot be converted to the destination field type.

View Source
var ErrBindNonPointerValue = errors.New("can not bind to non-pointer value")

ErrBindNonPointerValue is required bind pointer

View Source
var ErrInvalidHandlerType = MsgInvalidHandlerType

Deprecated: Use MsgInvalidHandlerType. This alias will be removed in v0.2.0.

View Source
var LoggerContextKey = "_fox-goinc/fox/logger/context/key"

LoggerContextKey logger save in gin context

View Source
var MsgInvalidHandlerType = "invalid handler type: %s\n" +
	"handler signature: %s\n" +
	"Supported handler types:\n" +
	"1. func()\n" +
	"2. func(ctx *Context) T\n" +
	"3. func(ctx *Context) (T, error)\n" +
	"4. func(ctx *Context, args S) T\n" +
	"5. func(ctx *Context, args S) (T, error)\n" +
	"Where:\n" +
	"- S can be struct or map type, S will be auto binding from request body\n" +
	"- T can be any type, T will be auto render to response body\n" +
	"- error can be any type that implements error interface"

MsgInvalidHandlerType is the panic message format for invalid handler types.

View Source
var Query = &queryBinding{}

Query binder

View Source
var Recovery = gin.Recovery
View Source
var Validate = validator.New()

Validate is the global validator instance used by Fox's DefaultValidator. Register custom validations on this instance before request handling begins, for example in init() or main().

Functions

func IsDebugging

func IsDebugging() bool

IsDebugging returns true if the framework is running in debug mode. Use SetMode(gin.ReleaseMode) to disable debug mode.

func IsValidHandlerFunc added in v0.0.3

func IsValidHandlerFunc(handler HandlerFunc) bool

IsValidHandlerFunc checks if the handler matches the HandlerFunc type requirements.

func Logger

func Logger(config ...LoggerConfig) gin.HandlerFunc

Logger middleware

func Mode

func Mode() string

Mode returns current fox mode.

func NewXResponseTimer

func NewXResponseTimer(key ...string) gin.HandlerFunc

NewXResponseTimer x-response-time middleware

func SetMode

func SetMode(value string)

SetMode sets gin mode according to input string.

func WriteRouteManifest added in v0.1.1

func WriteRouteManifest(engine *Engine, path string) error

WriteRouteManifest writes the Engine route registry as indented JSON.

Types

type Context

type Context struct {
	*gin.Context

	Logger logger.Logger
	// Request is the http request copy from gin.Context.
	Request *http.Request
	// contains filtered or unexported fields
}

Context with engine

func (*Context) Copy added in v0.0.7

func (c *Context) Copy() *Context

func (*Context) Deadline added in v0.0.6

func (c *Context) Deadline() (deadline time.Time, ok bool)

func (*Context) Done added in v0.0.6

func (c *Context) Done() <-chan struct{}

func (*Context) Err added in v0.0.6

func (c *Context) Err() error

func (*Context) Next added in v0.0.6

func (c *Context) Next()

func (*Context) RequestBody

func (c *Context) RequestBody() (body []byte, err error)

RequestBody return request body bytes see c.ShouldBindBodyWith

func (*Context) TraceID

func (c *Context) TraceID() string

TraceID returns the request trace ID. It checks the gin context, request header, and response header in order, falling back to generating a new ID which is then written to both the response header and gin context.

Note: This method has a side effect when no trace ID exists. If you only want to read without generating, check c.GetHeader(logger.TraceID) directly.

func (*Context) Value added in v0.0.6

func (c *Context) Value(key any) any

type DefaultValidator

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

DefaultValidator is the default implementation of Validator.

func (*DefaultValidator) Engine

func (v *DefaultValidator) Engine() any

Engine return validate

func (*DefaultValidator) ValidateStruct

func (v *DefaultValidator) ValidateStruct(obj any) error

ValidateStruct check struct

type DomainEngine

type DomainEngine struct {
	*Engine

	GetEngine func() *Engine
	// contains filtered or unexported fields
}

DomainEngine subdomain engine

func NewDefaultDomainEngine

func NewDefaultDomainEngine() *DomainEngine

NewDefaultDomainEngine new default domain engine

func NewDomainEngine

func NewDomainEngine(get ...func() *Engine) *DomainEngine

NewDomainEngine new domain engine

func (*DomainEngine) Domain

func (engine *DomainEngine) Domain(name string, engineFunc func(subEngine *Engine))

Domain registers an exact-match domain handler.

Domains are matched in registration order. The first match wins, regardless of whether it is exact or regexp. Register regexp patterns after exact domains to avoid accidental shadowing.

func (*DomainEngine) DomainRegexp

func (engine *DomainEngine) DomainRegexp(name string, engineFunc func(subEngine *Engine))

DomainRegexp registers a regexp domain handler.

Domains are matched in registration order. The first match wins, regardless of whether it is exact or regexp. Register regexp patterns after exact domains to avoid accidental shadowing.

func (*DomainEngine) ServeHTTP

func (engine *DomainEngine) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP conforms to the http.Handler interface.

type Engine

type Engine struct {
	*gin.Engine

	RouterGroup

	// DefaultRenderErrorStatusCode is the default http status code used for automatic rendering
	DefaultRenderErrorStatusCode int

	RenderErrorFunc RenderErrorFunc
	// contains filtered or unexported fields
}

Engine for server.

func Default

func Default() *Engine

Default return an Engine instance with Logger and Recovery middleware already attached.

func New

func New() *Engine

New return engine instance.

func (*Engine) CORS

func (engine *Engine) CORS(config cors.Config)

CORS config.

func (*Engine) DisableRouteRegistry added in v0.0.11

func (engine *Engine) DisableRouteRegistry()

DisableRouteRegistry stops collecting handler reflection metadata for new routes. Existing entries are dropped. Use when you do not run any tooling (such as openapi generation) and want to free the per-route memory.

func (*Engine) HandlerRoutes added in v0.0.11

func (engine *Engine) HandlerRoutes() []RouteInfo

HandlerRoutes returns a stable snapshot of routes registered through fox.

func (*Engine) Load

func (engine *Engine) Load(f RouterConfigFunc, fs ...embed.FS)

Load router config.

func (*Engine) NoMethod added in v0.0.3

func (engine *Engine) NoMethod(handlers ...HandlerFunc)

func (*Engine) NoRoute added in v0.0.3

func (engine *Engine) NoRoute(handlers ...HandlerFunc)

func (*Engine) NotFound

func (engine *Engine) NotFound(handlers ...HandlerFunc)

NotFound adds handlers for NoRoute. It returns a 404 code by default.

func (*Engine) Use

func (engine *Engine) Use(middleware ...HandlerFunc)

Use middleware.

type HandlerFunc

type HandlerFunc any

HandlerFunc is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but support auto binding and auto render.

Support handler types:

  1. func(){}
  2. func(ctx *Context) T { ... }
  3. func(ctx *Context) (T, error) { ... }
  4. func(ctx *Context, args S) T { ... }
  5. func(ctx *Context, args S) (T, error) { ... }

Where:

  • S can be struct or map type, S will be auto binding from request body
  • T can be any type, T will be auto render to response body
  • error can be any type that implements error interface

IMPORTANT: When a handler with a non-nil return value is used as middleware through Use, the chain is aborted after the value is rendered. For middleware that should pass through, use a signature without return values or use gin.HandlerFunc directly.

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain defines a HandlerFunc slice.

func (HandlersChain) Last

func (c HandlersChain) Last() HandlerFunc

Last returns the last handler in the chain. i.e. the last handler is the main one.

type IsValider

type IsValider interface {
	IsValid() error
}

IsValider interface

type LoggerConfig

type LoggerConfig struct {
	// SkipPaths is an url path array which logs are not written.
	// Optional.
	SkipPaths []string
}

LoggerConfig defines the config for Logger middleware.

type RenderErrorFunc added in v0.0.3

type RenderErrorFunc func(ctx *Context, err error)

type RouteInfo added in v0.0.11

type RouteInfo struct {
	Method      string
	Path        string
	Handler     HandlerFunc
	HandlerType reflect.Type
	HandlerName string
}

RouteInfo preserves the original fox handler metadata for registered routes. Gin only exposes the wrapped handler, so fox records the business handler at route registration time for external tooling such as documentation generators.

type RouteManifest added in v0.1.1

type RouteManifest struct {
	Version string               `json:"version"`
	Routes  []RouteManifestRoute `json:"routes"`
}

RouteManifest is a stable JSON representation of routes registered on an Engine. Tooling can consume it without booting the application itself.

func RouteManifestFromEngine added in v0.1.1

func RouteManifestFromEngine(engine *Engine) RouteManifest

RouteManifestFromEngine returns a serializable snapshot of the Engine route registry.

type RouteManifestField added in v0.1.1

type RouteManifestField struct {
	Name      string            `json:"name"`
	Tag       string            `json:"tag,omitempty"`
	Anonymous bool              `json:"anonymous,omitempty"`
	Type      RouteManifestType `json:"type"`
}

RouteManifestField is a serializable subset of reflect.StructField.

type RouteManifestRoute added in v0.1.1

type RouteManifestRoute struct {
	Method      string              `json:"method"`
	Path        string              `json:"path"`
	Handler     string              `json:"handler,omitempty"`
	InputTypes  []RouteManifestType `json:"inputTypes,omitempty"`
	ResultTypes []RouteManifestType `json:"resultTypes,omitempty"`
}

RouteManifestRoute describes one Fox route and the original business handler captured at registration time.

type RouteManifestType added in v0.1.1

type RouteManifestType struct {
	Kind    string               `json:"kind"`
	Name    string               `json:"name,omitempty"`
	PkgPath string               `json:"pkgPath,omitempty"`
	Key     *RouteManifestType   `json:"key,omitempty"`
	Elem    *RouteManifestType   `json:"elem,omitempty"`
	Fields  []RouteManifestField `json:"fields,omitempty"`
}

RouteManifestType is a serializable subset of reflect.Type.

type RouterConfigFunc

type RouterConfigFunc func(router *Engine, embedFS ...embed.FS)

RouterConfigFunc engine load router config func.

type RouterGroup

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

RouterGroup is gin.RouterGroup wrapper.

func (*RouterGroup) Any

func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc)

Any registers a route that matches all the HTTP methods. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.

func (*RouterGroup) DELETE

func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) gin.IRoutes

DELETE is a shortcut for router.Handle("DELETE", path, handle).

func (*RouterGroup) GET

func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) gin.IRoutes

GET is a shortcut for router.Handle("GET", path, handle).

func (*RouterGroup) Group

func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup

Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middleware for authorization could be grouped.

func (*RouterGroup) HEAD

func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) gin.IRoutes

HEAD is a shortcut for router.Handle("HEAD", path, handle).

func (*RouterGroup) Handle

func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) gin.IRoutes

Handle gin.Handle wrapper.

func (*RouterGroup) OPTIONS

func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) gin.IRoutes

OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).

func (*RouterGroup) PATCH

func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) gin.IRoutes

PATCH is a shortcut for router.Handle("PATCH", path, handle).

func (*RouterGroup) POST

func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) gin.IRoutes

POST is a shortcut for router.Handle("POST", path, handle).

func (*RouterGroup) PUT

func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) gin.IRoutes

PUT is a shortcut for router.Handle("PUT", path, handle).

func (*RouterGroup) Use

func (group *RouterGroup) Use(middleware ...HandlerFunc) gin.IRoutes

Use adds middleware to the group, see example code in GitHub.

type StatusCoder

type StatusCoder interface {
	StatusCode() int
}

StatusCoder is a interface for http status code

type XResponseTimer

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

XResponseTimer wrap gin response writer add start time

func (*XResponseTimer) Write

func (w *XResponseTimer) Write(b []byte) (int, error)

Write implement http.ResponseWriter

func (*XResponseTimer) WriteHeader

func (w *XResponseTimer) WriteHeader(statusCode int)

WriteHeader implement http.ResponseWriter

Directories

Path Synopsis
examples
01-basic command
02-binding command
03-middleware command
Package logger provides a customizable logging system for the application.
Package logger provides a customizable logging system for the application.

Jump to

Keyboard shortcuts

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