zinc

package module
v0.0.63 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2025 License: MIT Imports: 27 Imported by: 0

README

zinc

Zinc Version Go Version License

Zinc is a high-performance, minimal API framework for Go that focuses on speed, simplicity, and developer velocity. Designed to compete with the most popular frameworks around today in performance and usability.

Features

  • Fast: Optimized routing and minimal middleware overhead
  • Simple API: Intuitive and expressive API that follows Go idioms
  • Powerful Router: Support for static routes, path parameters, route groups, and middleware
  • Template Engine: Built-in HTML templating with custom functions and template caching
  • WebSocket Support: Real-time communication with room-based broadcasting
  • File Uploads: Easy file upload handling with size limits and type validation
  • Cron Scheduler: Built-in cron jobs for scheduled tasks
  • Memory Efficient: Utilizes sync.Pool and fixed-size data structures to minimize allocations
  • Well-Tested: Comprehensive test suite ensures reliability

Installation

go get github.com/0mjs/zinc

Quick Start

package main

import (
    "github.com/0mjs/zinc"
    "log"
)

func main() {
    app := zinc.New()
    
    // Simple route
    app.Get("/", func(c *zinc.Context) {
        c.Send("Hello, World!")
    })
    
    // Path parameters
    app.Get("/users/:id", func(c *zinc.Context) {
        c.JSON(zinc.Map{
            "message": "User ID: " + c.Param("id"),
        })
    })
    
    // Route grouping
    api := app.Group("/api")
    api.Get("/users", func(c *zinc.Context) {
        c.JSON(zinc.Map{
            "users": []string{"matthew", "mark", "luke", "john"},
        })
    })
    
    // Middleware
    app.Use(LoggerMiddleware())
    
    log.Fatal(app.Serve())
}

func LoggerMiddleware() zinc.Middleware {
    return func(c *zinc.Context) {
        // Log before request handling
        c.Next() // Pass control to the next middleware or handler
        // Log after request handling
    }
}

Documentation

For complete documentation, visit:

Benchmarks

Zinc is designed for high performance, with benchmarks showing it to be competitive with or faster than other popular Go frameworks:

  • Static routes: ~800ns/op
  • Dynamic routes: ~1.2μs/op
  • Middleware chain: ~2.0μs/op

Typed Service Dependency Injection

Zinc provides a powerful type-safe service dependency injection system that allows you to register and retrieve services by their concrete types.

Registering Services

You can register services using either the string-based approach or the new type-based approach:

// String-based service registration (legacy)
app.Service("userService", userService)

// Type-based service registration (recommended)
app.Register(userService)
Retrieving Services

There are several ways to retrieve services:

  1. String-based retrieval (legacy):
userService := c.Service("userService").(*UserService)
  1. Type-based retrieval using generics:
// From App instance
userService, ok := zinc.ServiceOf[*UserService](app)
if !ok {
    // Handle service not found
}

// From Context
userService, ok := zinc.ContextServiceOf[*UserService](c)
if !ok {
    // Handle service not found
}

The type-based approach provides several advantages:

  • Compile-time type safety
  • No need for type assertions
  • No string literals that could contain typos
  • Better IDE support with code completion
Examples
Basic Usage
// Register a service
app.Register(userService)

// Use the service in a handler
app.Get("/users", func(c *zinc.Context) error {
    service, ok := zinc.ContextServiceOf[*UserService](c)
    if !ok {
        return c.Status(zinc.StatusInternalServerError).String("Service not available")
    }
    return service.GetUsers(c)
})
Using Services in Middleware

Services can be accessed directly from middleware functions:

// Middleware that uses typed services
authMiddleware := func(c *zinc.Context) error {
    // Access the auth service directly from context
    authService, ok := zinc.ContextServiceOf[*AuthService](c)
    if !ok {
        return c.Status(zinc.StatusInternalServerError).String("Auth service not available")
    }
    
    // Use the service
    token := c.Request.Header.Get("Authorization")
    if err := authService.ValidateToken(token); err != nil {
        return c.Status(zinc.StatusUnauthorized).String("Invalid token")
    }
    
    // Continue with the next handler
    return c.Next()
}

