goTap

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2025 License: MIT Imports: 50 Imported by: 0

README ΒΆ

goTap Web Framework

Go Version License

goTap is a high-performance HTTP web framework for Go, inspired by Gin. Designed specifically for highly available and low-latency POS (Point-of-Sale) systems, REST APIs, web applications, and microservices.

πŸš€ Features

Core Framework
  • High Performance - Fast routing with radix tree, context pooling
  • Middleware Chain - Extensible middleware system with Logger, Recovery
  • Route Grouping - Organize routes with common prefixes and middleware
  • Parameter Binding - URL params, query strings, JSON, XML, Form, Headers
  • Data Validation - 11 built-in validators (required, email, min/max, etc.)
  • Error Management - Panic recovery and centralized error handling
Security Middleware
  • JWT Authentication - HMAC-SHA256 token generation with role-based access
  • BasicAuth - HTTP Basic Authentication with timing attack prevention
  • CORS - Cross-Origin Resource Sharing with wildcard support
  • Rate Limiting - Token bucket algorithm with per-user/path controls
  • IP Filtering - Whitelist/blacklist with CIDR support
Rendering & Responses
  • JSON Variants - Standard, Indented, Secure, JSONP, ASCII, Pure JSON
  • XML/YAML - Full XML and YAML rendering support
  • HTML Templates - Go template engine with glob/file loading
  • Content Negotiation - Accept header-based format selection
  • Gzip Compression - Automatic response compression with smart thresholds
  • Server-Sent Events - Streaming real-time updates
API Documentation
  • Swagger/OpenAPI - Interactive API documentation with Swagger UI
  • Auto-Generation - Generate docs from code annotations
  • Interactive Testing - Test APIs directly in browser
  • Authentication Support - JWT, BasicAuth in Swagger UI
  • OpenAPI 3.0 - Industry-standard API specification
POS-Optimized Features
  • Shadow Database - Dual-DB with automatic failover and health monitoring
  • GORM Integration - Type-safe ORM with MySQL, PostgreSQL, SQLite support
  • WebSocket Support - Real-time bidirectional communication
  • Transaction Tracking - Audit trail with UUID/POS ID generation
  • High Availability - Built for 99.9%+ uptime retail systems

πŸ“¦ Installation

go get -u github.com/jaswant99k/gotap

Requirements: Go 1.21+

🎯 Quick Start

package main

import "github.com/jaswant99k/gotap"

func main() {
    // Create router with Logger and Recovery middleware
    r := goTap.Default()

    // Define routes
    r.GET("/ping", func(c *goTap.Context) {
        c.JSON(200, goTap.H{
            "message": "pong",
        })
    })

    // URL parameters
    r.GET("/hello/:name", func(c *goTap.Context) {
        name := c.Param("name")
        c.JSON(200, goTap.H{
            "message": "Hello " + name,
        })
    })

    // Start server on :8080
    r.Run()
}

πŸ“– Examples

Route Parameters
r.GET("/user/:id", func(c *goTap.Context) {
    id := c.Param("id")
    c.String(200, "User ID: %s", id)
})
Query Strings
r.GET("/search", func(c *goTap.Context) {
    query := c.Query("q")
    c.JSON(200, goTap.H{"query": query})
})
Route Groups
api := r.Group("/api/v1")
{
    api.GET("/users", listUsers)
    api.POST("/users", createUser)
    api.GET("/users/:id", getUser)
}
POST Form Data
r.POST("/form", func(c *goTap.Context) {
    name := c.PostForm("name")
    email := c.PostForm("email")
    c.JSON(200, goTap.H{
        "name": name,
        "email": email,
    })
})
Custom Middleware
func AuthMiddleware() goTap.HandlerFunc {
    return func(c *goTap.Context) {
        token := c.GetHeader("Authorization")
        if token == "" {
            c.AbortWithStatusJSON(401, goTap.H{"error": "unauthorized"})
            return
        }
        c.Next()
    }
}

// Use middleware
r.Use(AuthMiddleware())
CORS Middleware
// Allow all origins (development)
r.Use(goTap.CORS())

// Production: whitelist specific origins
r.Use(goTap.CORSWithConfig(goTap.CORSConfig{
    AllowOrigins: []string{"https://pos.retailer.com"},
    AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
    AllowCredentials: true,
    MaxAge: 3600,
}))
Gzip Compression
// Default: compress responses >1KB
r.Use(goTap.Gzip())

// Custom: fast compression for real-time POS
r.Use(goTap.GzipWithConfig(goTap.GzipConfig{
    Level: gzip.BestSpeed,
    MinLength: 512,
    ExcludedExtensions: []string{".jpg", ".png", ".pdf"},
}))
JWT Authentication
secret := "your-secret-key-minimum-32-characters"

// Public routes
r.POST("/login", loginHandler)
r.POST("/register", registerHandler)

// Protected routes (require authentication)
auth := r.Group("/api")
auth.Use(goTap.JWTAuth(secret))
{
    auth.GET("/profile", getProfile)
    auth.PUT("/profile", updateProfile)
}

// Admin-only routes
admin := r.Group("/admin")
admin.Use(goTap.JWTAuth(secret))
admin.Use(goTap.RequireRole("admin"))
{
    admin.GET("/users", listUsers)
    admin.DELETE("/users/:id", deleteUser)
}

// Multiple roles allowed
manage := r.Group("/manage")
manage.Use(goTap.JWTAuth(secret))
manage.Use(goTap.RequireAnyRole("admin", "manager"))
{
    manage.GET("/orders", listOrders)
}

See full authentication guide: examples/auth/README.md

GORM Database Integration
import (
    "github.com/jaswant99k/gotap"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

// Connect to database
db, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{})

// Inject GORM into context
r.Use(goTap.GormInject(db))

// Use in handlers
r.GET("/users/:id", func(c *goTap.Context) {
    db := goTap.MustGetGorm(c)
    var user User
    db.First(&user, c.Param("id"))
    c.JSON(200, user)
})

See full GORM guide: examples/gorm/README.md

πŸ—οΈ Project Structure

goTap/
β”œβ”€β”€ gotap.go              # Main engine
β”œβ”€β”€ context.go            # Request context
β”œβ”€β”€ router.go             # Routing logic
β”œβ”€β”€ routergroup.go        # Route grouping
β”œβ”€β”€ tree.go               # Radix tree
β”œβ”€β”€ middleware/           # Built-in middleware
β”œβ”€β”€ examples/             # Usage examples
└── tests/                # Unit tests

🎯 Roadmap

Phase 1: Core Foundation βœ…
  • Basic engine and context
  • Routing with radix tree
  • HTTP method handlers
  • Logger and Recovery middleware
Phase 2: Advanced Routing βœ…
  • Static file serving
  • File uploads/downloads
  • Route groups
Phase 3: Security Middleware βœ…
  • JWT authentication middleware
  • BasicAuth middleware
  • CORS middleware
  • Gzip compression
  • Transaction ID tracking
  • IP whitelist middleware
  • Rate limiting
Phase 4-6: Data & Rendering βœ…
  • Data binding and validation
  • Multiple render formats (JSON variants, XML, YAML, HTML)
  • Content negotiation
  • Server-Sent Events
  • Shadow Database integration
  • WebSocket support
Phase 7: Performance (In Progress)
  • Comprehensive benchmarking suite
  • Memory profiling and optimization
  • Zero-allocation improvements
  • Connection pooling
Phase 8: Testing (85% Complete)
  • 113 comprehensive tests
  • Middleware tests
  • Binding and validation tests
  • 90%+ code coverage target
Phase 9: Advanced Features (Planned)
  • Custom validators plugin system
  • Hot reload support
  • Metrics and tracing
  • HTTP/2 Server Push

πŸ“Š Performance

goTap is designed for high performance:

  • Routing: < 30,000 ns/op for complex routes
  • Throughput: 100,000+ req/sec target
  • Latency: Sub-millisecond response time
  • Memory: Zero-allocation routing

🀝 Contributing

Contributions are welcome! Please read CONTRIBUTING.md for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

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

πŸ™ Acknowledgments

  • Inspired by Gin
  • Built for the POS industry with ❀️

πŸ“§ Contact


Made with ❀️ for high-performance POS systems

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	MIMEJSON              = "application/json"
	MIMEHTML              = "text/html"
	MIMEXML               = "application/xml"
	MIMEXML2              = "text/xml"
	MIMEPlain             = "text/plain"
	MIMEPOSTForm          = "application/x-www-form-urlencoded"
	MIMEMultipartPOSTForm = "multipart/form-data"
)

Content-Type MIME of the most common data formats.

View Source
const (
	// DebugMode indicates goTap mode is debug.
	DebugMode = "debug"
	// ReleaseMode indicates goTap mode is release.
	ReleaseMode = "release"
	// TestMode indicates goTap mode is test.
	TestMode = "test"
)
View Source
const Version = "0.1.0"

Variables ΒΆ

View Source
var (
	JSON          = jsonBinding{}
	XML           = xmlBinding{}
	Form          = formBinding{}
	Query         = queryBinding{}
	FormPost      = formPostBinding{}
	FormMultipart = formMultipartBinding{}
	Header        = headerBinding{}
	Uri           = uriBinding{}
)
View Source
var (
	ErrInvalidToken      = errors.New("invalid token")
	ErrExpiredToken      = errors.New("token has expired")
	ErrInvalidSignature  = errors.New("invalid signature")
	ErrMissingToken      = errors.New("missing authorization token")
	ErrInvalidAuthHeader = errors.New("invalid authorization header format")
)

JWT errors

