httpserver

package
v0.0.0-...-b125894 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultListLimit is the default page size for list endpoints.
	DefaultListLimit = 100
	// MaxListLimit is the maximum allowed page size.
	MaxListLimit = 1000
)
View Source
const MethodAny = "*"

MethodAny registers a route for all HTTP methods supported by Gin.

Variables

View Source
var ErrServerStopping = errors.New("http server is stopping")

ErrServerStopping indicates that the server is already shutting down.

Functions

func NewAuthService

func NewAuthService(users []UserConfig) *authService

NewAuthService creates a compatibility adapter for the HTTP server.

func NewRoot

func NewRoot(engine *httpGin.Engine, root string) *routerGroup

Root group

Types

type Config

type Config struct {
	EnablePProf       bool
	RateLimit         *RateLimitConfig
	EnableRetry       bool
	AuthTokens        []string
	AuthUsers         []UserConfig
	PublicPaths       []string
	AdminPaths        []string
	PromReg           *prometheus.Registry
	VersionInfo       *version.Info
	ReadHeaderTimeout time.Duration
	ReadTimeout       time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	MaxHeaderBytes    int
	MaxBodyBytes      int64
	ErrorStatusMapper response.HTTPStatusMapper
}

Config defines the configuration options for the HTTP server.

type Context

type Context struct {
	UserID  string
	IsAdmin bool
	// contains filtered or unexported fields
}

Context is a custom request context that wraps gin.Context internally. All gin types are hidden; callers only interact with this type.

func (*Context) Abort

func (ctx *Context) Abort()

Abort prevents pending handlers from being called.

func (*Context) CanAccessTask

func (ctx *Context) CanAccessTask(taskUserID string) bool

CanAccessTask reports whether the current user may access a task owned by taskUserID.

func (*Context) ClientIP

func (ctx *Context) ClientIP() string

ClientIP returns the client's IP address.

func (*Context) DefaultQuery

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

Query returns the query string value for the given key, or the defaultValue if not present.

func (*Context) ErrorStatusMapper

func (ctx *Context) ErrorStatusMapper() response.HTTPStatusMapper

ErrorStatusMapper returns the process-specific API error status directory.

func (*Context) Header

func (ctx *Context) Header(key, val string)

Header sets a response header.

func (*Context) JSON

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

JSON writes a JSON response with the given HTTP status code.

func (*Context) Next

func (ctx *Context) Next()

Next executes the pending handlers in the chain.

func (*Context) Param

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

Param returns the URL path parameter for the given key (e.g. "id" for "/:id").

func (*Context) ParseListParams

func (ctx *Context) ParseListParams() (ListParams, error)

ParseListParams reads limit/offset/sort from the query string. Defaults apply only to absent parameters; explicit limits must be positive.

func (*Context) ProtoBuf

func (ctx *Context) ProtoBuf(code int, obj any)

ProtoBuf writes a protobuf response with the given HTTP status code.

func (*Context) Query

func (ctx *Context) Query(key string) string

Query returns the query string value for the given key.

func (*Context) Request

func (ctx *Context) Request() *http.Request

Request returns the underlying *http.Request.

func (*Context) ShouldBindBodyWith

func (ctx *Context) ShouldBindBodyWith(obj any, b httpBinding.BindingBody) error

ShouldBindBodyWith decodes the request body using the given binding. Useful for ProtoBuf and other non-JSON encodings.

func (*Context) ShouldBindJSON

func (ctx *Context) ShouldBindJSON(obj any) error

ShouldBindJSON decodes the JSON request body into obj.

func (*Context) ShouldBindQuery

func (ctx *Context) ShouldBindQuery(obj any) error

ShouldBindQuery binds query string parameters into obj using the form binding.

func (*Context) Status

func (ctx *Context) Status(code int)

Status writes the given HTTP status code without a body.

func (*Context) Writer

func (ctx *Context) Writer() http.ResponseWriter

Writer returns the underlying http.ResponseWriter.

type ErrHandlerContextFunc

type ErrHandlerContextFunc func(*Context) error

ErrHandlerContextFunc is a handler that returns an error for uniform error handling.

type HandlerContextFunc

type HandlerContextFunc func(*Context)

HandlerContextFunc is a middleware/handler that receives a custom Context.

func NewAuthMiddleware

func NewAuthMiddleware(svc *authService, pathSets ...[]string) HandlerContextFunc

NewAuthMiddleware returns a HandlerContextFunc that validates requests using the given authService.

type ListParams

type ListParams struct {
	Limit  int
	Offset int
	Sort   string
}

ListParams holds pagination and sorting parameters for list endpoints. Sort uses a leading "-" for descending, e.g. "-created_at".

type Permission

type Permission = authn.Permission

type RateLimitConfig

type RateLimitConfig struct {
	RequestsPerSecond int
	Burst             int
}

RateLimitConfig enables per-client rate limiting.

type Route

type Route struct {
	Method  string
	Path    string
	Handler ErrHandlerContextFunc
}

Route defines an HTTP route.

type Server

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

Server is an HTTP server instance.

func NewServer

func NewServer(cfg *Config) *Server

NewServer creates a new HTTP server with the given configuration.

func (*Server) Close

func (s *Server) Close() error

Close forcefully closes active HTTP connections after graceful draining fails.

func (*Server) Done

func (s *Server) Done() <-chan struct{}

Done is closed when the serving goroutine exits.

func (*Server) Group

func (s *Server) Group() *routerGroup

Group return the cgroup for this httpserver

func (*Server) MustRegisterRoutes

func (s *Server) MustRegisterRoutes(subGroup string, routes []Route)

func (*Server) RegisterOpenAPIHandlers

func (s *Server) RegisterOpenAPIHandlers(
	specification []byte,
	register func(router httpGin.IRouter),
) error

RegisterOpenAPIHandlers validates generated routes against their bundled specification before dispatching to the generated Gin adapter.

func (*Server) Shutdown

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

Shutdown stops accepting requests and waits for the serving goroutine.

func (*Server) Start

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

Start binds addr before returning and serves requests in the background.

func (*Server) StrictErrorHandlers

func (s *Server) StrictErrorHandlers() StrictErrorHandlers

StrictErrorHandlers returns callbacks using the server's error directory.

func (*Server) Wait

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

Wait returns the serving result or the context error.

type StrictErrorHandlers

type StrictErrorHandlers struct {
	RequestError  func(ctx *httpGin.Context, err error)
	HandlerError  func(ctx *httpGin.Context, err error)
	ResponseError func(ctx *httpGin.Context, err error)
}

StrictErrorHandlers adapts generated Strict Server errors to the shared error response boundary.

func NewStrictErrorHandlers

func NewStrictErrorHandlers(statusMapper response.HTTPStatusMapper) StrictErrorHandlers

NewStrictErrorHandlers returns callbacks for generated Strict Server options.

type User

type User = authn.Principal

type UserConfig

type UserConfig = authn.UserConfig

Directories

Path Synopsis
Package auth provides framework-independent authentication and authorization.
Package auth provides framework-independent authentication and authorization.
Package pprof provides a standalone HTTP server for Go runtime profiles.
Package pprof provides a standalone HTTP server for Go runtime profiles.

Jump to

Keyboard shortcuts

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