// Apply the middleware to routes or groups
app.Get("/protected", authMiddleware, func(c *zinc.Context) error {
    return c.String("Protected resource")
})

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	ParamIdentifier    = ':'
	WildcardIdentifier = '*'
)
View Source
const (
	HeaderAuthorization                   = "Authorization"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderAge                             = "Age"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderExpires                         = "Expires"
	HeaderPragma                          = "Pragma"
	HeaderWarning                         = "Warning"
	HeaderAcceptCH                        = "Accept-CH"
	HeaderAcceptCHLifetime                = "Accept-CH-Lifetime"
	HeaderContentDPR                      = "Content-DPR"
	HeaderDPR                             = "DPR"
	HeaderEarlyData                       = "Early-Data"
	HeaderSaveData                        = "Save-Data"
	HeaderViewportWidth                   = "Viewport-Width"
	HeaderWidth                           = "Width"
	HeaderETag                            = "ETag"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderLastModified                    = "Last-Modified"
	HeaderVary                            = "Vary"
	HeaderConnection                      = "Connection"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderAccept                          = "Accept"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderCookie                          = "Cookie"
	HeaderExpect                          = "Expect"
	HeaderMaxForwards                     = "Max-Forwards"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderOrigin                          = "Origin"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies   = "X-Permitted-Cross-Domain-Policies"
	HeaderDNT                             = "DNT"
	HeaderTk                              = "Tk"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentType                     = "Content-Type"
	HeaderForwarded                       = "Forwarded"
	HeaderVia                             = "Via"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedHost                  = "X-Forwarded-Host"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXForwardedProtocol              = "X-Forwarded-Protocol"
	HeaderXForwardedSsl                   = "X-Forwarded-Ssl"
	HeaderXUrlScheme                      = "X-Url-Scheme"
	HeaderLocation                        = "Location"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderUserAgent                       = "User-Agent"
	HeaderAllow                           = "Allow"
	HeaderServer                          = "Server"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderContentRange                    = "Content-Range"
	HeaderIfRange                         = "If-Range"
	HeaderRange                           = "Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderLastEventID                     = "Last-Event-ID"
	HeaderNEL                             = "NEL"
	HeaderPingFrom                        = "Ping-From"
	HeaderPingTo                          = "Ping-To"
	HeaderReportTo                        = "Report-To"
	HeaderTE                              = "TE"
	HeaderTrailer                         = "Trailer"
	HeaderTransferEncoding                = "Transfer-Encoding"
	HeaderSecWebSocketAccept              = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions          = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey                 = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol            = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion             = "Sec-WebSocket-Version"
	HeaderAcceptPatch                     = "Accept-Patch"
	HeaderAcceptPushPolicy                = "Accept-Push-Policy"
	HeaderAcceptSignature                 = "Accept-Signature"
	HeaderAltSvc                          = "Alt-Svc"
	HeaderDate                            = "Date"
	HeaderIndex                           = "Index"
	HeaderLargeAllocation                 = "Large-Allocation"
	HeaderLink                            = "Link"
	HeaderPushPolicy                      = "Push-Policy"
	HeaderRetryAfter                      = "Retry-After"
	HeaderServerTiming                    = "Server-Timing"
	HeaderSignature                       = "Signature"
	HeaderSignedHeaders                   = "Signed-Headers"
	HeaderSourceMap                       = "SourceMap"
	HeaderUpgrade                         = "Upgrade"
	HeaderXDNSPrefetchControl             = "X-DNS-Prefetch-Control"
	HeaderXPingback                       = "X-Pingback"
	HeaderXRequestID                      = "X-Request-ID"
	HeaderXRequestedWith                  = "X-Requested-With"
	HeaderXRobotsTag                      = "X-Robots-Tag"
	HeaderXUACompatible                   = "X-UA-Compatible"
)
View Source
const (
	MethodGet     = "GET"     // RFC 7231, 4.3.1
	MethodHead    = "HEAD"    // RFC 7231, 4.3.2
	MethodPost    = "POST"    // RFC 7231, 4.3.3
	MethodPut     = "PUT"     // RFC 7231, 4.3.4
	MethodPatch   = "PATCH"   // RFC 5789
	MethodDelete  = "DELETE"  // RFC 7231, 4.3.5
	MethodConnect = "CONNECT" // RFC 7231, 4.3.6
	MethodOptions = "OPTIONS" // RFC 7231, 4.3.7
	MethodTrace   = "TRACE"   // RFC 7231, 4.3.8

)

HTTP methods