View Source
var (
	// DefaultWriter is the default io.Writer used by goTap for debug output and
	// middleware output like Logger() or Recovery().
	DefaultWriter io.Writer = os.Stdout

	// DefaultErrorWriter is the default io.Writer used by goTap to debug errors
	DefaultErrorWriter io.Writer = os.Stderr
)
View Source
var (
	// ErrWebSocketUpgradeFailed is returned when WebSocket upgrade fails
	ErrWebSocketUpgradeFailed = errors.New("websocket upgrade failed")
	// ErrConnectionClosed is returned when connection is closed
	ErrConnectionClosed = errors.New("connection closed")
)
View Source
var WSUpgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

WSUpgrader is the default WebSocket upgrader

Functions ΒΆ

func AutoMigrate ΒΆ

func AutoMigrate(db *gorm.DB, models ...interface{}) error

AutoMigrate runs auto migration for given models

func CosineSimilarity ΒΆ

func CosineSimilarity(a, b Vector) float32

CosineSimilarity calculates cosine similarity between two vectors

func Dir ΒΆ

func Dir(root string, listDirectory bool) http.FileSystem

Dir returns a http.FileSystem that can be used by http.FileServer(). It is used internally in router.Static(). if listDirectory == true, then it works the same as http.Dir() otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.

func DotProduct ΒΆ

func DotProduct(a, b Vector) float32

DotProduct calculates dot product of two vectors

func EuclideanDistance ΒΆ

func EuclideanDistance(a, b Vector) float32

EuclideanDistance calculates Euclidean distance between two vectors

func GenerateJWT ΒΆ

func GenerateJWT(secret string, claims JWTClaims) (string, error)

GenerateJWT generates a new JWT token with the given claims

func GetGorm ΒΆ

func GetGorm(c *Context) (*gorm.DB, bool)

GetGorm retrieves GORM database from context

func GetReadDB ΒΆ

func GetReadDB(c *Context) (*sql.DB, bool)

GetReadDB retrieves read database connection from context

func GetShadowDB ΒΆ

func GetShadowDB(c *Context) (*shadowdb.ShadowDB, bool)

GetShadowDB retrieves Shadow DB from context

func GetTransactionID ΒΆ

func GetTransactionID(c *Context) string

GetTransactionID retrieves transaction ID from context

func GetWriteDB ΒΆ

func GetWriteDB(c *Context) (*sql.DB, bool)

GetWriteDB retrieves write database connection from context

func GormBatchDelete ΒΆ

func GormBatchDelete(db *gorm.DB, model interface{}, ids []interface{}) error

GormBatchDelete performs batch soft delete operation

func GormBatchInsert ΒΆ

func GormBatchInsert(db *gorm.DB, records interface{}, batchSize int) error

GormBatchInsert performs batch insert operation

func GormBatchUpdate ΒΆ

func GormBatchUpdate(db *gorm.DB, model interface{}, updates map[string]interface{}) error

GormBatchUpdate performs batch update operation

func GormCountRecords ΒΆ

func GormCountRecords(db *gorm.DB, model interface{}, condition ...interface{}) (int64, error)

GormCountRecords counts total records for pagination

func GormCreate ΒΆ

func GormCreate(db *gorm.DB, value interface{}) error

GormCreate creates a new record

func GormDelete ΒΆ

func GormDelete(db *gorm.DB, value interface{}, conds ...interface{}) error

GormDelete deletes a record (soft delete if model has DeletedAt)

func GormExecRaw ΒΆ

func GormExecRaw(db *gorm.DB, sql string, values ...interface{}) error

GormExecRaw executes raw SQL query

func GormExists ΒΆ

func GormExists(db *gorm.DB, model interface{}, condition ...interface{}) (bool, error)

GormExists checks if a record exists

func GormFind ΒΆ

func GormFind(db *gorm.DB, dest interface{}, pagination *GormPagination, condition ...interface{}) error

GormFind helper for finding records with pagination

func GormFindByID ΒΆ

func GormFindByID(db *gorm.DB, dest interface{}, id interface{}) error

GormFindByID finds a record by ID

func GormQueryRaw ΒΆ

func GormQueryRaw(db *gorm.DB, dest interface{}, sql string, values ...interface{}) error

GormQueryRaw executes raw SQL query and scans results

func GormSearch ΒΆ

func GormSearch(db *gorm.DB, table, column, query string) *gorm.DB

GormSearch performs full-text search (MySQL)

func GormUpdate ΒΆ

func GormUpdate(db *gorm.DB, model interface{}, updates interface{}) error

GormUpdate updates a record

func GormWithContext ΒΆ

func GormWithContext(c *Context) *gorm.DB

GormWithContext returns GORM DB with request context

func IsDebugging ΒΆ

func IsDebugging() bool

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

func Mode ΒΆ

func Mode() string

Mode returns current goTap mode.

func MustGetGorm ΒΆ

func MustGetGorm(c *Context) *gorm.DB

MustGetGorm retrieves GORM database from context or panics

func NewGormDB ΒΆ

func NewGormDB(config *DBConfig) (*gorm.DB, error)

NewGormDB creates a new GORM database connection

func POSTransactionIDGenerator ΒΆ

func POSTransactionIDGenerator(terminalID string) func() string

POSTransactionIDGenerator generates POS-specific transaction IDs Format: POS-TERMINALID-TIMESTAMP-COUNTER

func RefreshToken ΒΆ

func RefreshToken(oldToken, secret string, extendDuration time.Duration) (string, error)

RefreshToken generates a new token with extended expiration

func SetMode ΒΆ

func SetMode(value string)

SetMode sets goTap mode according to input string.

func SetValidator ΒΆ

func SetValidator(v Validator)

SetValidator sets the default validator

func SetupSwagger ΒΆ

func SetupSwagger(r *Engine, basePath string)

SetupSwagger registers Swagger UI routes Usage:

import _ "yourmodule/docs" // swagger docs
goTap.SetupSwagger(r, "/swagger")

func SetupSwaggerWithAuth ΒΆ

func SetupSwaggerWithAuth(r *Engine, basePath string, authMiddleware ...HandlerFunc)

SetupSwaggerWithAuth registers Swagger UI routes with authentication Usage:

goTap.SetupSwaggerWithAuth(r, "/swagger", goTap.JWTAuth(jwtSecret))

func ShortTransactionIDGenerator ΒΆ

func ShortTransactionIDGenerator() string

ShortTransactionIDGenerator generates short transaction IDs (12 chars)

func Shutdown ΒΆ

func Shutdown(srv *http.Server, ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting active connections. This is a convenience wrapper around http.Server.Shutdown. It waits for all active requests to complete or until the context is canceled.

func ShutdownWithTimeout ΒΆ

func ShutdownWithTimeout(srv *http.Server, timeout ...time.Duration) error

ShutdownWithTimeout is a convenience method that creates a context with timeout and calls Shutdown. Default timeout is 5 seconds.

func UUIDTransactionIDGenerator ΒΆ

func UUIDTransactionIDGenerator() string

UUIDTransactionIDGenerator generates UUID-like transaction IDs

func VectorToJSON ΒΆ

func VectorToJSON(vector Vector) string

VectorToJSON converts a vector to JSON string

func WithTransaction ΒΆ

func WithTransaction(db *gorm.DB, fn func(tx *gorm.DB) error) error

WithTransaction helper function to run code in a transaction

Types ΒΆ

type Accounts ΒΆ

type Accounts map[string]string

Accounts defines a key/value for user/pass list of authorized logins

type BasicAuthPair ΒΆ

type BasicAuthPair struct {
	Username string
	Password string
}

BasicAuthPair represents a user/password pair for BasicAuth

type Binding ΒΆ

type Binding interface {
	Name() string
	Bind(*http.Request, interface{}) error
}

Binding describes the interface which needs to be implemented for binding request data

func DefaultBinding ΒΆ

func DefaultBinding(method, contentType string) Binding

DefaultBinding returns the appropriate Binding instance based on the HTTP method and Content-Type

type BindingBody ΒΆ

type BindingBody interface {
	Binding
	BindBody(io.Reader, interface{}) error
}

BindingBody adds BindBody method to Binding. BindBody is similar to Bind, but it reads the body from supplied io.Reader instead of req.Body

type BindingUri ΒΆ

type BindingUri interface {
	Name() string
	BindUri(map[string][]string, interface{}) error
}

BindingUri binds from request URI (path and query params)

type CORSConfig ΒΆ

type CORSConfig struct {
	// AllowOrigins is a list of origins that may access the resource
	// Default: []string{"*"}
	AllowOrigins []string

	// AllowMethods is a list of methods the client is allowed to use
	// Default: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
	AllowMethods []string

	// AllowHeaders is a list of request headers that can be used when making the actual request
	// Default: []string{"Origin", "Content-Length", "Content-Type"}
	AllowHeaders []string

	// ExposeHeaders indicates which headers are safe to expose
	// Default: []string{}
	ExposeHeaders []string

	// AllowCredentials indicates whether the request can include user credentials
	// Default: false
	AllowCredentials bool

	// MaxAge indicates how long the results of a preflight request can be cached
	// Default: 12 hours
	MaxAge time.Duration

	// AllowWildcard allows wildcard subdomains (e.g., https://*.example.com)
	// Default: false
	AllowWildcard bool

	// AllowOriginFunc is a custom function to validate the origin
	// It takes the origin as an argument and returns true if allowed
	// This overrides AllowOrigins
	AllowOriginFunc func(origin string) bool
}

CORSConfig defines the config for CORS middleware

func DefaultCORSConfig ΒΆ

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig returns a default CORS configuration

type Context ΒΆ

type Context struct {
	Request *http.Request
	Writer  ResponseWriter

	Params Params

	// Keys is a key/value pair exclusively for the context of each request.
	Keys map[string]any

	// Errors is a list of errors attached to all the handlers/middlewares who used this context.
	Errors errorMsgs

	// Accepted defines a list of manually accepted formats for content negotiation.
	Accepted []string
	// contains filtered or unexported fields
}

Context is the most important part of goTap. It allows us to pass variables between middleware, manage the flow, validate the JSON of a request and render a JSON response for example.

func (*Context) Abort ΒΆ

func (c *Context) Abort()

Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.

func (*Context) AbortWithError ΒΆ

func (c *Context) AbortWithError(code int, err error) *Error

AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and pushes the specified error to `c.Errors`. See Context.Error() for more details.

func (*Context) AbortWithStatus ΒΆ

func (c *Context) AbortWithStatus(code int)

AbortWithStatus calls `Abort()` and writes the headers with the specified status code. For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).

