Documentation
¶
Index ¶
- func BindModelSchema[TSchema any](model any) (*TSchema, error)
- func Delete[TIn any](r *Router, path string, handler func(*Context, *TIn) error, ...)
- func Get[TIn any, TOut any](r *Router, path string, handler func(*Context, *TIn) (*TOut, error), ...)
- func IsBadRequest(err error) bool
- func IsConflict(err error) bool
- func IsForbidden(err error) bool
- func IsInternal(err error) bool
- func IsNotFound(err error) bool
- func IsUnauthorized(err error) bool
- func Patch[TIn any, TOut any](r *Router, path string, handler func(*Context, *TIn) (*TOut, error), ...)
- func Post[TIn any, TOut any](r *Router, path string, handler func(*Context, *TIn) (*TOut, error), ...)
- func Put[TIn any, TOut any](r *Router, path string, handler func(*Context, *TIn) (*TOut, error), ...)
- func SSE[TIn any](r *Router, path string, handler func(*Context, *TIn, *SSEStream) error, ...)
- func WebSocket[TIn any](r *Router, path string, handler func(*Context, *TIn, *WebSocketConn) error, ...)
- func WriteError(c *gin.Context, err error)
- type CacheInvalidator
- type CacheKeyFunc
- type CacheOption
- type CacheTagFunc
- type CachedResponse
- type Config
- type Context
- func (c *Context) BeginTx() error
- func (c *Context) CommitTx() error
- func (c *Context) Deadline() (deadline time.Time, ok bool)
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) Forbidden(message string)
- func (c *Context) GetUserID() uint
- func (c *Context) JSON200(obj interface{})
- func (c *Context) JSON201(obj interface{})
- func (c *Context) JSON204()
- func (c *Context) Locale() string
- func (c *Context) RequestID() string
- func (c *Context) RollbackTx() error
- func (c *Context) StdContext() context.Context
- func (c *Context) T(key string, args ...interface{}) string
- func (c *Context) Unauthorized(message string)
- func (c *Context) Value(key any) any
- type Controller
- type ControllerFunc
- type Download
- type Error
- type ErrorMapper
- type FieldError
- type LifecycleHook
- type MemoryCacheStore
- func (s *MemoryCacheStore) AcquireLock(key string, ttl time.Duration) (func(), bool)
- func (s *MemoryCacheStore) AddTags(key string, tags ...string)
- func (s *MemoryCacheStore) Delete(key string)
- func (s *MemoryCacheStore) DeleteMany(keys ...string)
- func (s *MemoryCacheStore) Get(key string) (*CachedResponse, bool)
- func (s *MemoryCacheStore) InvalidateTags(tags ...string) int
- func (s *MemoryCacheStore) Set(key string, value *CachedResponse)
- type ModelSchema
- type ModelSchemaOption
- type NinjaAPI
- func (api *NinjaAPI) AddController(prefix string, c Controller, opts ...RouterOption)
- func (api *NinjaAPI) AddRouter(router *Router)
- func (api *NinjaAPI) Engine() *gin.Engine
- func (api *NinjaAPI) Handler() http.Handler
- func (api *NinjaAPI) OnShutdown(hook LifecycleHook)
- func (api *NinjaAPI) OnStartup(hook LifecycleHook)
- func (api *NinjaAPI) RegisterErrorMapper(mapper ErrorMapper)
- func (api *NinjaAPI) Run(addr string) error
- func (api *NinjaAPI) Serve(listener net.Listener) error
- func (api *NinjaAPI) Shutdown(ctx context.Context) error
- func (api *NinjaAPI) UseGin(mw ...gin.HandlerFunc)
- type OperationOption
- func BearerAuth() OperationOption
- func Cache(ttl time.Duration, opts ...CacheOption) OperationOption
- func CacheControl(value string) OperationOption
- func Deprecated() OperationOption
- func Description(d string) OperationOption
- func ETag() OperationOption
- func ExcludeFromDocs() OperationOption
- func OperationID(id string) OperationOption
- func Paginated[T any]() OperationOption
- func PaginatedResponse[T any](status int, description string) OperationOption
- func RateLimit(requestsPerSecond int, burst ...int) OperationOption
- func Response(status int, description string, model any) OperationOption
- func Security(name string, scopes ...string) OperationOption
- func SuccessStatus(code int) OperationOption
- func Summary(s string) OperationOption
- func TagDescription(tag, description string) OperationOption
- func Tags(tags ...string) OperationOption
- func Timeout(d time.Duration) OperationOption
- func WithTransaction() OperationOption
- type RedisCacheConfig
- type RedisCacheStore
- func (s *RedisCacheStore) AcquireLock(key string, ttl time.Duration) (func(), bool)
- func (s *RedisCacheStore) AddTags(key string, tags ...string)
- func (s *RedisCacheStore) Client() *redis.Client
- func (s *RedisCacheStore) Close() error
- func (s *RedisCacheStore) Delete(key string)
- func (s *RedisCacheStore) DeleteMany(keys ...string)
- func (s *RedisCacheStore) Get(key string) (*CachedResponse, bool)
- func (s *RedisCacheStore) GetContext(ctx context.Context, key string) (*CachedResponse, bool)
- func (s *RedisCacheStore) InvalidateTags(tags ...string) int
- func (s *RedisCacheStore) Ping(ctx context.Context) error
- func (s *RedisCacheStore) Set(key string, value *CachedResponse)
- func (s *RedisCacheStore) SetContext(ctx context.Context, key string, value *CachedResponse)
- type ResponseCacheContextStore
- type ResponseCacheDeleteStore
- type ResponseCacheLockStore
- type ResponseCacheStore
- type ResponseCacheTagStore
- type Router
- type RouterOption
- func WithBearerAuth() RouterOption
- func WithSecurity(name string, scopes ...string) RouterOption
- func WithTagDescription(tag, description string) RouterOption
- func WithTagDescriptions(descriptions map[string]string) RouterOption
- func WithTags(tags ...string) RouterOption
- func WithVersion(version string) RouterOption
- type SSEEvent
- type SSEStream
- type Schema
- type SecurityRequirement
- type SecurityScheme
- type TransactionHandlers
- type UploadedFile
- type ValidationError
- type VersionConfig
- type WebSocketConn
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BindModelSchema ¶
BindModelSchema creates a user-defined schema value from a model.
func Delete ¶
func Delete[TIn any](r *Router, path string, handler func(*Context, *TIn) error, opts ...OperationOption)
Delete registers a DELETE endpoint with a typed input but no response body.
type DeleteUserInput struct {
UserID int `path:"id"`
}
ninja.Delete(router, "/:id", deleteUserHandler)
func Get ¶
func Get[TIn any, TOut any](r *Router, path string, handler func(*Context, *TIn) (*TOut, error), opts ...OperationOption)
Get registers a GET endpoint.
type ListUsersQuery struct {
Page int `query:"page"`
Size int `query:"size"`
}
ninja.Get(router, "/", listUsersHandler)
func IsBadRequest ¶
func IsConflict ¶
func IsForbidden ¶
func IsInternal ¶
func IsNotFound ¶
func IsUnauthorized ¶
func Patch ¶
func Patch[TIn any, TOut any](r *Router, path string, handler func(*Context, *TIn) (*TOut, error), opts ...OperationOption)
Patch registers a PATCH endpoint.
func Post ¶
func Post[TIn any, TOut any](r *Router, path string, handler func(*Context, *TIn) (*TOut, error), opts ...OperationOption)
Post registers a POST endpoint.
func Put ¶
func Put[TIn any, TOut any](r *Router, path string, handler func(*Context, *TIn) (*TOut, error), opts ...OperationOption)
Put registers a PUT endpoint.
func SSE ¶
func SSE[TIn any](r *Router, path string, handler func(*Context, *TIn, *SSEStream) error, opts ...OperationOption)
SSE registers a GET endpoint that streams server-sent events.
func WebSocket ¶
func WebSocket[TIn any](r *Router, path string, handler func(*Context, *TIn, *WebSocketConn) error, opts ...OperationOption)
WebSocket registers a GET endpoint that upgrades the connection to WebSocket.
func WriteError ¶
WriteError writes an appropriate JSON error response.
Types ¶
type CacheInvalidator ¶
type CacheInvalidator struct {
// contains filtered or unexported fields
}
func NewCacheInvalidator ¶
func NewCacheInvalidator(store ResponseCacheStore) *CacheInvalidator
NewCacheInvalidator provides a unified invalidation entry point for any cache store.
func (*CacheInvalidator) AcquireLock ¶
func (i *CacheInvalidator) AcquireLock(key string, ttl time.Duration) (func(), bool)
AcquireLock tries to obtain a short-lived lock for the given cache key.
func (*CacheInvalidator) Delete ¶
func (i *CacheInvalidator) Delete(keys ...string) int
Delete removes one or more cached keys when the underlying store supports invalidation.
func (*CacheInvalidator) InvalidateTags ¶
func (i *CacheInvalidator) InvalidateTags(tags ...string) int
InvalidateTags removes all keys currently associated with the provided tags.
type CacheKeyFunc ¶
type CacheOption ¶
type CacheOption func(*routeCacheConfig)
func CacheWithKey ¶
func CacheWithKey(fn CacheKeyFunc) CacheOption
CacheWithKey customizes the cache key for a route.
func CacheWithMaxBodyBytes ¶ added in v1.0.3
func CacheWithMaxBodyBytes(max int64) CacheOption
CacheWithMaxBodyBytes limits how much response body data a cached route will buffer for ETag generation and cache storage. Responses larger than max are streamed to the client and are not cached. Use a negative value to disable the limit for trusted small-response routes.
func CacheWithStore ¶
func CacheWithStore(store ResponseCacheStore) CacheOption
CacheWithStore overrides the cache backend for a route.
func CacheWithTags ¶
func CacheWithTags(fn CacheTagFunc) CacheOption
CacheWithTags assigns one or more tags to stored responses so they can be invalidated later.
type CacheTagFunc ¶
type CachedResponse ¶
type CachedResponse struct {
Status int
Header http.Header
Body []byte
Expires time.Time
ETag string
}
CachedResponse is the serialized representation of a cached HTTP response. All fields are exported so that external ResponseCacheStore implementations can read and write them without relying on internal package types.
type Config ¶
type Config struct {
// Title is the API title shown in the OpenAPI docs (default: "Gin Ninja API").
Title string
// Version is the API version string (default: "1.0.0").
Version string
// Description is an optional long description of the API.
Description string
// DocsURL is the path at which the Swagger UI is served (default: "/docs").
// Set DisableDocs to true to disable the UI.
DocsURL string
// DisableDocs disables the Swagger UI route.
DisableDocs bool
// HideDocsShortcut hides the "API Docs" shortcut on the homepage while
// leaving the Swagger UI route configured by DocsURL unchanged.
HideDocsShortcut bool
// OpenAPIURL is the path at which the raw OpenAPI JSON is served (default: "/openapi.json").
OpenAPIURL string
// DisableOpenAPI disables the raw OpenAPI JSON routes. Because Swagger UI
// depends on OpenAPI JSON, enabling this also disables the docs route.
DisableOpenAPI bool
// Prefix is a global path prefix prepended to every route (default: "").
Prefix string
// Versions configures named API version namespaces and version-scoped docs.
Versions map[string]VersionConfig
// HomepageURL is the path at which the welcome homepage is served (default: "/").
// Set DisableHomepage to true to disable the homepage.
HomepageURL string
// DisableHomepage disables the welcome homepage route.
DisableHomepage bool
// AdminURL is the path used for the "Admin" shortcut button on the homepage.
// Leave empty to hide the Admin button (the framework does not mount admin itself).
AdminURL string
// SecuritySchemes defines reusable OpenAPI security schemes, such as JWT
// bearer authentication shown by Swagger UI's "Authorize" button.
SecuritySchemes map[string]SecurityScheme
// Settings is optional instance-scoped application configuration used by
// framework helpers such as the startup banner.
Settings *settings.Config
// TransactionHandlers configures request-scoped transaction helpers for
// operations that use WithTransaction.
TransactionHandlers *TransactionHandlers
// DisableGinDefault disables the default gin Logger and Recovery middleware
// when set to true. Set this to true when you provide your own middleware
// via UseGin (e.g. the structured logger from middleware.Logger).
DisableGinDefault bool
// ReadTimeout limits the time allowed to read the full request, including
// the body. Zero uses the default safe timeout.
ReadTimeout time.Duration
// WriteTimeout limits the time allowed to write a response. Zero uses the
// default safe timeout.
WriteTimeout time.Duration
// IdleTimeout limits how long keep-alive connections stay idle. Zero uses
// the default safe timeout.
IdleTimeout time.Duration
// GracefulShutdownTimeout bounds how long Run waits for shutdown hooks and
// in-flight requests after receiving SIGINT or SIGTERM. Zero uses 10s.
GracefulShutdownTimeout time.Duration
}
Config holds configuration options for a NinjaAPI instance.
type Context ¶
Context wraps *gin.Context and is passed to every handler function. It gives handlers access to the underlying gin context while remaining compatible with the standard library context.Context interface.
func (*Context) GetUserID ¶
GetUserID returns the authenticated user's ID from the JWT claims. Returns 0 if the JWTAuth middleware was not registered or the token was invalid.
func (*Context) JSON200 ¶
func (c *Context) JSON200(obj interface{})
JSON200 is a convenience method to respond with 200 OK and a JSON body.
func (*Context) JSON201 ¶
func (c *Context) JSON201(obj interface{})
JSON201 is a convenience method to respond with 201 Created and a JSON body.
func (*Context) JSON204 ¶
func (c *Context) JSON204()
JSON204 is a convenience method to respond with 204 No Content.
func (*Context) Locale ¶
Locale returns the negotiated locale stored by the I18n middleware. Returns "en" if the I18n middleware is not registered or the context does not contain a locale value.
locale := ctx.Locale() // "en" or "zh"
func (*Context) RequestID ¶
RequestID returns the X-Request-ID value injected by the RequestID middleware. Returns an empty string if the middleware was not registered.
func (*Context) RollbackTx ¶
RollbackTx rolls back the active request-scoped transaction.
func (*Context) StdContext ¶
StdContext returns the standard library context from the request.
func (*Context) T ¶
T returns the translated message for key in the request locale. Variadic args are applied with fmt.Sprintf when the message contains format verbs.
msg := ctx.T("not_found") // "not found" or "资源不存在"
func (*Context) Unauthorized ¶
Unauthorized aborts the request with 401 Unauthorized.
type Controller ¶
type Controller interface {
Register(r *Router)
}
Controller groups related routes for a single domain resource. Implement Register to wire all of its endpoints onto the provided Router.
Use api.AddController to create the router, call Register, and mount it in one step:
type BookController struct{ db *gorm.DB }
func (c *BookController) Register(r *ninja.Router) {
ninja.Get(r, "/", c.List, ninja.Summary("List books"))
ninja.Post(r, "/", c.Create, ninja.Summary("Create book"))
ninja.Get(r, "/:id", c.Get, ninja.Summary("Get book"))
ninja.Put(r, "/:id", c.Update, ninja.Summary("Update book"))
ninja.Delete(r, "/:id", c.Delete, ninja.Summary("Delete book"))
}
api.AddController("/books", &BookController{db: db},
ninja.WithTags("Books"),
ninja.WithBearerAuth(),
)
type ControllerFunc ¶
type ControllerFunc func(r *Router)
ControllerFunc is an adapter that lets a plain function serve as a Controller. It is useful for small, inline controllers and in tests.
api.AddController("/items", ninja.ControllerFunc(func(r *ninja.Router) {
ninja.Get(r, "/", listItems)
ninja.Post(r, "/", createItem)
}), ninja.WithTags("Items"))
func (ControllerFunc) Register ¶
func (f ControllerFunc) Register(r *Router)
Register calls f(r), satisfying the Controller interface.
type Download ¶
type Download struct {
Filename string
ContentType string
Data []byte
Reader io.Reader
Size int64
Inline bool
Headers map[string]string
}
Download represents a binary/file response.
func NewDownload ¶
NewDownload returns a binary response backed by a byte slice.
type Error ¶
type Error struct {
// Status is the HTTP status code.
Status int `json:"-"`
// Code is an optional machine-readable error code.
Code string `json:"code,omitempty"`
// Message is a human-readable description of the error.
Message string `json:"message"`
// Detail provides additional error context.
Detail interface{} `json:"detail,omitempty"`
}
Error represents an API error response.
func BadRequestError ¶
func BadRequestError() *Error
BadRequestError returns a fresh copy of the standard bad-request error.
func ConflictError ¶
func ConflictError() *Error
ConflictError returns a fresh copy of the standard conflict error.
func ForbiddenError ¶
func ForbiddenError() *Error
ForbiddenError returns a fresh copy of the standard forbidden error.
func InternalError ¶
func InternalError() *Error
InternalError returns a fresh copy of the standard internal-server error.
func NewErrorWithCode ¶
NewErrorWithCode creates a new API error with a status code, machine-readable code, and message.
func NotFoundError ¶
func NotFoundError() *Error
NotFoundError returns a fresh copy of the standard not-found error.
func UnauthorizedError ¶
func UnauthorizedError() *Error
UnauthorizedError returns a fresh copy of the standard unauthorized error.
type ErrorMapper ¶
ErrorMapper converts arbitrary errors into framework errors. Returning nil means the mapper did not handle the error.
type FieldError ¶
type FieldError struct {
// Field is the name of the field that failed validation.
Field string `json:"field"`
// Message describes why validation failed.
Message string `json:"message"`
}
FieldError represents a single field-level validation failure.
type LifecycleHook ¶
LifecycleHook runs during API startup or shutdown.
type MemoryCacheStore ¶
type MemoryCacheStore struct {
// contains filtered or unexported fields
}
func NewMemoryCacheStore ¶
func NewMemoryCacheStore() *MemoryCacheStore
NewMemoryCacheStore creates an in-memory route cache store.
func NewMemoryCacheStoreWithLimit ¶
func NewMemoryCacheStoreWithLimit(maxEntries int) *MemoryCacheStore
NewMemoryCacheStoreWithLimit creates an in-memory route cache store with a bounded size.
func (*MemoryCacheStore) AcquireLock ¶
func (s *MemoryCacheStore) AcquireLock(key string, ttl time.Duration) (func(), bool)
func (*MemoryCacheStore) AddTags ¶
func (s *MemoryCacheStore) AddTags(key string, tags ...string)
func (*MemoryCacheStore) Delete ¶
func (s *MemoryCacheStore) Delete(key string)
func (*MemoryCacheStore) DeleteMany ¶
func (s *MemoryCacheStore) DeleteMany(keys ...string)
func (*MemoryCacheStore) Get ¶
func (s *MemoryCacheStore) Get(key string) (*CachedResponse, bool)
func (*MemoryCacheStore) InvalidateTags ¶
func (s *MemoryCacheStore) InvalidateTags(tags ...string) int
func (*MemoryCacheStore) Set ¶
func (s *MemoryCacheStore) Set(key string, value *CachedResponse)
type ModelSchema ¶
type ModelSchema[T any] struct { Model T `json:"-"` Fields []string `json:"-"` Exclude []string `json:"-"` }
ModelSchema wraps a model value and serializes only the allowed fields.
func NewModelSchema ¶
func NewModelSchema[T any](model T, opts ...ModelSchemaOption) *ModelSchema[T]
NewModelSchema wraps a model with optional field filters.
func (ModelSchema[T]) MarshalJSON ¶
func (m ModelSchema[T]) MarshalJSON() ([]byte, error)
type ModelSchemaOption ¶
type ModelSchemaOption func(*modelSchemaFilter)
ModelSchemaOption customizes how a model is serialized.
func Exclude ¶
func Exclude(fields ...string) ModelSchemaOption
Exclude removes the provided field names from serialization.
func Fields ¶
func Fields(fields ...string) ModelSchemaOption
Fields limits serialization to the provided field names.
type NinjaAPI ¶
type NinjaAPI struct {
// contains filtered or unexported fields
}
NinjaAPI is the central API instance. It wraps a *gin.Engine and manages routers, middleware, and OpenAPI documentation generation in a style inspired by django-ninja.
api := ninja.New(ninja.Config{Title: "My API", Version: "1.0.0"})
api.AddRouter(usersRouter)
api.Run(":8080")
func New ¶
New creates a new NinjaAPI with the supplied configuration. Sensible defaults are applied for any empty fields.
func (*NinjaAPI) AddController ¶
func (api *NinjaAPI) AddController(prefix string, c Controller, opts ...RouterOption)
AddController is a convenience wrapper that creates a Router with the given prefix and options, delegates route registration to the controller, and mounts the router via AddRouter.
api.AddController("/books", &BookController{db: db},
ninja.WithTags("Books"),
ninja.WithBearerAuth(),
)
func (*NinjaAPI) AddRouter ¶
AddRouter mounts a Router under the API. All operations defined on the router (and any nested sub-routers) are registered with the gin engine and included in the OpenAPI spec.
func (*NinjaAPI) Engine ¶
Engine returns the underlying *gin.Engine so callers can add custom middleware or register routes outside of the ninja router system.
func (*NinjaAPI) Handler ¶
Handler returns the API as an http.Handler, useful for testing with httptest.NewServer or embedding in existing servers.
func (*NinjaAPI) OnShutdown ¶
func (api *NinjaAPI) OnShutdown(hook LifecycleHook)
OnShutdown registers a hook that runs during graceful shutdown.
func (*NinjaAPI) OnStartup ¶
func (api *NinjaAPI) OnStartup(hook LifecycleHook)
OnStartup registers a hook that runs before the HTTP server starts accepting traffic.
func (*NinjaAPI) RegisterErrorMapper ¶
func (api *NinjaAPI) RegisterErrorMapper(mapper ErrorMapper)
func (*NinjaAPI) Shutdown ¶
Shutdown gracefully stops the active server and runs shutdown hooks once.
func (*NinjaAPI) UseGin ¶
func (api *NinjaAPI) UseGin(mw ...gin.HandlerFunc)
UseGin registers one or more raw gin.HandlerFunc middleware on the underlying engine before application routers are mounted. Middleware added here affects routers registered after this call; use router.UseGin for router-scoped middleware.
api.UseGin(middleware.RequestID()) api.UseGin(middleware.CORSFromConfig(cfg.CORS)) api.UseGin(middleware.Logger(log)) api.UseGin(middleware.JWTAuthWithConfig(cfg.JWT))
type OperationOption ¶
type OperationOption func(*operation)
OperationOption is a functional option for configuring an Operation.
func BearerAuth ¶
func BearerAuth() OperationOption
BearerAuth marks this operation as requiring the default bearerAuth scheme.
func Cache ¶
func Cache(ttl time.Duration, opts ...CacheOption) OperationOption
Cache enables route-level response caching for safe read endpoints.
func CacheControl ¶
func CacheControl(value string) OperationOption
CacheControl sets the Cache-Control response header for successful responses.
func Deprecated ¶
func Deprecated() OperationOption
Deprecated marks the operation as deprecated in the docs.
func Description ¶
func Description(d string) OperationOption
Description sets the long description shown in the OpenAPI docs.
func ETag ¶
func ETag() OperationOption
ETag enables automatic ETag generation for successful responses.
func ExcludeFromDocs ¶
func ExcludeFromDocs() OperationOption
ExcludeFromDocs omits the operation from the generated OpenAPI spec.
func OperationID ¶
func OperationID(id string) OperationOption
OperationID sets an explicit operationId in the OpenAPI spec.
func Paginated ¶
func Paginated[T any]() OperationOption
Paginated declares a standard paginated success response schema.
func PaginatedResponse ¶
func PaginatedResponse[T any](status int, description string) OperationOption
PaginatedResponse documents an additional paginated OpenAPI response.
func RateLimit ¶
func RateLimit(requestsPerSecond int, burst ...int) OperationOption
RateLimit applies a per-operation in-memory token-bucket rate limit.
func Response ¶
func Response(status int, description string, model any) OperationOption
Response documents an additional OpenAPI response for the operation. Pass model as nil for responses without a JSON response body.
func Security ¶
func Security(name string, scopes ...string) OperationOption
Security adds an OpenAPI security requirement to this operation.
func SuccessStatus ¶
func SuccessStatus(code int) OperationOption
SuccessStatus sets the HTTP status code used for successful responses. The default is 200 OK (201 Created is common for POST).
func Summary ¶
func Summary(s string) OperationOption
Summary sets the human-readable summary shown in the OpenAPI docs.
func TagDescription ¶
func TagDescription(tag, description string) OperationOption
TagDescription records a top-level OpenAPI tag description for this operation.
func Tags ¶
func Tags(tags ...string) OperationOption
Tags overrides the tags for this specific operation.
func Timeout ¶
func Timeout(d time.Duration) OperationOption
Timeout applies a context-based per-operation cooperative timeout. It cancels the request context and allows an early timeout response, but long-running handlers must observe ctx.Done() or ctx.Request.Context().Done() to stop promptly.
func WithTransaction ¶
func WithTransaction() OperationOption
WithTransaction wraps the operation in a request-scoped database transaction.
type RedisCacheConfig ¶
RedisCacheConfig configures the built-in Redis-backed response cache store.
type RedisCacheStore ¶
type RedisCacheStore struct {
// contains filtered or unexported fields
}
RedisCacheStore stores serialized route responses in Redis.
func NewRedisCacheStore ¶
func NewRedisCacheStore(cfg RedisCacheConfig) (*RedisCacheStore, error)
NewRedisCacheStore creates a Redis-backed response cache store.
func NewRedisCacheStoreWithClient ¶
func NewRedisCacheStoreWithClient(client *redis.Client, prefix string) *RedisCacheStore
NewRedisCacheStoreWithClient wraps an existing Redis client.
func (*RedisCacheStore) AcquireLock ¶
func (s *RedisCacheStore) AcquireLock(key string, ttl time.Duration) (func(), bool)
func (*RedisCacheStore) AddTags ¶
func (s *RedisCacheStore) AddTags(key string, tags ...string)
func (*RedisCacheStore) Client ¶
func (s *RedisCacheStore) Client() *redis.Client
Client exposes the underlying Redis client for health checks and shutdown hooks.
func (*RedisCacheStore) Close ¶
func (s *RedisCacheStore) Close() error
Close closes the underlying Redis client.
func (*RedisCacheStore) Delete ¶
func (s *RedisCacheStore) Delete(key string)
func (*RedisCacheStore) DeleteMany ¶
func (s *RedisCacheStore) DeleteMany(keys ...string)
func (*RedisCacheStore) Get ¶
func (s *RedisCacheStore) Get(key string) (*CachedResponse, bool)
func (*RedisCacheStore) GetContext ¶
func (s *RedisCacheStore) GetContext(ctx context.Context, key string) (*CachedResponse, bool)
func (*RedisCacheStore) InvalidateTags ¶
func (s *RedisCacheStore) InvalidateTags(tags ...string) int
func (*RedisCacheStore) Ping ¶
func (s *RedisCacheStore) Ping(ctx context.Context) error
Ping verifies that the configured Redis server is reachable.
func (*RedisCacheStore) Set ¶
func (s *RedisCacheStore) Set(key string, value *CachedResponse)
func (*RedisCacheStore) SetContext ¶
func (s *RedisCacheStore) SetContext(ctx context.Context, key string, value *CachedResponse)
type ResponseCacheContextStore ¶
type ResponseCacheContextStore interface {
GetContext(ctx context.Context, key string) (*CachedResponse, bool)
SetContext(ctx context.Context, key string, value *CachedResponse)
}
ResponseCacheContextStore optionally supports request-scoped cache I/O. Implementations should honor cancellation and deadlines carried by ctx.
type ResponseCacheDeleteStore ¶
ResponseCacheDeleteStore optionally supports cache-key invalidation.
type ResponseCacheLockStore ¶
type ResponseCacheLockStore interface {
AcquireLock(key string, ttl time.Duration) (unlock func(), ok bool)
}
ResponseCacheLockStore optionally supports short-lived distributed or local locks.
type ResponseCacheStore ¶
type ResponseCacheStore interface {
Get(key string) (*CachedResponse, bool)
Set(key string, value *CachedResponse)
}
ResponseCacheStore stores serialized route responses for cacheable endpoints. Implementations receive fully-exported CachedResponse values and may store them in any backend (in-process memory, Redis, Memcached, etc.).
type ResponseCacheTagStore ¶
type ResponseCacheTagStore interface {
AddTags(key string, tags ...string)
InvalidateTags(tags ...string) int
}
ResponseCacheTagStore optionally supports assigning tags to keys and invalidating by tag.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router groups a set of API endpoints under a common URL prefix. Routers can be nested arbitrarily.
func NewRouter ¶
func NewRouter(prefix string, opts ...RouterOption) *Router
NewRouter creates a new Router with the given URL prefix and options.
r := ninja.NewRouter("/users", ninja.WithTags("Users"))
func (*Router) AddRouter ¶
AddRouter mounts a sub-router under this router. The sub-router's prefix is appended to this router's prefix.
func (*Router) Use ¶
Use adds a typed middleware function that runs before every handler on this router. Returning a non-nil error aborts the request with an appropriate error response.
func (*Router) UseGin ¶
func (r *Router) UseGin(mw ...gin.HandlerFunc)
UseGin adds one or more raw gin.HandlerFunc middleware to this router. Use this to attach infrastructure middleware (JWT, CORS, rate limiting, etc.) at the router level instead of the engine level.
r := ninja.NewRouter("/admin", ninja.WithTags("Admin"))
r.UseGin(middleware.JWTAuthWithSecret("secret"))
type RouterOption ¶
type RouterOption func(*Router)
RouterOption is a functional option for configuring a Router.
func WithBearerAuth ¶
func WithBearerAuth() RouterOption
WithBearerAuth applies the default JWT bearer OpenAPI security requirement.
func WithSecurity ¶
func WithSecurity(name string, scopes ...string) RouterOption
WithSecurity adds an OpenAPI security requirement to all operations registered on this router.
func WithTagDescription ¶
func WithTagDescription(tag, description string) RouterOption
WithTagDescription records a top-level OpenAPI tag description.
func WithTagDescriptions ¶
func WithTagDescriptions(descriptions map[string]string) RouterOption
WithTagDescriptions records multiple top-level OpenAPI tag descriptions.
func WithTags ¶
func WithTags(tags ...string) RouterOption
WithTags adds OpenAPI tags to all operations registered on this router.
func WithVersion ¶
func WithVersion(version string) RouterOption
WithVersion marks the router and its nested operations as belonging to a named API version.
type SSEStream ¶
type SSEStream struct {
// contains filtered or unexported fields
}
SSEStream writes compliant server-sent event frames.
type Schema ¶
type Schema struct {
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Description string `json:"description,omitempty"`
Default interface{} `json:"default,omitempty"`
Properties map[string]*Schema `json:"properties,omitempty"`
Items *Schema `json:"items,omitempty"`
Required []string `json:"required,omitempty"`
Enum []interface{} `json:"enum,omitempty"`
Ref string `json:"$ref,omitempty"`
Nullable bool `json:"nullable,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
Example interface{} `json:"example,omitempty"`
}
Schema represents a JSON Schema object (OpenAPI 3.0 compatible subset).
type SecurityRequirement ¶
SecurityRequirement maps an OpenAPI security scheme name to required scopes.
type SecurityScheme ¶
type SecurityScheme struct {
Type string `json:"type"`
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"`
In string `json:"in,omitempty"`
Scheme string `json:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty"`
}
SecurityScheme describes an OpenAPI reusable security scheme.
func HTTPBearerSecurityScheme ¶
func HTTPBearerSecurityScheme(bearerFormat string) SecurityScheme
HTTPBearerSecurityScheme returns a standard JWT bearer auth scheme.
type TransactionHandlers ¶
type TransactionHandlers struct {
Begin func(*gin.Context) error
Commit func(*gin.Context) error
Rollback func(*gin.Context) error
WithTransaction func(*gin.Context, func() error) error
}
TransactionHandlers configures request-scoped transaction behavior for a NinjaAPI instance.
type UploadedFile ¶
type UploadedFile struct {
*multipart.FileHeader
}
UploadedFile wraps a multipart file and exposes convenience helpers.
func (*UploadedFile) Bytes ¶
func (f *UploadedFile) Bytes() ([]byte, error)
Bytes reads the uploaded file content into memory.
type ValidationError ¶
type ValidationError struct {
// Errors contains the individual field validation errors.
Errors []FieldError `json:"errors"`
}
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type VersionConfig ¶
type VersionConfig struct {
Prefix string
Description string
// Deprecated marks the API version as deprecated. Requests to deprecated
// routes receive a `Deprecation: true` response header (and a date-formatted
// `Deprecation` header when DeprecatedSince is set).
Deprecated bool
// DeprecatedSince is the optional RFC 1123 date at which deprecation was
// announced. When set, the `Deprecation` header is emitted as an HTTP-date
// (e.g. "Mon, 01 Jan 2024 00:00:00 GMT") instead of the literal "true".
DeprecatedSince time.Time
// Sunset is a backward-compatible RFC 1123 date string indicating when the
// version will be removed (e.g. "Mon, 01 Jul 2025 00:00:00 GMT"). Prefer
// SunsetTime for new code. When set, the `Sunset` response header is
// emitted.
Sunset string
// SunsetTime is the preferred structured form of Sunset. If non-zero it
// takes precedence over the compatibility Sunset string and is formatted as
// an HTTP-date.
SunsetTime time.Time
// MigrationURL is a URL pointing to migration documentation. When set,
// a `Link: <url>; rel="deprecation"` header is emitted.
MigrationURL string
// contains filtered or unexported fields
}
VersionConfig configures a named API version namespace.
type WebSocketConn ¶
WebSocketConn is a small convenience wrapper over gorilla/websocket.
func (*WebSocketConn) ReceiveJSON ¶
func (c *WebSocketConn) ReceiveJSON(v any) error
func (*WebSocketConn) ReceiveText ¶
func (c *WebSocketConn) ReceiveText() (string, error)
func (*WebSocketConn) SendJSON ¶
func (c *WebSocketConn) SendJSON(v any) error
func (*WebSocketConn) SendText ¶
func (c *WebSocketConn) SendText(value string) error
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package admin provides an explicit, metadata-driven admin API for GORM models.
|
Package admin provides an explicit, metadata-driven admin API for GORM models. |
|
Package bootstrap provides helpers for initialising the core application components (database, logger) from a settings.Config.
|
Package bootstrap provides helpers for initialising the core application components (database, logger) from a settings.Config. |
|
cmd
|
|
|
gin-ninja-cli
module
|
|
|
examples
|
|
|
admin
command
Package main runs the focused admin gin-ninja example.
|
Package main runs the focused admin gin-ninja example. |
|
basic
command
Package main demonstrates a minimal gin-ninja application.
|
Package main demonstrates a minimal gin-ninja application. |
|
compact
command
Package main runs a compact counterpart to the full gin-ninja example.
|
Package main runs a compact counterpart to the full gin-ninja example. |
|
controller
command
Package main demonstrates the gin-ninja Controller pattern.
|
Package main demonstrates the gin-ninja Controller pattern. |
|
features
command
Package main runs the focused feature-demo gin-ninja example.
|
Package main runs the focused feature-demo gin-ninja example. |
|
full
command
Package main is the entry-point for the gin-ninja full example.
|
Package main is the entry-point for the gin-ninja full example. |
|
users
command
Package main runs the focused auth + users gin-ninja example.
|
Package main runs the focused auth + users gin-ninja example. |
|
internal
|
|
|
Package middleware provides production-ready HTTP middleware for gin-ninja applications.
|
Package middleware provides production-ready HTTP middleware for gin-ninja applications. |
|
Package order provides safe, declarative sorting helpers for query inputs.
|
Package order provides safe, declarative sorting helpers for query inputs. |
|
Package orm provides a thin integration layer between gin-ninja and the go-toolkits/gormx ORM library (https://github.com/shijl0925/go-toolkits).
|
Package orm provides a thin integration layer between gin-ninja and the go-toolkits/gormx ORM library (https://github.com/shijl0925/go-toolkits). |
|
Package pagination provides reusable pagination types for gin-ninja handlers.
|
Package pagination provides reusable pagination types for gin-ninja handlers. |
|
pkg
|
|
|
i18n
Package i18n provides locale negotiation and translation helpers for gin-ninja applications.
|
Package i18n provides locale negotiation and translation helpers for gin-ninja applications. |
|
logger
Package logger provides a Zap-based structured logger for gin-ninja applications.
|
Package logger provides a Zap-based structured logger for gin-ninja applications. |
|
response
Package response provides a standardised JSON response envelope for gin-ninja APIs, following the common pattern used in Go admin backends:
|
Package response provides a standardised JSON response envelope for gin-ninja APIs, following the common pattern used in Go admin backends: |
|
Package settings provides Viper-based configuration management for gin-ninja applications.
|
Package settings provides Viper-based configuration management for gin-ninja applications. |