View Source
const (
	StatusContinue                      = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols            = 101 // RFC 7231, 6.2.2
	StatusProcessing                    = 102 // RFC 2518, 10.1
	StatusEarlyHints                    = 103 // RFC 8297
	StatusOK                            = 200 // RFC 7231, 6.3.1
	StatusCreated                       = 201 // RFC 7231, 6.3.2
	StatusAccepted                      = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInformation   = 203 // RFC 7231, 6.3.4
	StatusNoContent                     = 204 // RFC 7231, 6.3.5
	StatusResetContent                  = 205 // RFC 7231, 6.3.6
	StatusPartialContent                = 206 // RFC 7233, 4.1
	StatusMultiStatus                   = 207 // RFC 4918, 11.1
	StatusAlreadyReported               = 208 // RFC 5842, 7.1
	StatusIMUsed                        = 226 // RFC 3229, 10.4.1
	StatusMultipleChoices               = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently              = 301 // RFC 7231, 6.4.2
	StatusFound                         = 302 // RFC 7231, 6.4.3
	StatusSeeOther                      = 303 // RFC 7231, 6.4.4
	StatusNotModified                   = 304 // RFC 7232, 4.1
	StatusUseProxy                      = 305 // RFC 7231, 6.4.5
	StatusTemporaryRedirect             = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect             = 308 // RFC 7538, 3
	StatusBadRequest                    = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                  = 401 // RFC 7235, 3.1
	StatusPaymentRequired               = 402 // RFC 7231, 6.5.2
	StatusForbidden                     = 403 // RFC 7231, 6.5.3
	StatusNotFound                      = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed              = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                 = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired             = 407 // RFC 7235, 3.2
	StatusRequestTimeout                = 408 // RFC 7231, 6.5.7
	StatusConflict                      = 409 // RFC 7231, 6.5.8
	StatusGone                          = 410 // RFC 7231, 6.5.9
	StatusLengthRequired                = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed            = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge         = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong             = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType          = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable  = 416 // RFC 7233, 4.4
	StatusExpectationFailed             = 417 // RFC 7231, 6.5.14
	StatusTeapot                        = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest            = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity           = 422 // RFC 4918, 11.2
	StatusLocked                        = 423 // RFC 4918, 11.3
	StatusFailedDependency              = 424 // RFC 4918, 11.4
	StatusTooEarly                      = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired               = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired          = 428 // RFC 6585, 3
	StatusTooManyRequests               = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge   = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons    = 451 // RFC 7725, 3
	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes

View Source
const Version = "0.063"

Version is the current version of Zinc. This should be updated for each release.

Variables

View Source
var (
	ErrBadRequest                    = NewError(StatusBadRequest)                    // RFC 7231, 6.5.1
	ErrUnauthorized                  = NewError(StatusUnauthorized)                  // RFC 7235, 3.1
	ErrPaymentRequired               = NewError(StatusPaymentRequired)               // RFC 7231, 6.5.2
	ErrForbidden                     = NewError(StatusForbidden)                     // RFC 7231, 6.5.3
	ErrNotFound                      = NewError(StatusNotFound)                      // RFC 7231, 6.5.4
	ErrMethodNotAllowed              = NewError(StatusMethodNotAllowed)              // RFC 7231, 6.5.5
	ErrNotAcceptable                 = NewError(StatusNotAcceptable)                 // RFC 7231, 6.5.6
	ErrProxyAuthRequired             = NewError(StatusProxyAuthRequired)             // RFC 7235, 3.2
	ErrRequestTimeout                = NewError(StatusRequestTimeout)                // RFC 7231, 6.5.7
	ErrConflict                      = NewError(StatusConflict)                      // RFC 7231, 6.5.8
	ErrGone                          = NewError(StatusGone)                          // RFC 7231, 6.5.9
	ErrLengthRequired                = NewError(StatusLengthRequired)                // RFC 7231, 6.5.10
	ErrPreconditionFailed            = NewError(StatusPreconditionFailed)            // RFC 7232, 4.2
	ErrRequestEntityTooLarge         = NewError(StatusRequestEntityTooLarge)         // RFC 7231, 6.5.11
	ErrRequestURITooLong             = NewError(StatusRequestURITooLong)             // RFC 7231, 6.5.12
	ErrUnsupportedMediaType          = NewError(StatusUnsupportedMediaType)          // RFC 7231, 6.5.13
	ErrRequestedRangeNotSatisfiable  = NewError(StatusRequestedRangeNotSatisfiable)  // RFC 7233, 4.4
	ErrExpectationFailed             = NewError(StatusExpectationFailed)             // RFC 7231, 6.5.14
	ErrTeapot                        = NewError(StatusTeapot)                        // RFC 7168, 2.3.3
	ErrMisdirectedRequest            = NewError(StatusMisdirectedRequest)            // RFC 7540, 9.1.2
	ErrUnprocessableEntity           = NewError(StatusUnprocessableEntity)           // RFC 4918, 11.2
	ErrLocked                        = NewError(StatusLocked)                        // RFC 4918, 11.3
	ErrFailedDependency              = NewError(StatusFailedDependency)              // RFC 4918, 11.4
	ErrTooEarly                      = NewError(StatusTooEarly)                      // RFC 8470, 5.2.
	ErrUpgradeRequired               = NewError(StatusUpgradeRequired)               // RFC 7231, 6.5.15
	ErrPreconditionRequired          = NewError(StatusPreconditionRequired)          // RFC 6585, 3
	ErrTooManyRequests               = NewError(StatusTooManyRequests)               // RFC 6585, 4
	ErrRequestHeaderFieldsTooLarge   = NewError(StatusRequestHeaderFieldsTooLarge)   // RFC 6585, 5
	ErrUnavailableForLegalReasons    = NewError(StatusUnavailableForLegalReasons)    // RFC 7725, 3
	ErrInternalServerError           = NewError(StatusInternalServerError)           // RFC 7231, 6.6.1
	ErrNotImplemented                = NewError(StatusNotImplemented)                // RFC 7231, 6.6.2
	ErrBadGateway                    = NewError(StatusBadGateway)                    // RFC 7231, 6.6.3
	ErrServiceUnavailable            = NewError(StatusServiceUnavailable)            // RFC 7231, 6.6.4
	ErrGatewayTimeout                = NewError(StatusGatewayTimeout)                // RFC 7231, 6.6.5
	ErrHTTPVersionNotSupported       = NewError(StatusHTTPVersionNotSupported)       // RFC 7231, 6.6.6
	ErrVariantAlsoNegotiates         = NewError(StatusVariantAlsoNegotiates)         // RFC 2295, 8.1
	ErrInsufficientStorage           = NewError(StatusInsufficientStorage)           // RFC 4918, 11.5
	ErrLoopDetected                  = NewError(StatusLoopDetected)                  // RFC 5842, 7.2
	ErrNotExtended                   = NewError(StatusNotExtended)                   // RFC 2774, 7
	ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // RFC 6585, 6
)
View Source
var DefaultConfig = Config{
	DefaultAddr:               "0.0.0.0:6538",
	ServerHeader:              "Zinc/" + Version,
	AppName:                   "",
	AppVersion:                Version,
	ShutdownTimeout:           10 * time.Second,
	ReadTimeout:               5 * time.Second,
	WriteTimeout:              10 * time.Second,
	IdleTimeout:               120 * time.Second,
	CaseSensitive:             false,
	StrictRouting:             false,
	BodyLimit:                 4 * 1024 * 1024,
	Concurrency:               256 * 1024,
	EnableTrustedProxyCheck:   false,
	TrustedProxies:            []string{},
	ProxyHeader:               "X-Forwarded-For",
	DisableKeepalive:          false,
	DisableDefaultContentType: false,
	RouteCacheSize:            1000,
	DisableStartupMessage:     false,
	EnablePrintRoutes:         false,
}

DefaultConfig provides the default server configuration. It can be used as a base configuration for the server initialisation.

View Source
var ErrResponseAlreadySent = errors.New("response already sent")

Functions

func ContextServiceOf

func ContextServiceOf[T any](c *Context) (service T, ok bool)

ContextServiceOf is a helper function to retrieve a service by type from a Context Usage example: service, ok := zinc.ContextServiceOf[*UserService](c)

func GetVersion

func GetVersion() string

GetVersion returns the current version of Zinc.

func GetVersionHeader

func GetVersionHeader() string

GetVersionHeader returns the full version string for HTTP headers.

func ServiceOf

func ServiceOf[T any](a *App) (service T, ok bool)

ServiceOf is a convenience function to retrieve a service by type T Usage example: service := app.ServiceOf[*UserService]()

Types

type App

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

func New

func New(config ...Config) *App

New creates a new Zinc application instance with the specified configuration. If no configuration is provided, the default configuration is used.

func (*App) Connect

func (a *App) Connect(path string, handlers ...RouteHandler) error

Connect registers a route for the CONNECT HTTP method.

func (*App) ConnectDB

func (a *App) ConnectDB(driverName, dataSourceName string) error

ConnectDB establishes a connection to the database and stores the pool. It requires the driver name (e.g., "postgres", "sqlite3") and the DSN. Remember to import the specific database driver in your main package (e.g., _ "github.com/lib/pq").

func (*App) Cron

func (a *App) Cron(id string, schedule string, handler interface{}) error

Cron adds a cron job to be executed on the given schedule Supports both error-returning and non-error-returning handlers

func (*App) Delete

func (a *App) Delete(path string, handlers ...RouteHandler) error

Delete registers a route for the DELETE HTTP method.

func (*App) Get

func (a *App) Get(path string, handlers ...RouteHandler) error

Get registers a route for the GET HTTP method.

func (*App) GetDB

func (a *App) GetDB() *sql.DB

GetDB retrieves the configured database connection pool. Returns nil if no database connection has been established.

func (*App) GetService

func (a *App) GetService(serviceType reflect.Type) interface{}

GetService retrieves a service by its concrete type Returns the service or nil if not found

func (*App) Group

func (a *App) Group(prefix string) *Group

Group creates a new route group with a specified prefix

func (*App) Head

func (a *App) Head(path string, handlers ...RouteHandler) error

Head registers a route for the HEAD HTTP method.

func (*App) Injectable

func (a *App) Injectable(service interface{})

Register registers a service with the application by its concrete type This allows for type-safe retrieval using GetService() later

func (*App) Options

func (a *App) Options(path string, handlers ...RouteHandler) error

Options registers a route for the OPTIONS HTTP method.

func (*App) Patch

func (a *App) Patch(path string, handlers ...RouteHandler) error

Patch registers a route for the PATCH HTTP method.

func (*App) Post

func (a *App) Post(path string, handlers ...RouteHandler) error

Post registers a route for the POST HTTP method.

func (*App) Put

func (a *App) Put(path string, handlers ...RouteHandler) error

Put registers a route for the PUT HTTP method.

func (*App) RemoveCRON

func (a *App) RemoveCRON(id string)

RemoveCRON removes a scheduled job by ID

func (*App) Serve

func (a *App) Serve(port ...string) error

Serve starts the HTTP server on the specified port

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the default HTTP handler for the Zinc application.

func (*App) SetConfig

func (a *App) SetConfig(config *Config)

SetConfig sets the application configuration

func (*App) SetFileUpload

func (a *App) SetFileUpload(upload *FileUpload)

SetFileUpload sets the file upload handler

func (*App) SetTemplateEngine

func (a *App) SetTemplateEngine(engine *TemplateEngine)

SetTemplateEngine sets the template engine

func (*App) SetWebSocketHandler

func (a *App) SetWebSocketHandler(handler *WebSocketHandler)

SetWebSocketHandler sets the WebSocket handler

func (*App) StartCRON

func (a *App) StartCRON()

StartCRON starts the scheduler

func (*App) StopCRON

func (a *App) StopCRON()

StopScheduler stops all scheduled jobs

func (*App) Trace

func (a *App) Trace(path string, handlers ...RouteHandler) error

Trace registers a route for the TRACE HTTP method.

func (*App) Use

func (a *App) Use(middleware ...Middleware)

Use adds middleware to the application

func (*App) Validate

func (a *App) Validate(s any) ValidationErrors

Validate validates a struct using the validator

func (*App) Version

func (a *App) Version() string

Version returns the current version of the Zinc framework.

type BindOptions

type BindOptions struct {
	// DisableValidation disables validation after binding
	DisableValidation bool
	// DisableUnknownFields disables errors for unknown fields
	DisableUnknownFields bool
}

BindOptions holds options for binding data

type Config

type Config struct {
	// Server configuration
	// DefaultAddr specifies the HTTP server address.
	// If not set, the server will listen on "0.0.0.0:6538".
	DefaultAddr string
	// ServerHeader sets the value of the Server HTTP header.
	ServerHeader string
	// AppName specifies the name of the application.
	AppName string
	// AppVersion specifies the version of the application.
	AppVersion string

	// Timeout settings
	// ShutdownTimeout specifies the maximum duration to wait for server shutdown.
	ShutdownTimeout time.Duration
	// ReadTimeout is the maximum duration for reading the entire request.
	ReadTimeout time.Duration
	// WriteTimeout is the maximum duration before timing out writes of the response.
	WriteTimeout time.Duration
	// IdleTimeout is the maximum amount of time to wait for the next request.
	IdleTimeout time.Duration

	// Router settings
	// CaseSensitive determines if routes should be case-sensitive.
	// When false, /Foo and /foo are treated as the same route.
	CaseSensitive bool
	// StrictRouting determines if routes with trailing slashes are different than those without.
	// When false, /api and /api/ are treated as the same route.
	StrictRouting bool
	// BodyLimit sets the maximum allowed size for a request body in bytes.
	// Default is 4MB.
	BodyLimit int64
	// Concurrency sets the maximum number of concurrent connections.
	Concurrency int
	// EnableTrustedProxyCheck enables checking for trusted proxies
	// when determining client IP addresses.
	EnableTrustedProxyCheck bool
	// TrustedProxies is a list of IP addresses or CIDR blocks that are trusted.
	TrustedProxies []string
	// ProxyHeader specifies which header to use for client IP address.
	ProxyHeader string
	// DisableKeepalive disables keep-alive connections.
	DisableKeepalive bool
	// DisableDefaultContentType disables sending the Content-Type header in responses
	// when no content type is explicitly set.
	DisableDefaultContentType bool

	// Routing cache settings
	// RouteCacheSize determines how many routes are stored in the route cache.
	// Set to 0 to disable caching.
	RouteCacheSize int

	// Debug settings
	// DisableStartupMessage disables the startup message when the server starts.
	DisableStartupMessage bool
	// EnablePrintRoutes enables printing all routes on startup.
	EnablePrintRoutes bool
}

Config holds the server configuration parameters.

type Context

type Context struct {
	Response    http.ResponseWriter
	Request     *http.Request
	PathParams  params
	QueryParams url.Values
	Method      string

	Store map[string]interface{}
	// contains filtered or unexported fields
}

Context holds the context for a request. It is used to pass data between middleware and handlers.

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request) *Context