func (*Context) AbortWithStatusJSON ΒΆ

func (c *Context) AbortWithStatusJSON(code int, jsonObj any)

AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body. It also sets the Content-Type as "application/json".

func (*Context) AbortWithStatusPureJSON ΒΆ

func (c *Context) AbortWithStatusPureJSON(code int, jsonObj any)

AbortWithStatusPureJSON calls `Abort()` and then `PureJSON` internally. This method stops the chain, writes the status code and return a JSON body without escaping. It also sets the Content-Type as "application/json".

func (*Context) AsciiJSON ΒΆ

func (c *Context) AsciiJSON(code int, obj interface{})

AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string It also sets the Content-Type as "application/json"

func (*Context) Bind ΒΆ

func (c *Context) Bind(obj interface{}) error

Bind checks the Content-Type to select a binding engine automatically

func (*Context) BindHeader ΒΆ

func (c *Context) BindHeader(obj interface{}) error

BindHeader is a shortcut for c.MustBindWith(obj, binding.Header)

func (*Context) BindJSON ΒΆ

func (c *Context) BindJSON(obj interface{}) error

BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON)

func (*Context) BindQuery ΒΆ

func (c *Context) BindQuery(obj interface{}) error

BindQuery is a shortcut for c.MustBindWith(obj, binding.Query)

func (*Context) BindUri ΒΆ

func (c *Context) BindUri(obj interface{}) error

BindUri binds the passed struct pointer using the URI parameters

func (*Context) BindXML ΒΆ

func (c *Context) BindXML(obj interface{}) error

BindXML is a shortcut for c.MustBindWith(obj, binding.XML)

func (*Context) ClientIP ΒΆ

func (c *Context) ClientIP() string

ClientIP implements one best effort algorithm to return the real client IP. It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not.

func (*Context) ContentType ΒΆ

func (c *Context) ContentType() string

ContentType returns the Content-Type header of the request.

func (*Context) Cookie ΒΆ

func (c *Context) Cookie(name string) (string, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.

func (*Context) Copy ΒΆ

func (c *Context) Copy() *Context

Copy returns a copy of the current context that can be safely used outside the request's scope. This has to be used when the context has to be passed to a goroutine.

func (*Context) Data ΒΆ

func (c *Context) Data(code int, contentType string, data []byte)

Data writes some data into the body stream and updates the HTTP code.

func (*Context) Deadline ΒΆ

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

Deadline always returns that there is no deadline (ok==false).

func (*Context) DefaultPostForm ΒΆ

func (c *Context) DefaultPostForm(key, defaultValue string) string

DefaultPostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns the specified defaultValue string.

func (*Context) DefaultQuery ΒΆ

func (c *Context) DefaultQuery(key, defaultValue string) string

DefaultQuery returns the keyed url query value if it exists, otherwise it returns the specified defaultValue string.

func (*Context) Done ΒΆ

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

Done always returns nil (chan which will wait forever).

func (*Context) Err ΒΆ

func (c *Context) Err() error

Err always returns nil.

func (*Context) Error ΒΆ

func (c *Context) Error(err error) *Error

Error attaches an error to the current context. The error is pushed to a list of errors. It's a good idea to call Error for each error that occurred during the resolution of a request. A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response. Error will panic if err is nil.

func (*Context) File ΒΆ

func (c *Context) File(filepath string)

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

func (*Context) FileAttachment ΒΆ

func (c *Context) FileAttachment(filepath, filename string)

FileAttachment writes the specified file into the body stream in an efficient way On the client side, the file will be downloaded with the given filename

func (*Context) FileFromFS ΒΆ

func (c *Context) FileFromFS(filepath string, fs http.FileSystem)

FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way.

func (*Context) FormFile ΒΆ

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

FormFile returns the first file for the provided form key

func (*Context) FullPath ΒΆ

func (c *Context) FullPath() string

FullPath returns a matched route full path. For not found routes returns an empty string.

func (*Context) Get ΒΆ

func (c *Context) Get(key string) (value any, exists bool)

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

func (*Context) GetHeader ΒΆ

func (c *Context) GetHeader(key string) string

GetHeader returns value from request headers.

func (*Context) GetPostForm ΒΆ

func (c *Context) GetPostForm(key string) (string, bool)

GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded form or multipart form when it exists `(value, true)` (even when the value is an empty string), otherwise it returns ("", false).

func (*Context) GetPostFormArray ΒΆ

func (c *Context) GetPostFormArray(key string) (values []string, ok bool)

GetPostFormArray returns a slice of strings for a given form key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetQuery ΒΆ

func (c *Context) GetQuery(key string) (string, bool)

GetQuery is like Query(), it returns the keyed url query value if it exists `(value, true)` (even when the value is an empty string), otherwise it returns `("", false)`.

func (*Context) GetQueryArray ΒΆ

func (c *Context) GetQueryArray(key string) (values []string, ok bool)

GetQueryArray returns a slice of strings for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetRawData ΒΆ

func (c *Context) GetRawData() ([]byte, error)

GetRawData returns stream data.

func (*Context) HTML ΒΆ

func (c *Context) HTML(code int, name string, obj interface{})

HTML renders the HTTP template specified by its file name

func (*Context) Header ΒΆ

func (c *Context) Header(key, value string)

Header is a intelligent shortcut for c.Writer.Header().Set(key, value). It writes a header in the response. If value == "", this method removes the header `c.Writer.Header().Del(key)`

func (*Context) IndentedJSON ΒΆ

func (c *Context) IndentedJSON(code int, obj interface{})

IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body It also sets the Content-Type as "application/json" WARNING: use this only for development purposes since printing pretty JSON is more CPU and bandwidth consuming. Use Context.JSON() instead.

func (*Context) IsAborted ΒΆ

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) JSON ΒΆ

func (c *Context) JSON(code int, obj any)

JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".

func (*Context) JSONP ΒΆ

func (c *Context) JSONP(code int, obj interface{})

JSONP serializes the given struct as JSON into the response body It adds padding to response body to request data from a server residing in a different domain than the client It also sets the Content-Type as "application/javascript"

func (*Context) MultipartForm ΒΆ

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm is a helper to access multipart form data

func (*Context) MustBindWith ΒΆ

func (c *Context) MustBindWith(obj interface{}, b Binding) error

MustBindWith binds the request body into obj using the specified binding engine

func (*Context) MustGet ΒΆ

func (c *Context) MustGet(key string) any

MustGet returns the value for the given key if it exists, otherwise it panics.

func (*Context) Negotiate ΒΆ

func (c *Context) Negotiate(code int, config Negotiate)

Negotiate chooses the best format to render based on Accept header

func (*Context) NegotiateFormat ΒΆ

func (c *Context) NegotiateFormat(offered ...string) string

NegotiateFormat returns an acceptable format from the Accept header

func (*Context) Next ΒΆ

func (c *Context) Next()

Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler.

func (*Context) Param ΒΆ

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

Param returns the value of the URL param. It is a shortcut for c.Params.ByName(key)

router.GET("/user/:id", func(c *goTap.Context) {
    // a GET request to /user/john
    id := c.Param("id") // id == "john"
})

func (*Context) PostForm ΒΆ

func (c *Context) PostForm(key string) (value string)

PostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns an empty string `("")`.

func (*Context) PostFormArray ΒΆ

func (c *Context) PostFormArray(key string) (values []string)

PostFormArray returns a slice of strings for a given form key.

func (*Context) PureJSON ΒΆ

func (c *Context) PureJSON(code int, obj interface{})

PureJSON serializes the given struct as JSON into the response body PureJSON, unlike JSON, does not replace special html characters with their unicode entities

func (*Context) Query ΒΆ

func (c *Context) Query(key string) (value string)

Query returns the keyed url query value if it exists, otherwise it returns an empty string `("")`. It is shortcut for `c.Request.URL.Query().Get(key)`

GET /path?id=1234&name=Manu
c.Query("id") == "1234"
c.Query("name") == "Manu"
c.Query("value") == ""

func (*Context) QueryArray ΒΆ

func (c *Context) QueryArray(key string) (values []string)

QueryArray returns a slice of strings for a given query key.

func (*Context) Redirect ΒΆ

func (c *Context) Redirect(code int, location string)

Redirect returns an HTTP redirect to the specific location.

func (*Context) Render ΒΆ

func (c *Context) Render(code int, r interface{})

Render writes a response using the provided renderer

func (*Context) SSE ΒΆ

func (c *Context) SSE(event string, data interface{})

SSE writes Server-Sent Events into the response stream

func (*Context) SaveUploadedFile ΒΆ

func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error

SaveUploadedFile uploads the form file to specific dst

func (*Context) SecureJSON ΒΆ

func (c *Context) SecureJSON(code int, obj interface{})

SecureJSON serializes the given struct as Secure JSON into the response body Default prepends "while(1)," to response body if the given struct is array values It also sets the Content-Type as "application/json"

