Documentation
ΒΆ
Index ΒΆ
- Constants
- Variables
- func AutoMigrate(db *gorm.DB, models ...interface{}) error
- func CosineSimilarity(a, b Vector) float32
- func Dir(root string, listDirectory bool) http.FileSystem
- func DotProduct(a, b Vector) float32
- func EuclideanDistance(a, b Vector) float32
- func GenerateJWT(secret string, claims JWTClaims) (string, error)
- func GetGorm(c *Context) (*gorm.DB, bool)
- func GetReadDB(c *Context) (*sql.DB, bool)
- func GetShadowDB(c *Context) (*shadowdb.ShadowDB, bool)
- func GetTransactionID(c *Context) string
- func GetWriteDB(c *Context) (*sql.DB, bool)
- func GormBatchDelete(db *gorm.DB, model interface{}, ids []interface{}) error
- func GormBatchInsert(db *gorm.DB, records interface{}, batchSize int) error
- func GormBatchUpdate(db *gorm.DB, model interface{}, updates map[string]interface{}) error
- func GormCountRecords(db *gorm.DB, model interface{}, condition ...interface{}) (int64, error)
- func GormCreate(db *gorm.DB, value interface{}) error
- func GormDelete(db *gorm.DB, value interface{}, conds ...interface{}) error
- func GormExecRaw(db *gorm.DB, sql string, values ...interface{}) error
- func GormExists(db *gorm.DB, model interface{}, condition ...interface{}) (bool, error)
- func GormFind(db *gorm.DB, dest interface{}, pagination *GormPagination, ...) error
- func GormFindByID(db *gorm.DB, dest interface{}, id interface{}) error
- func GormQueryRaw(db *gorm.DB, dest interface{}, sql string, values ...interface{}) error
- func GormSearch(db *gorm.DB, table, column, query string) *gorm.DB
- func GormUpdate(db *gorm.DB, model interface{}, updates interface{}) error
- func GormWithContext(c *Context) *gorm.DB
- func IsDebugging() bool
- func Mode() string
- func MustGetGorm(c *Context) *gorm.DB
- func NewGormDB(config *DBConfig) (*gorm.DB, error)
- func POSTransactionIDGenerator(terminalID string) func() string
- func RefreshToken(oldToken, secret string, extendDuration time.Duration) (string, error)
- func SetMode(value string)
- func SetValidator(v Validator)
- func SetupSwagger(r *Engine, basePath string)
- func SetupSwaggerWithAuth(r *Engine, basePath string, authMiddleware ...HandlerFunc)
- func ShortTransactionIDGenerator() string
- func Shutdown(srv *http.Server, ctx context.Context) error
- func ShutdownWithTimeout(srv *http.Server, timeout ...time.Duration) error
- func UUIDTransactionIDGenerator() string
- func VectorToJSON(vector Vector) string
- func WithTransaction(db *gorm.DB, fn func(tx *gorm.DB) error) error
- type Accounts
- type BasicAuthPair
- type Binding
- type BindingBody
- type BindingUri
- type CORSConfig
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithError(code int, err error) *Error
- func (c *Context) AbortWithStatus(code int)
- func (c *Context) AbortWithStatusJSON(code int, jsonObj any)
- func (c *Context) AbortWithStatusPureJSON(code int, jsonObj any)
- func (c *Context) AsciiJSON(code int, obj interface{})
- func (c *Context) Bind(obj interface{}) error
- func (c *Context) BindHeader(obj interface{}) error
- func (c *Context) BindJSON(obj interface{}) error
- func (c *Context) BindQuery(obj interface{}) error
- func (c *Context) BindUri(obj interface{}) error
- func (c *Context) BindXML(obj interface{}) error
- func (c *Context) ClientIP() string
- func (c *Context) ContentType() string
- func (c *Context) Cookie(name string) (string, error)
- func (c *Context) Copy() *Context
- func (c *Context) Data(code int, contentType string, data []byte)
- func (c *Context) Deadline() (deadline time.Time, ok bool)
- func (c *Context) DefaultPostForm(key, defaultValue string) string
- func (c *Context) DefaultQuery(key, defaultValue string) string
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) Error(err error) *Error
- func (c *Context) File(filepath string)
- func (c *Context) FileAttachment(filepath, filename string)
- func (c *Context) FileFromFS(filepath string, fs http.FileSystem)
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) FullPath() string
- func (c *Context) Get(key string) (value any, exists bool)
- func (c *Context) GetHeader(key string) string
- func (c *Context) GetPostForm(key string) (string, bool)
- func (c *Context) GetPostFormArray(key string) (values []string, ok bool)
- func (c *Context) GetQuery(key string) (string, bool)
- func (c *Context) GetQueryArray(key string) (values []string, ok bool)
- func (c *Context) GetRawData() ([]byte, error)
- func (c *Context) HTML(code int, name string, obj interface{})
- func (c *Context) Header(key, value string)
- func (c *Context) IndentedJSON(code int, obj interface{})
- func (c *Context) IsAborted() bool
- func (c *Context) JSON(code int, obj any)
- func (c *Context) JSONP(code int, obj interface{})
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) MustBindWith(obj interface{}, b Binding) error
- func (c *Context) MustGet(key string) any
- func (c *Context) Negotiate(code int, config Negotiate)
- func (c *Context) NegotiateFormat(offered ...string) string
- func (c *Context) Next()
- func (c *Context) Param(key string) string
- func (c *Context) PostForm(key string) (value string)
- func (c *Context) PostFormArray(key string) (values []string)
- func (c *Context) PureJSON(code int, obj interface{})
- func (c *Context) Query(key string) (value string)
- func (c *Context) QueryArray(key string) (values []string)
- func (c *Context) Redirect(code int, location string)
- func (c *Context) Render(code int, r interface{})
- func (c *Context) SSE(event string, data interface{})
- func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
- func (c *Context) SecureJSON(code int, obj interface{})
- func (c *Context) SecureJSONWithPrefix(code int, prefix string, obj interface{})
- func (c *Context) Set(key string, value any)
- func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
- func (c *Context) ShouldBind(obj interface{}) error
- func (c *Context) ShouldBindBodyWith(obj interface{}, bb BindingBody) (err error)
- func (c *Context) ShouldBindHeader(obj interface{}) error
- func (c *Context) ShouldBindJSON(obj interface{}) error
- func (c *Context) ShouldBindQuery(obj interface{}) error
- func (c *Context) ShouldBindUri(obj interface{}) error
- func (c *Context) ShouldBindWith(obj interface{}, b Binding) error
- func (c *Context) ShouldBindXML(obj interface{}) error
- func (c *Context) Status(code int)
- func (c *Context) Stream(step func(w http.ResponseWriter) bool) bool
- func (c *Context) String(code int, format string, values ...any)
- func (c *Context) Value(key any) any
- func (c *Context) WebSocket(handler WebSocketHandler)
- func (c *Context) WebSocketWithConfig(config WebSocketConfig, handler WebSocketHandler)
- func (c *Context) XML(code int, obj interface{})
- func (c *Context) YAML(code int, obj interface{})
- type DBConfig
- type DefaultValidator
- type Delims
- type Engine
- func (engine *Engine) LoadHTMLFiles(files ...string)
- func (engine *Engine) LoadHTMLGlob(pattern string)
- func (engine *Engine) NoMethod(handlers ...HandlerFunc)
- func (engine *Engine) NoRoute(handlers ...HandlerFunc)
- func (engine *Engine) Routes() (routes RoutesInfo)
- func (engine *Engine) Run(addr ...string) (err error)
- func (engine *Engine) RunServer(addr ...string) *http.Server
- func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error)
- func (engine *Engine) SecureJSONPrefix(prefix string)
- func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (engine *Engine) SetHTMLTemplate(templ *template.Template)
- func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes
- type Error
- type ErrorType
- type GormCache
- type GormPagination
- type GormSoftDelete
- type GzipConfig
- type H
- type HandlerFunc
- func BasicAuth(accounts Accounts) HandlerFunc
- func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc
- func BurstRateLimiter(maxBurst int, refillRate float64) HandlerFunc
- func CORS() HandlerFunc
- func CORSWithConfig(config CORSConfig) HandlerFunc
- func CombinedIPFilter(whitelist, blacklist []string) HandlerFunc
- func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc
- func DBHealthCheck() HandlerFunc
- func GormHealthCheck() HandlerFunc
- func GormInject(db *gorm.DB) HandlerFunc
- func GormLogger() HandlerFunc
- func GormTransaction() HandlerFunc
- func Gzip() HandlerFunc
- func GzipWithConfig(config GzipConfig) HandlerFunc
- func IPBlacklist(blockedIPs ...string) HandlerFunc
- func IPBlacklistWithConfig(config IPBlacklistConfig) HandlerFunc
- func IPWhitelist(allowedIPs ...string) HandlerFunc
- func IPWhitelistWithConfig(config IPWhitelistConfig) HandlerFunc
- func JWTAuth(secret string) HandlerFunc
- func JWTAuthWithConfig(config JWTConfig) HandlerFunc
- func Logger() HandlerFunc
- func LoggerWithConfig(conf LoggerConfig) HandlerFunc
- func MongoHealthCheck(client *MongoClient) HandlerFunc
- func MongoInject(client *MongoClient) HandlerFunc
- func MongoLogger() HandlerFunc
- func MongoTransaction(client *MongoClient) HandlerFunc
- func RateLimiter(max int, window time.Duration) HandlerFunc
- func RateLimiterByAPIKey(max int, window time.Duration, headerName string) HandlerFunc
- func RateLimiterByPath(max int, window time.Duration) HandlerFunc
- func RateLimiterByUser(max int, window time.Duration) HandlerFunc
- func RateLimiterWithConfig(config RateLimiterConfig) HandlerFunc
- func Recovery() HandlerFunc
- func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc
- func RedisCache(config RedisCacheConfig) HandlerFunc
- func RedisHealthCheck(client *RedisClient) HandlerFunc
- func RedisInject(client *RedisClient) HandlerFunc
- func RedisSession(config RedisSessionConfig) HandlerFunc
- func RequireAnyRole(roles ...string) HandlerFunc
- func RequireHealthyDB() HandlerFunc
- func RequireRole(requiredRole string) HandlerFunc
- func ShadowDBMiddleware(sdb *shadowdb.ShadowDB) HandlerFunc
- func SwaggerHandler(config *SwaggerConfig) HandlerFunc
- func SwaggerJSON(jsonData []byte) HandlerFunc
- func SwaggerYAML(yamlData []byte) HandlerFunc
- func TransactionID() HandlerFunc
- func TransactionIDWithConfig(config TransactionIDConfig) HandlerFunc
- func VectorDeleteHandler() HandlerFunc
- func VectorGetHandler() HandlerFunc
- func VectorInject(store VectorStore) HandlerFunc
- func VectorInsertHandler() HandlerFunc
- func VectorLogger() HandlerFunc
- func VectorSearchHandler() HandlerFunc
- type HandlersChain
- type IPBlacklistConfig
- type IPWhitelistConfig
- type IRouter
- type IRoutes
- type InMemoryVectorStore
- func (s *InMemoryVectorStore) Delete(ctx context.Context, ids []string) error
- func (s *InMemoryVectorStore) Get(ctx context.Context, id string) (*VectorDocument, error)
- func (s *InMemoryVectorStore) Insert(ctx context.Context, documents []*VectorDocument) error
- func (s *InMemoryVectorStore) Search(ctx context.Context, queryVector Vector, limit int) ([]*VectorSearchResult, error)
- func (s *InMemoryVectorStore) Update(ctx context.Context, document *VectorDocument) error
- type JWTClaims
- type JWTConfig
- type LogFormatterParams
- type LoggerConfig
- type MongoAuditLog
- type MongoCache
- type MongoClient
- type MongoPagination
- type MongoRepository
- func (r *MongoRepository) Aggregate(ctx context.Context, pipeline interface{}) (*mongo.Cursor, error)
- func (r *MongoRepository) CountDocuments(ctx context.Context, filter interface{}) (int64, error)
- func (r *MongoRepository) CreateIndex(ctx context.Context, keys interface{}, unique bool) (string, error)
- func (r *MongoRepository) DeleteByID(ctx context.Context, id interface{}) (*mongo.DeleteResult, error)
- func (r *MongoRepository) DeleteOne(ctx context.Context, filter interface{}) (*mongo.DeleteResult, error)
- func (r *MongoRepository) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*mongo.Cursor, error)
- func (r *MongoRepository) FindByID(ctx context.Context, id interface{}) *mongo.SingleResult
- func (r *MongoRepository) FindOne(ctx context.Context, filter interface{}) (*mongo.SingleResult, error)
- func (r *MongoRepository) InsertMany(ctx context.Context, documents []interface{}) (*mongo.InsertManyResult, error)
- func (r *MongoRepository) InsertOne(ctx context.Context, document interface{}) (*mongo.InsertOneResult, error)
- func (r *MongoRepository) UpdateByID(ctx context.Context, id interface{}, update interface{}) (*mongo.UpdateResult, error)
- func (r *MongoRepository) UpdateOne(ctx context.Context, filter interface{}, update interface{}) (*mongo.UpdateResult, error)
- type MongoTextSearch
- type Negotiate
- type Param
- type Params
- type ProductEmbedding
- type ProductRecommender
- type RateLimiterConfig
- type RateLimiterStore
- type RecoveryFunc
- type RedisCacheConfig
- type RedisClient
- type RedisPubSub
- type RedisSessionConfig
- type ResponseWriter
- type RouteInfo
- type RouterGroup
- func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) BasePath() string
- func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) Static(relativePath, root string) IRoutes
- func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes
- func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes
- func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes
- type RoutesInfo
- type SSEvent
- type Session
- type SwaggerConfig
- type TransactionIDConfig
- type Validator
- type Vector
- type VectorDocument
- type VectorMiddleware
- type VectorSearchRequest
- type VectorSearchResult
- type VectorStore
- type WebSocketConfig
- type WebSocketConn
- func (ws *WebSocketConn) Close() error
- func (ws *WebSocketConn) IsClosed() bool
- func (ws *WebSocketConn) ReadJSON(v interface{}) error
- func (ws *WebSocketConn) ReadText() (string, error)
- func (ws *WebSocketConn) Send(message []byte) error
- func (ws *WebSocketConn) SendJSON(v interface{}) error
- func (ws *WebSocketConn) SendText(message string) error
- func (ws *WebSocketConn) SetReadDeadline(t time.Time) error
- func (ws *WebSocketConn) SetWriteDeadline(t time.Time) error
- type WebSocketHandler
- type WebSocketHub
- func (h *WebSocketHub) Broadcast(message []byte)
- func (h *WebSocketHub) BroadcastJSON(v interface{})
- func (h *WebSocketHub) ClientCount() int
- func (h *WebSocketHub) Clients() []*WebSocketConn
- func (h *WebSocketHub) Close()
- func (h *WebSocketHub) Register(client *WebSocketConn)
- func (h *WebSocketHub) Unregister(client *WebSocketConn)
Constants ΒΆ
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.
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" )
const Version = "0.1.0"
Variables ΒΆ
var ( JSON = jsonBinding{} XML = xmlBinding{} Form = formBinding{} Query = queryBinding{} FormPost = formPostBinding{} FormMultipart = formMultipartBinding{} Header = headerBinding{} Uri = uriBinding{} )
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
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 )
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") )
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 ΒΆ
AutoMigrate runs auto migration for given models
func CosineSimilarity ΒΆ
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 ΒΆ
DotProduct calculates dot product of two vectors
func EuclideanDistance ΒΆ
EuclideanDistance calculates Euclidean distance between two vectors
func GenerateJWT ΒΆ
GenerateJWT generates a new JWT token with the given claims
func GetShadowDB ΒΆ
GetShadowDB retrieves Shadow DB from context
func GetTransactionID ΒΆ
GetTransactionID retrieves transaction ID from context
func GetWriteDB ΒΆ
GetWriteDB retrieves write database connection from context
func GormBatchDelete ΒΆ
GormBatchDelete performs batch soft delete operation
func GormBatchInsert ΒΆ
GormBatchInsert performs batch insert operation
func GormBatchUpdate ΒΆ
GormBatchUpdate performs batch update operation
func GormCountRecords ΒΆ
GormCountRecords counts total records for pagination
func GormCreate ΒΆ
GormCreate creates a new record
func GormDelete ΒΆ
GormDelete deletes a record (soft delete if model has DeletedAt)
func GormExecRaw ΒΆ
GormExecRaw executes raw SQL query
func GormExists ΒΆ
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 ΒΆ
GormFindByID finds a record by ID
func GormQueryRaw ΒΆ
GormQueryRaw executes raw SQL query and scans results
func GormSearch ΒΆ
GormSearch performs full-text search (MySQL)
func GormUpdate ΒΆ
GormUpdate updates a record
func GormWithContext ΒΆ
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 MustGetGorm ΒΆ
MustGetGorm retrieves GORM database from context or panics
func POSTransactionIDGenerator ΒΆ
POSTransactionIDGenerator generates POS-specific transaction IDs Format: POS-TERMINALID-TIMESTAMP-COUNTER
func RefreshToken ΒΆ
RefreshToken generates a new token with extended expiration
func SetupSwagger ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
VectorToJSON converts a vector to JSON string
Types ΒΆ
type BasicAuthPair ΒΆ
BasicAuthPair represents a user/password pair for BasicAuth
type Binding ΒΆ
Binding describes the interface which needs to be implemented for binding request data
func DefaultBinding ΒΆ
DefaultBinding returns the appropriate Binding instance based on the HTTP method and Content-Type
type BindingBody ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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) BindHeader ΒΆ
BindHeader is a shortcut for c.MustBindWith(obj, binding.Header)
func (*Context) ClientIP ΒΆ
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 ΒΆ
ContentType returns the Content-Type header of the request.
func (*Context) Cookie ΒΆ
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 ΒΆ
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) DefaultPostForm ΒΆ
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 ΒΆ
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) 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) FileAttachment ΒΆ
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 ΒΆ
FullPath returns a matched route full path. For not found routes returns an empty string.
func (*Context) Get ΒΆ
Get returns the value for the given key, ie: (value, true). If the value does not exist it returns (nil, false)
func (*Context) GetPostForm ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
GetRawData returns stream data.
func (*Context) Header ΒΆ
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 ΒΆ
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) JSON ΒΆ
JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".
func (*Context) JSONP ΒΆ
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 ΒΆ
MultipartForm is a helper to access multipart form data
func (*Context) MustBindWith ΒΆ
MustBindWith binds the request body into obj using the specified binding engine
func (*Context) MustGet ΒΆ
MustGet returns the value for the given key if it exists, otherwise it panics.
func (*Context) NegotiateFormat ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
PostFormArray returns a slice of strings for a given form key.
func (*Context) PureJSON ΒΆ
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 ΒΆ
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 ΒΆ
QueryArray returns a slice of strings for a given query key.
func (*Context) SaveUploadedFile ΒΆ
func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
SaveUploadedFile uploads the form file to specific dst
func (*Context) SecureJSON ΒΆ
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 ΒΆ
SecureJSONWithPrefix serializes the given struct as Secure JSON with custom prefix
func (*Context) Set ΒΆ
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 ΒΆ
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 ΒΆ
ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header)
func (*Context) ShouldBindJSON ΒΆ
ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON)
func (*Context) ShouldBindQuery ΒΆ
ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query)
func (*Context) ShouldBindUri ΒΆ
ShouldBindUri binds the passed struct pointer using the URI parameters
func (*Context) ShouldBindWith ΒΆ
ShouldBindWith binds the request body into obj using the specified binding engine
func (*Context) ShouldBindXML ΒΆ
ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML)
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) 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
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 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 ΒΆ
LoadHTMLFiles loads HTML templates from specific files
func (*Engine) LoadHTMLGlob ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
Error represents a error's specification.
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
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) Offset ΒΆ
func (p *GormPagination) Offset() int
Offset calculates the offset for the query
type GormSoftDelete ΒΆ
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 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 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 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 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 ΒΆ
func (s *InMemoryVectorStore) Get(ctx context.Context, id string) (*VectorDocument, error)
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 ΒΆ
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
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 ΒΆ
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
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 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.
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 ΒΆ
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 ΒΆ
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
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 Session ΒΆ
Session represents a user session stored in Redis
func GetSession ΒΆ
GetSession retrieves session from context
func MustGetSession ΒΆ
MustGetSession retrieves session from context or panics
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
type Vector ΒΆ
type Vector []float32
Vector represents an embedding vector
func JSONToVector ΒΆ
JSONToVector converts JSON string to vector
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) 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
Source Files
ΒΆ
- binding.go
- context.go
- errors.go
- fs.go
- gotap.go
- logger.go
- middleware_basicauth.go
- middleware_cors.go
- middleware_gorm.go
- middleware_gzip.go
- middleware_ipwhitelist.go
- middleware_jwt.go
- middleware_mongodb.go
- middleware_ratelimit.go
- middleware_redis.go
- middleware_shadowdb.go
- middleware_swagger.go
- middleware_transaction.go
- middleware_vector.go
- mode.go
- recovery.go
- render.go
- response_writer.go
- router.go
- routergroup.go
- tree.go
- utils.go
- validation.go
- websocket.go
Directories
ΒΆ
| Path | Synopsis |
|---|---|
|
examples
|
|
|
auth
command
|
|
|
basic
command
|
|
|
binding
command
|
|
|
graceful-shutdown
command
|
|
|
json-rendering
command
|
|
|
rendering
command
|
|
|
security
command
|
|
|
static
command
|
|