NewContext creates a new context for a request.

func (*Context) Bind

func (c *Context) Bind(v interface{}, opts ...*BindOptions) error

Bind automatically binds request data based on Content-Type

func (*Context) BindForm

func (c *Context) BindForm(v interface{}, opts ...*BindOptions) error

BindForm binds form data to the provided struct and validates it

func (*Context) BindJSON

func (c *Context) BindJSON(v interface{}, opts ...*BindOptions) error

BindJSON binds the JSON request body to the provided struct and validates it

func (*Context) BindQuery

func (c *Context) BindQuery(v interface{}, opts ...*BindOptions) error

BindQuery binds query parameters to the provided struct and validates it

func (*Context) BindXML

func (c *Context) BindXML(v interface{}, opts ...*BindOptions) error

BindXML binds the XML request body to the provided struct and validates it

func (*Context) Body

func (c *Context) Body() (string, error)

Body returns the request body as a string.

func (*Context) BodyParser

func (c *Context) BodyParser(out interface{}) error

BodyParser parses the request body into a provided struct.

func (*Context) BroadcastToRoom

func (c *Context) BroadcastToRoom(roomID string, message []byte) error

func (*Context) DB

func (c *Context) DB() *sql.DB

DB returns the database connection pool associated with the application. It returns nil if no database connection has been configured for the App.