func (*Context) SecureJSONWithPrefix ΒΆ

func (c *Context) SecureJSONWithPrefix(code int, prefix string, obj interface{})

SecureJSONWithPrefix serializes the given struct as Secure JSON with custom prefix

func (*Context) Set ΒΆ

func (c *Context) Set(key string, value any)

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 (*Context) SetCookie ΒΆ

func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie adds a Set-Cookie header to the ResponseWriter's headers.

func (*Context) ShouldBind ΒΆ

func (c *Context) ShouldBind(obj interface{}) error

ShouldBind checks the Content-Type to select a binding engine automatically

func (*Context) ShouldBindBodyWith ΒΆ

func (c *Context) ShouldBindBodyWith(obj interface{}, bb BindingBody) (err error)

ShouldBindBodyWith is similar to ShouldBindWith but it stores the request body into the context and reuses when called again

func (*Context) ShouldBindHeader ΒΆ

func (c *Context) ShouldBindHeader(obj interface{}) error

ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header)

func (*Context) ShouldBindJSON ΒΆ

func (c *Context) ShouldBindJSON(obj interface{}) error

ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON)

func (*Context) ShouldBindQuery ΒΆ

func (c *Context) ShouldBindQuery(obj interface{}) error

ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query)

func (*Context) ShouldBindUri ΒΆ

func (c *Context) ShouldBindUri(obj interface{}) error

ShouldBindUri binds the passed struct pointer using the URI parameters

func (*Context) ShouldBindWith ΒΆ

func (c *Context) ShouldBindWith(obj interface{}, b Binding) error

ShouldBindWith binds the request body into obj using the specified binding engine

func (*Context) ShouldBindXML ΒΆ

func (c *Context) ShouldBindXML(obj interface{}) error

ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML)

func (*Context) Status ΒΆ

func (c *Context) Status(code int)

Status sets the HTTP response code.

func (*Context) Stream ΒΆ

func (c *Context) Stream(step func(w http.ResponseWriter) bool) bool

Stream sends a streaming response and returns a boolean indicating "Is client disconnected?"

func (*Context) String ΒΆ

func (c *Context) String(code int, format string, values ...any)

String writes the given string into the response body.

func (*Context) Value ΒΆ

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

Value returns the value associated with this context for key.

func (*Context) WebSocket ΒΆ

func (c *Context) WebSocket(handler WebSocketHandler)

WebSocket upgrades the HTTP connection to WebSocket and handles it

func (*Context) WebSocketWithConfig ΒΆ

func (c *Context) WebSocketWithConfig(config WebSocketConfig, handler WebSocketHandler)

WebSocketWithConfig upgrades with custom configuration

func (*Context) XML ΒΆ

func (c *Context) XML(code int, obj interface{})

XML serializes the given struct as XML into the response body

func (*Context) YAML ΒΆ

func (c *Context) YAML(code int, obj interface{})

YAML serializes the given struct as YAML into the response body

type DBConfig ΒΆ

type DBConfig struct {
	Driver          string        // "mysql", "postgres", "sqlite"
	DSN             string        // Data Source Name
	MaxIdleConns    int           // Maximum idle connections
	MaxOpenConns    int           // Maximum open connections
	ConnMaxLifetime time.Duration // Connection max lifetime
	LogLevel        logger.LogLevel
}

DBConfig holds database configuration

func DefaultDBConfig ΒΆ

func DefaultDBConfig() *DBConfig

DefaultDBConfig returns default database configuration

type DefaultValidator ΒΆ

type DefaultValidator struct{}

DefaultValidator is a simple built-in validator using struct tags

func (*DefaultValidator) Engine ΒΆ

func (v *DefaultValidator) Engine() interface{}

Engine returns the underlying validation engine

func (*DefaultValidator) ValidateStruct ΒΆ

func (v *DefaultValidator) ValidateStruct(obj interface{}) error

ValidateStruct validates a struct based on "validate" tags

type Delims ΒΆ

type Delims struct {
	Left  string
	Right string
}

Delims represents template delimiters

type Engine ΒΆ

type Engine struct {
	RouterGroup

	// Router configuration
	RedirectTrailingSlash  bool
	RedirectFixedPath      bool
	HandleMethodNotAllowed bool
	ForwardedByClientIP    bool
	UseRawPath             bool
	UnescapePathValues     bool
	RemoveExtraSlash       bool

	FuncMap template.FuncMap

	MaxMultipartMemory int64
	// contains filtered or unexported fields
}

Engine is the framework's instance, it contains the muxer, middleware and configuration settings. Create an instance of Engine, by using New() or Default()

func Default ΒΆ

func Default() *Engine

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

func New ΒΆ

func New() *Engine

New returns a new blank Engine instance without any middleware attached. By default, the configuration is: - RedirectTrailingSlash: true - RedirectFixedPath: false - HandleMethodNotAllowed: false - ForwardedByClientIP: true - UseRawPath: false - UnescapePathValues: true

func (*Engine) LoadHTMLFiles ΒΆ

func (engine *Engine) LoadHTMLFiles(files ...string)

LoadHTMLFiles loads HTML templates from specific files

func (*Engine) LoadHTMLGlob ΒΆ

func (engine *Engine) LoadHTMLGlob(pattern string)

LoadHTMLGlob loads HTML templates from a glob pattern

func (*Engine) NoMethod ΒΆ

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

NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true.

func (*Engine) NoRoute ΒΆ

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

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

func (*Engine) Routes ΒΆ

func (engine *Engine) Routes() (routes RoutesInfo)

Routes returns a slice of registered routes, including some useful information, such as: the http method, path, and the handler name.

func (*Engine) Run ΒΆ

func (engine *Engine) Run(addr ...string) (err error)

Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) RunServer ΒΆ

func (engine *Engine) RunServer(addr ...string) *http.Server

RunServer attaches the router to a http.Server and starts listening and serving HTTP requests. This method returns the http.Server instance for advanced configuration and graceful shutdown. Example:

srv := router.RunServer(":5066")
// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
// Shutdown gracefully
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(ctx)

func (*Engine) RunTLS ΒΆ

func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error)

RunTLS attaches the router to a http.Server and starts listening and serving HTTPS requests. It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) SecureJSONPrefix ΒΆ

func (engine *Engine) SecureJSONPrefix(prefix string)

SecureJSONPrefix sets the prefix for SecureJSON rendering Default prefix is "while(1);"

func (*Engine) ServeHTTP ΒΆ

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

ServeHTTP conforms to the http.Handler interface.

func (*Engine) SetHTMLTemplate ΒΆ

func (engine *Engine) SetHTMLTemplate(templ *template.Template)

SetHTMLTemplate sets a custom HTML template

func (*Engine) Use ΒΆ

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

Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be included in the handlers chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.

type Error ΒΆ

type Error struct {
	Err  error
	Type ErrorType
	Meta any
}

Error represents a error's specification.

func (*Error) Error ΒΆ

func (msg *Error) Error() string

Error implements the error interface.

func (*Error) IsType ΒΆ

func (msg *Error) IsType(flags ErrorType) bool

IsType judges one error.

func (*Error) JSON ΒΆ

func (msg *Error) JSON() any

JSON creates a properly formatted JSON

func (*Error) SetMeta ΒΆ

func (msg *Error) SetMeta(data any) *Error

SetMeta sets the error's meta data.

func (*Error) SetType ΒΆ

func (msg *Error) SetType(flags ErrorType) *Error

SetType sets the error's type.

func (*Error) Unwrap ΒΆ

func (msg *Error) Unwrap() error

Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap()

type ErrorType ΒΆ

type ErrorType uint64

ErrorType is an unsigned 64-bit error code as defined in the goTap spec.

const (
	// ErrorTypeBind is used when Context.Bind() fails.
	ErrorTypeBind ErrorType = 1 << 63
	// ErrorTypeRender is used when Context.Render() fails.
	ErrorTypeRender ErrorType = 1 << 62
	// ErrorTypePrivate indicates a private error.
	ErrorTypePrivate ErrorType = 1 << 0
	// ErrorTypePublic indicates a public error.
	ErrorTypePublic ErrorType = 1 << 1
	// ErrorTypeAny indicates any other error.
	ErrorTypeAny ErrorType = 1<<64 - 1
)

type GormCache ΒΆ

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

GormCache is a simple caching helper for GORM queries

func NewGormCache ΒΆ

func NewGormCache() *GormCache

NewGormCache creates a new cache instance

func (*GormCache) Clear ΒΆ

func (gc *GormCache) Clear()

Clear clears all cache

func (*GormCache) Delete ΒΆ

func (gc *GormCache) Delete(key string)

Delete removes value from cache

func (*GormCache) Get ΒΆ

func (gc *GormCache) Get(key string) (interface{}, bool)

Get retrieves value from cache

func (*GormCache) Set ΒΆ

func (gc *GormCache) Set(key string, value interface{})

Set stores value in cache

type GormPagination ΒΆ

type GormPagination struct {
	Page     int `form:"page" json:"page"`
	PageSize int `form:"page_size" json:"page_size"`
}

GormPagination helper for pagination

func NewGormPagination ΒΆ

func NewGormPagination(c *Context) *GormPagination

NewGormPagination creates a new pagination instance from request

func (*GormPagination) Apply ΒΆ

func (p *GormPagination) Apply(db *gorm.DB) *gorm.DB

Apply applies pagination to GORM query

func (*GormPagination) Limit ΒΆ

func (p *GormPagination) Limit() int

Limit returns the page size

func (*GormPagination) Offset ΒΆ

func (p *GormPagination) Offset() int

Offset calculates the offset for the query

type GormSoftDelete ΒΆ

