srv

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package srv provides a minimal API server with routing, middleware, and model binding.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Error

func Error(code int, msg string) error

Error creates an HTTP error with a status code and message.

func JSON

func JSON(ctx *Context, code int, v any) error

JSON writes a JSON response using the context.

Types

type Context

type Context struct {
	Request  *http.Request
	Response http.ResponseWriter
	Params   map[string]string
	Ctx      context.Context
	// contains filtered or unexported fields
}

Context holds the request state for a single HTTP request.

func (*Context) Bind

func (c *Context) Bind(v any) error

Bind decodes the request body into v based on the Content-Type header.

func (*Context) BindAndValidate

func (c *Context) BindAndValidate(target any) validation.Errors

BindAndValidate decodes the request body into target and then runs validation. Returns a validation.Errors slice if decoding or validation fails.

func (*Context) Get

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

Get retrieves a value from the request context by key.

func (*Context) JSON

func (c *Context) JSON(code int, v any) error

JSON writes a JSON response with the given status code.

func (*Context) Set

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

Set stores a key-value pair in the request context.

func (*Context) String

func (c *Context) String(code int, s string)

String writes a plain text response with the given status code.

func (*Context) Validate

func (c *Context) Validate(target any) validation.Errors

Validate runs validation rules on the target object and returns the collected validation errors. Returns nil if there are no errors.

type Handler added in v1.1.0

type Handler interface {
	Handle(ctx context.Context) (any, error)
}

Handler is the interface for declarative struct-tagged endpoints.

type HandlerFunc

type HandlerFunc func(*Context) error

HandlerFunc is the handler signature for srv routes.

func HealthEndpoint

func HealthEndpoint(checker func(ctx context.Context) error) HandlerFunc

HealthEndpoint returns a handler that reports health status based on the checker function.

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware wraps a HandlerFunc, returning a new HandlerFunc.

func Auth

func Auth(secret []byte) Middleware

Auth returns middleware that validates a Bearer token using auth.VerifyToken. A valid token is attached to the context via auth.Payload.

func CORS

func CORS(allowOrigins ...string) Middleware

CORS returns middleware that sets CORS headers. Preflight OPTIONS requests get 204.

func Compress

func Compress() Middleware

Compress returns middleware that sets gzip content encoding.

func Logger

func Logger() Middleware

Logger returns middleware that logs request method, path, duration, and status.

func RateLimit

func RateLimit(rate, burst int) Middleware

RateLimit returns middleware that limits requests per client using a token bucket.

func Recovery

func Recovery() Middleware

Recovery returns middleware that catches panics and converts them to errors with stack traces.

func RequestID

func RequestID() Middleware

RequestID returns middleware that sets and propagates X-Request-ID.

type Option

type Option = options.Option[Server]

Option configures a Server.

type RouteInfo added in v1.2.0

type RouteInfo struct {
	Method string
	Path   string
}

RouteInfo describes a registered route.

type Server

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

Server is a minimal API HTTP server with routing and middleware support.

func New

func New(opts ...Option) *Server

New creates a new Server with optional configuration.

func (*Server) Group

func (s *Server) Group(prefix string, mw ...Middleware) *group

Group creates a route group with a common prefix and optional middleware.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string) error

ListenAndServe starts the server on the given address.

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error

ListenAndServeTLS starts the server with TLS on the given address.

func (*Server) MapDelete

func (s *Server) MapDelete(path string, handler HandlerFunc, mw ...Middleware)

MapDelete registers a DELETE route at the given path.

func (*Server) MapGet

func (s *Server) MapGet(path string, handler HandlerFunc, mw ...Middleware)

MapGet registers a GET route at the given path.

func (*Server) MapPost

func (s *Server) MapPost(path string, handler HandlerFunc, mw ...Middleware)

MapPost registers a POST route at the given path.

func (*Server) MapPut

func (s *Server) MapPut(path string, handler HandlerFunc, mw ...Middleware)

MapPut registers a PUT route at the given path.

func (*Server) RegisterHandler added in v1.1.0

func (s *Server) RegisterHandler(prototype Handler, container *di.Container)

RegisterHandler registers a struct that implements Handler as an endpoint. The struct must have method and path tags:

type MyEndpoint struct {
    Pattern `method:"GET" path:"/api/v1/ping"`
    Times   int `query:"times" default:"1"`
}

The container is used for dependency injection and bind for field population.

func (*Server) Routes added in v1.2.0

func (s *Server) Routes() []RouteInfo

Routes returns the registered route metadata.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler, dispatching requests through global middleware and routes.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server.

func (*Server) Use

func (s *Server) Use(mw Middleware)

Use registers global middleware on the server.

Jump to

Keyboard shortcuts

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