func (*Context) File

func (c *Context) File(name string) (*multipart.FileHeader, error)

File gets an uploaded file from the request

func (*Context) Files

func (c *Context) Files(name string) ([]*multipart.FileHeader, error)

Files gets all uploaded files for a form field

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

FormFile returns the first file from the multipart form

func (*Context) FormFiles

func (c *Context) FormFiles(name string) ([]*multipart.FileHeader, error)

FormFiles returns all files with the given field name

func (*Context) Get

func (c *Context) Get(key string) interface{}

Get retrieves a value from the context store.

func (*Context) HTML

func (c *Context) HTML(data string) error

func (*Context) HasQuery

func (c *Context) HasQuery(name string) bool

Optimized method to check if a query parameter exists (avoids additional parsing)

func (*Context) IP

func (c *Context) IP() string

IP returns the client's IP address.

func (*Context) JSON

func (c *Context) JSON(data interface{}) error

JSON serializes and sends JSON data

func (*Context) JoinRoom

func (c *Context) JoinRoom(roomID string, conn *websocket.Conn)

func (*Context) LeaveRoom

func (c *Context) LeaveRoom(roomID string, conn *websocket.Conn)

func (*Context) Next

func (c *Context) Next() error

Next calls the next middleware in the chain.

func (*Context) Param