type GormSoftDelete struct {
	DeletedAt *time.Time `gorm:"index" json:"deleted_at,omitempty"`
}

GormSoftDelete enables soft delete for all queries

type GzipConfig ΒΆ

type GzipConfig struct {
	// Level of compression (0-9, where 9 is best compression)
	// Default: gzip.DefaultCompression (-1)
	Level int

	// MinLength is minimum response size to compress (bytes)
	// Responses smaller than this won't be compressed
	// Default: 1024 (1KB)
	MinLength int

	// ExcludedExtensions is a list of file extensions that shouldn't be compressed
	// Example: []string{".png", ".jpg", ".jpeg", ".gif", ".zip"}
	ExcludedExtensions []string

	// ExcludedPaths is a list of paths that shouldn't be compressed
	// Example: []string{"/api/download", "/images"}
	ExcludedPaths []string

	// ExcludedPathsRegexs is a list of regex patterns for paths to exclude
	// More flexible than ExcludedPaths but slower
	ExcludedPathsRegexs []string
}

GzipConfig defines configuration for Gzip middleware

func DefaultGzipConfig ΒΆ

func DefaultGzipConfig() GzipConfig

DefaultGzipConfig returns a default Gzip configuration

type H ΒΆ

type H map[string]any

H is a shortcut for map[string]any

type HandlerFunc ΒΆ

type HandlerFunc func(*Context)

HandlerFunc defines the handler used by goTap middleware as return value.

func BasicAuth ΒΆ

func BasicAuth(accounts Accounts) HandlerFunc

BasicAuth returns a Basic HTTP Authorization middleware It takes a map[string]string where the key is the username and the value is the password, as well as the name of the Realm. If the realm is empty string, "Authorization Required" will be used by default.

func BasicAuthForRealm ΒΆ

func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc

BasicAuthForRealm returns a Basic HTTP Authorization middleware It takes a map[string]string where the key is the username and the value is the password, as well as the name of the Realm.

func BurstRateLimiter ΒΆ

func BurstRateLimiter(maxBurst int, refillRate float64) HandlerFunc

BurstRateLimiter creates a rate limiter that allows bursts maxBurst: maximum burst size refillRate: tokens refilled per second

func CORS ΒΆ

func CORS() HandlerFunc

CORS returns a middleware that adds CORS headers to responses

func CORSWithConfig ΒΆ

func CORSWithConfig(config CORSConfig) HandlerFunc

CORSWithConfig returns a CORS middleware with custom config

func CombinedIPFilter ΒΆ

func CombinedIPFilter(whitelist, blacklist []string) HandlerFunc

CombinedIPFilter combines whitelist and blacklist Blacklist is checked first, then whitelist

func CustomRecoveryWithWriter ΒΆ

func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc

CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.

func DBHealthCheck ΒΆ

func DBHealthCheck() HandlerFunc

DBHealthCheck returns a middleware that checks database health

func GormHealthCheck ΒΆ

func GormHealthCheck() HandlerFunc

GormHealthCheck middleware for health check endpoint

func GormInject ΒΆ

func GormInject(db *gorm.DB) HandlerFunc

GormInject injects GORM database instance into context

func GormLogger ΒΆ

func GormLogger() HandlerFunc

GormLogger middleware logs all database operations

func GormTransaction ΒΆ

func GormTransaction() HandlerFunc

GormTransaction wraps the handler in a database transaction

func Gzip ΒΆ

func Gzip() HandlerFunc

Gzip returns a middleware that compresses HTTP responses using Gzip compression It uses default configuration which compresses responses larger than 1KB

func GzipWithConfig ΒΆ

func GzipWithConfig(config GzipConfig) HandlerFunc

GzipWithConfig returns a Gzip middleware with custom configuration

func IPBlacklist ΒΆ

func IPBlacklist(blockedIPs ...string) HandlerFunc

IPBlacklist returns an IP blacklist middleware

func IPBlacklistWithConfig ΒΆ

func IPBlacklistWithConfig(config IPBlacklistConfig) HandlerFunc

IPBlacklistWithConfig returns an IP blacklist middleware with config

func IPWhitelist ΒΆ

func IPWhitelist(allowedIPs ...string) HandlerFunc

IPWhitelist returns an IP whitelist middleware

func IPWhitelistWithConfig ΒΆ

func IPWhitelistWithConfig(config IPWhitelistConfig) HandlerFunc

IPWhitelistWithConfig returns an IP whitelist middleware with config

func JWTAuth ΒΆ

func JWTAuth(secret string) HandlerFunc

JWTAuth returns a JWT authentication middleware

func JWTAuthWithConfig ΒΆ

func JWTAuthWithConfig(config JWTConfig) HandlerFunc

JWTAuthWithConfig returns a JWT authentication middleware with config

func Logger ΒΆ

func Logger() HandlerFunc

Logger instances a Logger middleware that will write the logs to goTap.DefaultWriter. By default, goTap.DefaultWriter = os.Stdout.

func LoggerWithConfig ΒΆ

func LoggerWithConfig(conf LoggerConfig) HandlerFunc

LoggerWithConfig instance a Logger middleware with config.

func MongoHealthCheck ΒΆ

func MongoHealthCheck(client *MongoClient) HandlerFunc

MongoHealthCheck returns middleware that checks MongoDB health

func MongoInject ΒΆ

func MongoInject(client *MongoClient) HandlerFunc

MongoInject injects MongoDB client into context for use in handlers

func MongoLogger ΒΆ

func MongoLogger() HandlerFunc

MongoLogger middleware logs all MongoDB operations

func MongoTransaction ΒΆ

func MongoTransaction(client *MongoClient) HandlerFunc

MongoTransaction wraps a handler in a MongoDB transaction

func RateLimiter ΒΆ

func RateLimiter(max int, window time.Duration) HandlerFunc

RateLimiter returns a rate limiter middleware max: maximum requests allowed window: time window duration

func RateLimiterByAPIKey ΒΆ

func RateLimiterByAPIKey(max int, window time.Duration, headerName string) HandlerFunc

RateLimiterByAPIKey returns a rate limiter that uses API key as key

func RateLimiterByPath ΒΆ

func RateLimiterByPath(max int, window time.Duration) HandlerFunc

RateLimiterByPath returns a rate limiter that uses request path as part of the key

func RateLimiterByUser ΒΆ

func RateLimiterByUser(max int, window time.Duration) HandlerFunc

RateLimiterByUser returns a rate limiter that uses user ID as key Requires JWT middleware to be used before this middleware

func RateLimiterWithConfig ΒΆ

func RateLimiterWithConfig(config RateLimiterConfig) HandlerFunc

RateLimiterWithConfig returns a rate limiter middleware with config

func Recovery ΒΆ

func Recovery() HandlerFunc

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

func RecoveryWithWriter ΒΆ

func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc

RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.

func RedisCache ΒΆ

func RedisCache(config RedisCacheConfig) HandlerFunc

RedisCache returns a middleware that caches GET requests in Redis

func RedisHealthCheck ΒΆ

func RedisHealthCheck(client *RedisClient) HandlerFunc

RedisHealthCheck returns middleware that checks Redis health

func RedisInject ΒΆ

func RedisInject(client *RedisClient) HandlerFunc

RedisInject injects Redis client into context for use in handlers

func RedisSession ΒΆ

func RedisSession(config RedisSessionConfig) HandlerFunc

RedisSession returns middleware for Redis-backed session management

func RequireAnyRole ΒΆ

func RequireAnyRole(roles ...string) HandlerFunc

RequireAnyRole returns a middleware that checks if the user has any of the required roles

func RequireHealthyDB ΒΆ

func RequireHealthyDB() HandlerFunc

RequireHealthyDB returns a middleware that requires a healthy database

func RequireRole ΒΆ

func RequireRole(requiredRole string) HandlerFunc

RequireRole returns a middleware that checks if the user has the required role

func ShadowDBMiddleware ΒΆ

func ShadowDBMiddleware(sdb *shadowdb.ShadowDB) HandlerFunc

ShadowDBMiddleware returns a middleware that injects Shadow DB into context

func SwaggerHandler ΒΆ

func SwaggerHandler(config *SwaggerConfig) HandlerFunc

SwaggerHandler returns a handler that serves Swagger UI It wraps gin-swagger to work with goTap's Context

func SwaggerJSON ΒΆ

func SwaggerJSON(jsonData []byte) HandlerFunc

SwaggerJSON serves the swagger.json file

func SwaggerYAML ΒΆ

func SwaggerYAML(yamlData []byte) HandlerFunc

SwaggerYAML serves the swagger.yaml file

func TransactionID ΒΆ

func TransactionID() HandlerFunc

TransactionID returns a middleware that generates unique transaction IDs for each request

func TransactionIDWithConfig ΒΆ

func TransactionIDWithConfig(config TransactionIDConfig) HandlerFunc

TransactionIDWithConfig returns a TransactionID middleware with config

func VectorDeleteHandler ΒΆ

func VectorDeleteHandler() HandlerFunc

VectorDeleteHandler creates a handler for deleting vectors

func VectorGetHandler ΒΆ

func VectorGetHandler() HandlerFunc

VectorGetHandler creates a handler for getting a vector by ID

func VectorInject ΒΆ

func VectorInject(store VectorStore) HandlerFunc

VectorInject injects vector store into context for use in handlers

func VectorInsertHandler ΒΆ

func VectorInsertHandler() HandlerFunc

VectorInsertHandler creates a handler for inserting vectors

func VectorLogger ΒΆ

func VectorLogger() HandlerFunc

VectorLogger logs vector operations

func VectorSearchHandler ΒΆ

func VectorSearchHandler() HandlerFunc

VectorSearchHandler creates a handler for vector search

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 IPBlacklistConfig ΒΆ

type IPBlacklistConfig struct {
	// BlockedIPs is a list of blocked IP addresses or CIDR ranges
	BlockedIPs []string

	// TrustedProxies is a list of trusted proxy IPs
	TrustedProxies []string

	// ErrorHandler is called when IP is blacklisted
	ErrorHandler func(*Context)

	// UseXForwardedFor determines if X-Forwarded-For header should be checked
	UseXForwardedFor bool

	// UseXRealIP determines if X-Real-IP header should be checked
	UseXRealIP bool
}

IPBlacklistConfig holds IP blacklist configuration

type IPWhitelistConfig ΒΆ

type IPWhitelistConfig struct {
	// AllowedIPs is a list of allowed IP addresses or CIDR ranges
	AllowedIPs []string

	// TrustedProxies is a list of trusted proxy IPs
	// When set, the middleware will look at X-Forwarded-For or X-Real-IP headers
	TrustedProxies []string

	// ErrorHandler is called when IP is not whitelisted
	ErrorHandler func(*Context)

	// UseXForwardedFor determines if X-Forwarded-For header should be checked
	// Only works if request comes from a trusted proxy
	UseXForwardedFor bool

	// UseXRealIP determines if X-Real-IP header should be checked
	// Only works if request comes from a trusted proxy
	UseXRealIP bool
}

IPWhitelistConfig holds IP whitelist configuration

type IRouter ΒΆ

type IRouter interface {
	IRoutes
	Group(string, ...HandlerFunc) *RouterGroup
}

IRouter defines all router handle interface includes single and group router.

type IRoutes ΒΆ

type IRoutes interface {
	Use(...HandlerFunc) IRoutes

	Handle(string, string, ...HandlerFunc) IRoutes
	Any(string, ...HandlerFunc) IRoutes
	GET(string, ...HandlerFunc) IRoutes
	POST(string, ...HandlerFunc) IRoutes
	DELETE(string, ...HandlerFunc) IRoutes
	PATCH(string, ...HandlerFunc) IRoutes
	PUT(string, ...HandlerFunc) IRoutes
	OPTIONS(string, ...HandlerFunc) IRoutes
	HEAD(string, ...HandlerFunc) IRoutes

	StaticFile(string, string) IRoutes
	StaticFS(string, http.FileSystem) IRoutes
	Static(string, string) IRoutes
}

IRoutes defines all router handle interface.

type InMemoryVectorStore ΒΆ

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

InMemoryVectorStore implements VectorStore in memory (for testing/demo)

func NewInMemoryVectorStore ΒΆ

func NewInMemoryVectorStore() *InMemoryVectorStore

NewInMemoryVectorStore creates a new in-memory vector store

func (*InMemoryVectorStore) Delete ΒΆ

func (s *InMemoryVectorStore) Delete(ctx context.Context, ids []string) error

Delete removes vectors by ID

func (*InMemoryVectorStore) Get ΒΆ

Get retrieves a vector by ID

func (*InMemoryVectorStore) Insert ΒΆ

func (s *InMemoryVectorStore) Insert(ctx context.Context, documents []*VectorDocument) error

Insert adds vectors to the store

func (*InMemoryVectorStore) Search ΒΆ

func (s *InMemoryVectorStore) Search(ctx context.Context, queryVector Vector, limit int) ([]*VectorSearchResult, error)

Search performs similarity search using cosine similarity

func (*InMemoryVectorStore) Update ΒΆ

func (s *InMemoryVectorStore) Update(ctx context.Context, document *VectorDocument) error

Update updates a vector

type JWTClaims ΒΆ

type JWTClaims struct {
	UserID    string                 `json:"user_id,omitempty"`
	Username  string                 `json:"username,omitempty"`
	Email     string                 `json:"email,omitempty"`
	Role      string                 `json:"role,omitempty"`
	ExpiresAt int64                  `json:"exp"`
	IssuedAt  int64                  `json:"iat"`
	Issuer    string                 `json:"iss,omitempty"`
	Subject   string                 `json:"sub,omitempty"`
	Custom    map[string]interface{} `json:"custom,omitempty"`
}

JWTClaims represents the claims in a JWT token

func GetJWTClaims ΒΆ

func GetJWTClaims(c *Context) (*JWTClaims, bool)

GetJWTClaims retrieves JWT claims from context

type JWTConfig ΒΆ

type JWTConfig struct {
	// Secret key for signing tokens
	Secret string

	// TokenLookup is a string in the form of "<source>:<name>" that is used
	// to extract token from the request.
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	// - "cookie:<name>"
	TokenLookup string

	// TokenHeadName is a string in the header. Default value is "Bearer"
	TokenHeadName string

	// TimeFunc provides the current time. You can override it for testing.
	TimeFunc func() time.Time

	// ErrorHandler defines a function which is executed when an error occurs.
	ErrorHandler func(*Context, error)

	// SuccessHandler defines a function which is executed after successful token validation.
	SuccessHandler func(*Context, *JWTClaims)
}

JWTConfig holds JWT middleware configuration

type LogFormatterParams ΒΆ

type LogFormatterParams struct {
	Request *http.Request

	// TimeStamp shows the time after the server returns a response.
	TimeStamp time.Time
	// StatusCode is HTTP response code.
	StatusCode int
	// Latency is how much time the server cost to process a certain request.
	Latency time.Duration
	// ClientIP equals Context's ClientIP method.
	ClientIP string
	// Method is the HTTP method given to the request.
	Method string
	// Path is a path the client requests.
	Path string
	// ErrorMessage is set if error has occurred in processing the request.
	ErrorMessage string
	// BodySize is the size of the Response Body
	BodySize int
	// Keys are the keys set on the request's context.
	Keys map[string]any
}

LogFormatterParams is the structure any formatter will be handed when time to log comes

func (*LogFormatterParams) MethodColor ΒΆ

func (p *LogFormatterParams) MethodColor() string

MethodColor is the ANSI color for appropriately logging http method to a terminal.

func (*LogFormatterParams) ResetColor ΒΆ

func (p *LogFormatterParams) ResetColor() string

ResetColor resets all escape attributes.

func (*LogFormatterParams) StatusCodeColor ΒΆ

func (p *LogFormatterParams) StatusCodeColor() string

StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.

type LoggerConfig ΒΆ

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

	// Output is a writer where logs are written.
	// Optional. Default value is goTap.DefaultWriter.
	Output io.Writer
}

LoggerConfig defines the config for Logger middleware.

type MongoAuditLog ΒΆ

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

MongoAuditLog middleware logs all requests to MongoDB

func NewMongoAuditLog ΒΆ

func NewMongoAuditLog(client *MongoClient, collectionName string, includeBody bool) *MongoAuditLog

NewMongoAuditLog creates a new audit log middleware

func (*MongoAuditLog) Middleware ΒΆ

func (mal *MongoAuditLog) Middleware() HandlerFunc

Middleware returns the audit log middleware

type MongoCache ΒΆ

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

MongoCache provides a simple cache layer using MongoDB

func NewMongoCache ΒΆ

func NewMongoCache(client *MongoClient, collectionName string, ttl time.Duration) *MongoCache

NewMongoCache creates a new MongoDB-based cache

func (*MongoCache) Clear ΒΆ

func (mc *MongoCache) Clear(ctx context.Context) error

Clear removes all cache entries

func (*MongoCache) Delete ΒΆ

func (mc *MongoCache) Delete(ctx context.Context, key string) error

Delete removes a value from cache

func (*MongoCache) Get ΒΆ

func (mc *MongoCache) Get(ctx context.Context, key string) (interface{}, error)

Get retrieves a value from cache

func (*MongoCache) Set ΒΆ

func (mc *MongoCache) Set(ctx context.Context, key string, value interface{}) error

Set stores a value in cache

type MongoClient ΒΆ

type MongoClient struct {
	Client   *mongo.Client
	Database *mongo.Database
	// contains filtered or unexported fields
}

MongoClient wraps mongo.Client for middleware use

func GetMongo ΒΆ

func GetMongo(c *Context) (*MongoClient, bool)

GetMongo retrieves MongoDB client from context

func MustGetMongo ΒΆ

func MustGetMongo(c *Context) *MongoClient

MustGetMongo retrieves MongoDB client from context or panics

func NewMongoClient ΒΆ

func NewMongoClient(uri, database string) (*MongoClient, error)

NewMongoClient creates a new MongoDB client wrapper

func (*MongoClient) Close ΒΆ

func (m *MongoClient) Close() error

Close closes the MongoDB connection

func (*MongoClient) Collection ΒΆ

func (m *MongoClient) Collection(name string) *mongo.Collection

Collection returns a collection from the database

type MongoPagination ΒΆ

type MongoPagination struct {
	Page     int64
	PageSize int64
	Total    int64
	Pages    int64
}

MongoPagination provides pagination helper

func NewMongoPagination ΒΆ

func NewMongoPagination(c *Context) *MongoPagination

NewMongoPagination creates pagination from context query params

func (*MongoPagination) FindOptions ΒΆ

func (p *MongoPagination) FindOptions() *options.FindOptions

FindOptions returns MongoDB find options with pagination

func (*MongoPagination) Response ΒΆ

func (p *MongoPagination) Response() H

Response returns pagination metadata for API response

func (*MongoPagination) SetTotal ΒΆ

func (p *MongoPagination) SetTotal(total int64)

SetTotal sets the total count and calculates pages

func (*MongoPagination) Skip ΒΆ

func (p *MongoPagination) Skip() int64

Skip returns the number of documents to skip

type MongoRepository ΒΆ

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

MongoRepository provides common database operations

func NewMongoRepository ΒΆ