func (c *Context) Param(name string) string

Param retrieves a path parameter by name.

func (*Context) Query

func (c *Context) Query(name string) string

Query retrieves a query parameter by name (with lazy loading)

func (*Context) RemoteIP

func (c *Context) RemoteIP() string

RemoteIP returns the remote IP address of the request.

func (*Context) Render

func (c *Context) Render(name string, data interface{}) error

Add template rendering methods to Context

func (*Context) SaveFile

func (c *Context) SaveFile(fileHeader *multipart.FileHeader, dst string) error

SaveFile saves a file from a multipart form to the specified destination

func (*Context) Send

func (c *Context) Send(data any) error

Send sends a response with the appropriate content type.

func (*Context) Service

func (c *Context) Service(name interface{}) interface{}

Service returns a service by name.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set stores a value in the context store.

func (*Context) Static

func (c *Context) Static(filepath string) error

func (*Context) Status

func (c *Context) Status(code int) *Context

Status sets the status code for the response.

func (*Context) String

func (c *Context) String(data string) error

String sends a string response

func (*Context) Upgrade

func (c *Context) Upgrade() (*websocket.Conn, error)

func (*Context) Version

func (c *Context) Version() string

Version returns the current version of the Zinc framework.

type CronJob

type CronJob struct {
	ID       string
	Schedule string
	Handler  func() error
	// contains filtered or unexported fields
}