func NewMongoRepository(client *MongoClient, collectionName string) *MongoRepository

NewMongoRepository creates a new repository for a collection

func (*MongoRepository) Aggregate ΒΆ

func (r *MongoRepository) Aggregate(ctx context.Context, pipeline interface{}) (*mongo.Cursor, error)

Aggregate performs aggregation pipeline

func (*MongoRepository) CountDocuments ΒΆ

func (r *MongoRepository) CountDocuments(ctx context.Context, filter interface{}) (int64, error)

CountDocuments counts documents matching filter

func (*MongoRepository) CreateIndex ΒΆ

func (r *MongoRepository) CreateIndex(ctx context.Context, keys interface{}, unique bool) (string, error)

CreateIndex creates an index on the collection

func (*MongoRepository) DeleteByID ΒΆ

func (r *MongoRepository) DeleteByID(ctx context.Context, id interface{}) (*mongo.DeleteResult, error)

DeleteByID deletes a document by ID

func (*MongoRepository) DeleteOne ΒΆ

func (r *MongoRepository) DeleteOne(ctx context.Context, filter interface{}) (*mongo.DeleteResult, error)

DeleteOne deletes a single document

func (*MongoRepository) Find ΒΆ

func (r *MongoRepository) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*mongo.Cursor, error)

Find finds multiple documents by filter

func (*MongoRepository) FindByID ΒΆ

func (r *MongoRepository) FindByID(ctx context.Context, id interface{}) *mongo.SingleResult

FindByID finds a document by ID

func (*MongoRepository) FindOne ΒΆ

func (r *MongoRepository) FindOne(ctx context.Context, filter interface{}) (*mongo.SingleResult, error)

FindOne finds a single document by filter

func (*MongoRepository) InsertMany ΒΆ

func (r *MongoRepository) InsertMany(ctx context.Context, documents []interface{}) (*mongo.InsertManyResult, error)

InsertMany inserts multiple documents

func (*MongoRepository) InsertOne ΒΆ

func (r *MongoRepository) InsertOne(ctx context.Context, document interface{}) (*mongo.InsertOneResult, error)

InsertOne inserts a single document

func (*MongoRepository) UpdateByID ΒΆ

func (r *MongoRepository) UpdateByID(ctx context.Context, id interface{}, update interface{}) (*mongo.UpdateResult, error)

UpdateByID updates a document by ID

func (*MongoRepository) UpdateOne ΒΆ

func (r *MongoRepository) UpdateOne(ctx context.Context, filter interface{}, update interface{}) (*mongo.UpdateResult, error)

UpdateOne updates a single document

type MongoTextSearch ΒΆ

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

MongoTextSearch provides full-text search functionality

func NewMongoTextSearch ΒΆ

func NewMongoTextSearch(client *MongoClient, collectionName string) *MongoTextSearch

NewMongoTextSearch creates a new text search instance

func (*MongoTextSearch) CreateTextIndex ΒΆ

func (mts *MongoTextSearch) CreateTextIndex(ctx context.Context, fields ...string) error

CreateTextIndex creates a text index on specified fields

func (*MongoTextSearch) Search ΒΆ

func (mts *MongoTextSearch) Search(ctx context.Context, query string, opts ...*options.FindOptions) (*mongo.Cursor, error)

Search performs a text search

type Negotiate ΒΆ

type Negotiate struct {
	Offered  []string
	HTMLName string
	HTMLData interface{}
	JSONData interface{}
	XMLData  interface{}
	YAMLData interface{}
	Data     interface{}
}

Negotiate contains all negotiations data

type Param ΒΆ

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params ΒΆ

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (Params) ByName ΒΆ

func (ps Params) ByName(name string) (va string)

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Get ΒΆ

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type ProductEmbedding ΒΆ

type ProductEmbedding struct {
	ProductID   string  `json:"product_id"`
	Name        string  `json:"name"`
	Description string  `json:"description"`
	Category    string  `json:"category"`
	Price       float64 `json:"price"`
	Vector      Vector  `json:"vector"`
}

ProductEmbedding represents a product with its vector embedding

type ProductRecommender ΒΆ

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

ProductRecommender provides product recommendations using vector similarity

func NewProductRecommender ΒΆ

func NewProductRecommender(store VectorStore) *ProductRecommender

NewProductRecommender creates a new product recommender

func (*ProductRecommender) AddProduct ΒΆ

func (pr *ProductRecommender) AddProduct(ctx context.Context, product *ProductEmbedding) error

AddProduct adds a product to the recommender

func (*ProductRecommender) GetSimilarProducts ΒΆ

func (pr *ProductRecommender) GetSimilarProducts(ctx context.Context, productID string, limit int) ([]*ProductEmbedding, error)

GetSimilarProducts finds products similar to the given product

type RateLimiterConfig ΒΆ

type RateLimiterConfig struct {
	// Max requests allowed in the time window
	Max int

	// Time window duration
	Window time.Duration

	// KeyFunc defines a function to generate the rate limiter key
	// Default: uses client IP
	KeyFunc func(*Context) string

	// ErrorHandler is called when rate limit is exceeded
	ErrorHandler func(*Context)

	// SkipFunc defines a function to skip rate limiting
	// Useful for whitelisting certain IPs or paths
	SkipFunc func(*Context) bool

	// Store is the storage backend for rate limit data
	// Default: in-memory store
	Store RateLimiterStore
}

RateLimiterConfig holds rate limiter configuration

type RateLimiterStore ΒΆ

type RateLimiterStore interface {
	// Increment increments the counter for the given key
	// Returns current count and expiration time
	Increment(key string, window time.Duration) (int, time.Time, error)

	// Reset resets the counter for the given key
	Reset(key string) error
}

RateLimiterStore defines the interface for rate limiter storage

type RecoveryFunc ΒΆ

type RecoveryFunc func(c *Context, err any)

RecoveryFunc defines the function passable to CustomRecovery.

type RedisCacheConfig ΒΆ

type RedisCacheConfig struct {
	// Redis client instance
	Client *RedisClient

	// TTL for cached responses (default: 5 minutes)
	TTL time.Duration

	// Key prefix for cache keys (default: "cache:")
	Prefix string

	// Skip cache for certain paths (e.g., ["/admin", "/api/auth"])
	SkipPaths []string

	// Only cache specific HTTP methods (default: ["GET"])
	CacheMethods []string

	// Custom key generator function (optional)
	KeyGenerator func(c *Context) string
}

RedisCacheConfig holds configuration for Redis caching middleware

type RedisClient ΒΆ

type RedisClient struct {
	Client *redis.Client
	// contains filtered or unexported fields
}

RedisClient wraps redis.Client for middleware use

func GetRedis ΒΆ

func GetRedis(c *Context) (*RedisClient, bool)

GetRedis retrieves Redis client from context

func MustGetRedis ΒΆ

func MustGetRedis(c *Context) *RedisClient

MustGetRedis retrieves Redis client from context or panics

func NewRedisClient ΒΆ

func NewRedisClient(addr, password string, db int) (*RedisClient, error)

NewRedisClient creates a new Redis client wrapper

func (*RedisClient) Close ΒΆ

func (r *RedisClient) Close() error

Close closes the Redis connection

type RedisPubSub ΒΆ

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

RedisPubSub provides pub/sub functionality for real-time updates

func NewRedisPubSub ΒΆ

func NewRedisPubSub(client *RedisClient, channels ...string) *RedisPubSub

NewRedisPubSub creates a new pub/sub instance

func (*RedisPubSub) Close ΒΆ

func (ps *RedisPubSub) Close() error

Close closes the pub/sub connection

func (*RedisPubSub) Publish ΒΆ

func (ps *RedisPubSub) Publish(channel, message string) error

Publish sends a message to a channel

func (*RedisPubSub) Receive ΒΆ

func (ps *RedisPubSub) Receive() <-chan *redis.Message

Receive returns the channel for receiving messages

type RedisSessionConfig ΒΆ

type RedisSessionConfig struct {
	// Redis client instance
	Client *RedisClient

	// Session TTL (default: 24 hours)
	TTL time.Duration

	// Cookie name (default: "session_id")
	CookieName string

	// Cookie path (default: "/")
	CookiePath string

	// Cookie domain (optional)
	CookieDomain string

	// Cookie secure flag (default: false)
	Secure bool

	// Cookie HttpOnly flag (default: true)
	HttpOnly bool
}

RedisSessionConfig holds configuration for Redis session management

type ResponseWriter ΒΆ

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher

	// Status returns the HTTP response status code of the current request.
	Status() int

	// Size returns the number of bytes already written into the response http body.
	// See Written()
	Size() int

	// WriteString writes the string into the response body.
	WriteString(string) (int, error)

	// Written returns true if the response body was already written.
	Written() bool

	// WriteHeaderNow forces to write the http header (status code + headers).
	WriteHeaderNow()
}

ResponseWriter ...

type RouteInfo ΒΆ

type RouteInfo struct {
	Method      string
	Path        string
	Handler     string
	HandlerFunc HandlerFunc
}

RouteInfo represents a request route's specification which contains method and path and its handler.

type RouterGroup ΒΆ

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

RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix and an array of handlers (middleware).

func (*RouterGroup) Any ΒΆ

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

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

func (*RouterGroup) BasePath ΒΆ

func (group *RouterGroup) BasePath() string

BasePath returns the base path of router group. For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api".

func (*RouterGroup) DELETE ΒΆ

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

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

func (*RouterGroup) GET ΒΆ

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

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

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) IRoutes

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

func (*RouterGroup) Handle ΒΆ

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

Handle registers a new request handle and middleware with the given path and method. The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*RouterGroup) OPTIONS ΒΆ

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

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

func (*RouterGroup) PATCH ΒΆ

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

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

func (*RouterGroup) POST ΒΆ

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

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

func (*RouterGroup) PUT ΒΆ

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

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

func (*RouterGroup) Static ΒΆ

func (group *RouterGroup) Static(relativePath, root string) IRoutes

Static serves files from the given file system root. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use:

router.Static("/static", "/var/www")

func (*RouterGroup) StaticFS ΒΆ

func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes

StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. Gin by default uses: goTap.Dir()

func (*RouterGroup) StaticFile ΒΆ

func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes

StaticFile registers a single route in order to serve a single file of the local filesystem. router.StaticFile("favicon.ico", "./resources/favicon.ico")

func (*RouterGroup) Use ΒΆ

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

Use adds middleware to the group

type RoutesInfo ΒΆ

type RoutesInfo []RouteInfo

RoutesInfo defines a RouteInfo slice.

type SSEvent ΒΆ

type SSEvent struct {
	Event string
	Data  interface{}
	ID    string
	Retry uint
}

SSEvent is a Server-Sent Event

func (SSEvent) Render ΒΆ

func (e SSEvent) Render(w http.ResponseWriter) error

Render renders a Server-Sent Event

type Session ΒΆ

type Session struct {
	ID   string
	Data map[string]string
	// contains filtered or unexported fields
}

Session represents a user session stored in Redis

func GetSession ΒΆ

func GetSession(c *Context) (*Session, bool)

GetSession retrieves session from context

func MustGetSession ΒΆ

func MustGetSession(c *Context) *Session

MustGetSession retrieves session from context or panics

func (*Session) Delete ΒΆ

func (s *Session) Delete(key string)

Delete removes a value from session

func (*Session) Destroy ΒΆ

func (s *Session) Destroy() error

Destroy removes session from Redis

func (*Session) Get ΒΆ

func (s *Session) Get(key string) (string, bool)

Get retrieves a value from session

func (*Session) Save ΒΆ

func (s *Session) Save() error

Save persists session data to Redis

func (*Session) Set ΒΆ

func (s *Session) Set(key, value string)

Set stores a value in session

type SwaggerConfig ΒΆ

type SwaggerConfig struct {
	// URL to swagger.json or swagger.yaml
	URL string
	// DocExpansion list, full, none
	DocExpansion string
	// DeepLinking enables deep linking for tags and operations
	DeepLinking bool
	// PersistAuthorization persists authorization data
	PersistAuthorization bool
	// DefaultModelsExpandDepth sets the default expansion depth for models
	DefaultModelsExpandDepth int
}

SwaggerConfig holds Swagger UI configuration

func DefaultSwaggerConfig ΒΆ

func DefaultSwaggerConfig() *SwaggerConfig

DefaultSwaggerConfig returns default Swagger configuration

type TransactionIDConfig ΒΆ

type TransactionIDConfig struct {
	// Generator defines a function to generate transaction IDs
	// Default: uses timestamp + random bytes + counter
	Generator func() string

	// HeaderName is the name of the header to set
	// Default: X-Transaction-ID
	HeaderName string

	// ContextKey is the key to store transaction ID in context
	// Default: transaction_id
	ContextKey string

	// IncludeInResponse determines if the transaction ID should be added to response headers
	// Default: true
	IncludeInResponse bool
}

TransactionIDConfig holds TransactionID middleware configuration

type Validator ΒΆ

type Validator interface {
	ValidateStruct(interface{}) error
	Engine() interface{}
}

Validator is the interface which needs to be implemented for validating request data

func GetValidator ΒΆ

func GetValidator() Validator

GetValidator returns the default validator

type Vector ΒΆ

type Vector []float32

Vector represents an embedding vector

func JSONToVector ΒΆ

func JSONToVector(jsonStr string) (Vector, error)

JSONToVector converts JSON string to vector

func Normalize ΒΆ

func Normalize(vector Vector) Vector

Normalize normalizes a vector to unit length

type VectorDocument ΒΆ

type VectorDocument struct {
	ID       string                 `json:"id"`
	Vector   Vector                 `json:"vector"`
	Metadata map[string]interface{} `json:"metadata"`
}

VectorDocument represents a document with vector embedding

type VectorMiddleware ΒΆ

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

VectorMiddleware provides common vector operations middleware

func NewVectorMiddleware ΒΆ

func NewVectorMiddleware(store VectorStore) *VectorMiddleware

NewVectorMiddleware creates a new vector middleware

func (*VectorMiddleware) SmartSearch ΒΆ

func (vm *VectorMiddleware) SmartSearch() HandlerFunc

SmartSearch middleware adds AI-powered search to endpoints

type VectorSearchRequest ΒΆ

type VectorSearchRequest struct {
	Vector   Vector                 `json:"vector" binding:"required"`
	Limit    int                    `json:"limit"`
	Filter   map[string]interface{} `json:"filter"`
	MinScore float32                `json:"min_score"`
}

VectorSearchRequest represents a search request

type VectorSearchResult ΒΆ

type VectorSearchResult struct {
	Document *VectorDocument `json:"document"`
	Score    float32         `json:"score"`
	Distance float32         `json:"distance"`
}

VectorSearchResult represents a search result with similarity score

type VectorStore ΒΆ

type VectorStore interface {
	// Insert adds vectors to the store
	Insert(ctx context.Context, documents []*VectorDocument) error

	// Search performs similarity search
	Search(ctx context.Context, queryVector Vector, limit int) ([]*VectorSearchResult, error)

	// Delete removes vectors by ID
	Delete(ctx context.Context, ids []string) error

	// Get retrieves a vector by ID
	Get(ctx context.Context, id string) (*VectorDocument, error)

	// Update updates a vector
	Update(ctx context.Context, document *VectorDocument) error
}

VectorStore interface for vector database operations

func GetVectorStore ΒΆ

func GetVectorStore(c *Context) (VectorStore, bool)

GetVectorStore retrieves vector store from context

func MustGetVectorStore ΒΆ

func MustGetVectorStore(c *Context) VectorStore

MustGetVectorStore retrieves vector store from context or panics

type WebSocketConfig ΒΆ

type WebSocketConfig struct {
	// ReadBufferSize specifies the size of the read buffer
	ReadBufferSize int

	// WriteBufferSize specifies the size of the write buffer
	WriteBufferSize int

	// HandshakeTimeout specifies the duration for the handshake to complete
	HandshakeTimeout time.Duration

	// CheckOrigin returns true if the request Origin header is acceptable
	CheckOrigin func(r *http.Request) bool

	// Error defines a function to handle errors
	Error func(c *Context, status int, err error)

	// Subprotocols specifies the server's supported protocols
	Subprotocols []string
}

WebSocketConfig holds WebSocket configuration

type WebSocketConn ΒΆ

type WebSocketConn struct {
	*websocket.Conn

	Context *Context
	// contains filtered or unexported fields
}

WebSocketConn wraps gorilla/websocket connection with additional features

func (*WebSocketConn) Close ΒΆ

func (ws *WebSocketConn) Close() error

Close closes the WebSocket connection

func (*WebSocketConn) IsClosed ΒΆ

func (ws *WebSocketConn) IsClosed() bool

IsClosed returns true if connection is closed

func (*WebSocketConn) ReadJSON ΒΆ

func (ws *WebSocketConn) ReadJSON(v interface{}) error

ReadJSON reads a JSON message

func (*WebSocketConn) ReadText ΒΆ

func (ws *WebSocketConn) ReadText() (string, error)

ReadText reads a text message

func (*WebSocketConn) Send ΒΆ

func (ws *WebSocketConn) Send(message []byte) error

Send sends a binary message

func (*WebSocketConn) SendJSON ΒΆ

func (ws *WebSocketConn) SendJSON(v interface{}) error

SendJSON sends a JSON message

func (*WebSocketConn) SendText ΒΆ

func (ws *WebSocketConn) SendText(message string) error

SendText sends a text message

func (*WebSocketConn) SetReadDeadline ΒΆ

func (ws *WebSocketConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline

func (*WebSocketConn) SetWriteDeadline ΒΆ

func (ws *WebSocketConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline

type WebSocketHandler ΒΆ

type WebSocketHandler func(*WebSocketConn)

WebSocketHandler defines the function signature for WebSocket handlers

type WebSocketHub ΒΆ

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

WebSocketHub manages WebSocket connections

func NewWebSocketHub ΒΆ

func NewWebSocketHub() *WebSocketHub

NewWebSocketHub creates a new WebSocket hub

func (*WebSocketHub) Broadcast ΒΆ

func (h *WebSocketHub) Broadcast(message []byte)

Broadcast sends a message to all clients

func (*WebSocketHub) BroadcastJSON ΒΆ

func (h *WebSocketHub) BroadcastJSON(v interface{})

BroadcastJSON sends a JSON message to all clients

func (*WebSocketHub) ClientCount ΒΆ

func (h *WebSocketHub) ClientCount() int

ClientCount returns the number of connected clients

func (*WebSocketHub) Clients ΒΆ

func (h *WebSocketHub) Clients() []*WebSocketConn

Clients returns all connected clients

func (*WebSocketHub) Close ΒΆ

func (h *WebSocketHub) Close()

Close closes all connections

func (*WebSocketHub) Register ΒΆ

func (h *WebSocketHub) Register(client *WebSocketConn)

Register registers a new client

func (*WebSocketHub) Unregister ΒΆ

func (h *WebSocketHub) Unregister(client *WebSocketConn)

Unregister unregisters a client

Directories ΒΆ

Path Synopsis
examples
auth command
basic command
binding command
json-rendering command
rendering command
security command
static command

Jump to

Keyboard shortcuts

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