CronJob represents a single scheduled job

type CronScheduler

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

CronScheduler manages all cron jobs

func (*CronScheduler) AddJob

func (cs *CronScheduler) AddJob(id, schedule string, handler func() error) error

AddJob adds a new job to the scheduler

func (*CronScheduler) RemoveJob

func (cs *CronScheduler) RemoveJob(id string)

RemoveJob removes a job from the scheduler

func (*CronScheduler) Start

func (cs *CronScheduler) Start()

Start starts the scheduler

func (*CronScheduler) Stop

func (cs *CronScheduler) Stop()

Stop stops the scheduler

type DBRoutedHandler

type DBRoutedHandler func(c *Context, db *sql.DB) error

DBRoutedHandler defines a handler function that expects a Context and a DB connection.

type FileUpload

type FileUpload struct {
	MaxSize    int64
	AllowTypes []string
	Directory  string
}

FileUpload represents file upload configuration

func NewFileUpload

func NewFileUpload(directory string) *FileUpload

NewFileUpload creates a new file upload handler

func (*FileUpload) SaveFile

func (f *FileUpload) SaveFile(file *multipart.FileHeader) (string, error)

SaveFile saves an uploaded file

func (*FileUpload) SetAllowedTypes

func (f *FileUpload) SetAllowedTypes(types []string)

SetAllowedTypes sets allowed file types

func (*FileUpload) SetMaxSize

func (f *FileUpload) SetMaxSize(size int64)

SetMaxSize sets the maximum file size in bytes

type Group

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

Group represents a group of routes with a common prefix and potentially shared middleware

func NewGroup

func NewGroup(app *App, prefix string) *Group

NewGroup creates a new route group

func (*Group) Add

func (g *Group) Add(method, path string, handlers ...RouteHandler) error

Add adds a route to the group with the given method and path

func (*Group) Connect

func (g *Group) Connect(path string, handlers ...RouteHandler) error

Connect registers a route for the CONNECT HTTP method

func (*Group) Delete

func (g *Group) Delete(path string, handlers ...RouteHandler) error

Delete registers a route for the DELETE HTTP method

func (*Group) Get

func (g *Group) Get(path string, handlers ...RouteHandler) error

Get registers a route for the GET HTTP method

func (*Group) Group

func (g *Group) Group(prefix string) *Group

Group creates a new sub-group with an additional prefix

func (*Group) Head

func (g *Group) Head(path string, handlers ...RouteHandler) error

Head registers a route for the HEAD HTTP method

func (*Group) Options

func (g *Group) Options(path string, handlers ...RouteHandler) error

Options registers a route for the OPTIONS HTTP method

func (*Group) Patch

func (g *Group) Patch(path string, handlers ...RouteHandler) error

Patch registers a route for the PATCH HTTP method

func (*Group) Post

func (g *Group) Post(path string, handlers ...RouteHandler) error

Post registers a route for the POST HTTP method

func (*Group) Put

func (g *Group) Put(path string, handlers ...RouteHandler) error

Put registers a route for the PUT HTTP method

func (*Group) Trace

func (g *Group) Trace(path string, handlers ...RouteHandler) error

Trace registers a route for the TRACE HTTP method

func (*Group) Use

func (g *Group) Use(middleware ...Middleware) *Group

Use adds middleware to the group

type HTTPError

type HTTPError struct {
	Code    int    // HTTP status code
	Message string // Error message
}

HTTPError represents an HTTP error with a status code and optional message.

func NewError

func NewError(code int) *HTTPError

NewError creates a new HTTPError with the given status code.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface.

func (*HTTPError) WithMessage

func (e *HTTPError) WithMessage(message string) *HTTPError

WithMessage sets a custom message for the error.

type Map

type Map map[string]any

type Middleware

type Middleware func(c *Context) error

Middleware represents a function that can be used as middleware.

type Room

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

type Route

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

Route represents a route in the router.

type RouteCache

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

RouteCache provides an LRU cache for routes.

func NewRouteCache

func NewRouteCache(size int) *RouteCache

NewRouteCache creates a new route cache with the specified size.

type RouteHandler

type RouteHandler func(c *Context) error

RouteHandler represents a function that handles a route request.

func StringHandler

func StringHandler(str string) RouteHandler

StringHandler creates a RouteHandler that returns the provided string.

func WithDB

func WithDB(handler DBRoutedHandler) RouteHandler

WithDB wraps a DBRoutedHandler, automatically providing the DB connection from the context. It returns a standard RouteHandler. If the DB connection is not available in the context, it returns a 500 error.

type RouteHandlerMap

type RouteHandlerMap map[string]RouteHandler

RouteHandlerMap is a map of HTTP methods to route handlers.

type RouteMap

type RouteMap map[string]map[string]*Route

RouteMap is a map of HTTP methods to paths to routes.

type RouteNode

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

RouteNode represents a node in the route trie.

type Router

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

Router handles HTTP routes and dispatches to the appropriate handler.

func (*Router) Add

func (r *Router) Add(method, path string, handlers ...RouteHandler) error

Add adds a route to the router.

func (*Router) Find

func (r *Router) Find(method, path string) (RouteHandler, *Context)

Find finds a route handler for the given method and path.

func (*Router) Use

func (r *Router) Use(middleware ...Middleware)

Use adds middleware to the router.

type TemplateEngine

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

TemplateEngine handles template rendering with caching

func NewTemplateEngine

func NewTemplateEngine(directory string) *TemplateEngine

NewTemplateEngine creates a new template engine

func (*TemplateEngine) AddFunc

func (e *TemplateEngine) AddFunc(name string, fn interface{})

AddFunc adds a single template function

func (*TemplateEngine) ClearCache

func (e *TemplateEngine) ClearCache()

ClearCache clears the template cache

func (*TemplateEngine) DisableCache

func (e *TemplateEngine) DisableCache()

DisableCache disables template caching

func (*TemplateEngine) GetDirectory

func (e *TemplateEngine) GetDirectory() string

GetDirectory returns the template directory path

func (*TemplateEngine) LoadTemplates

func (e *TemplateEngine) LoadTemplates() error

LoadTemplates preloads all templates from the directory

func (*TemplateEngine) Render

func (e *TemplateEngine) Render(w io.Writer, name string, data interface{}) error

Render renders a template with the given data

func (*TemplateEngine) SetExtension

func (e *TemplateEngine) SetExtension(ext string)

SetExtension sets the template file extension

func (*TemplateEngine) SetFuncMap

func (e *TemplateEngine) SetFuncMap(funcMap template.FuncMap)

SetFuncMap sets custom template functions

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

type ValidationErrors

type ValidationErrors []ValidationError

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

type Validator

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

func NewValidator

func NewValidator() *Validator

func (*Validator) Validate

func (v *Validator) Validate(s interface{}) ValidationErrors

type WebSocketHandler

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

func WebSocket

func WebSocket() *WebSocketHandler

func (*WebSocketHandler) BroadcastToRoom

func (h *WebSocketHandler) BroadcastToRoom(roomID string, message []byte) error

func (*WebSocketHandler) HandleWebSocket

func (h *WebSocketHandler) HandleWebSocket(c *Context) error

func (*WebSocketHandler) JoinRoom

func (h *WebSocketHandler) JoinRoom(roomID string, conn *websocket.Conn)

func (*WebSocketHandler) LeaveRoom

func (h *WebSocketHandler) LeaveRoom(roomID string, conn *websocket.Conn)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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