webserver

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: GPL-3.0 Imports: 20 Imported by: 0

README

server/webserver

Import path: github.com/InsideGallery/core/server/webserver

webserver provides Fiber-backed HTTP server helpers plus core-owned request, response, route, middleware, and outbound client contracts.

Main APIs

  • Config and GetEnvConfig(prefix...): HTTP server configuration. Defaults use the APP prefix.
  • New(cfg): creates a Server with a configured Fiber app.
  • Server.Run(ctx) and MustRun(ctx): run Fiber with graceful shutdown hooks.
  • Options, NewRuntime, and Runtime.Run(ctx): core-owned runtime wrapper.
  • Router, RouteHandler, RouteRequest, and RouteResponse: route contracts that avoid exposing Fiber to route callbacks.
  • NewFiberRouter(router): adapts a Fiber router to the core-owned router.
  • Middleware and RouteMiddleware: chain Fiber handlers or core-owned route handlers.
  • NewFiberApp(name): creates a Fiber app with the package error handler.
  • RegisterProbes and RegisterProbesWithState: install /healthz, /readyz, /livez, and /startupz.
  • Response, ErrorResponse, Pagination, and response helper functions.
  • NewStandardClient(client): adapts a net/http-compatible client to the core-owned Client contract.

Usage

cfg, err := webserver.GetEnvConfig()
if err != nil {
	return err
}

server := webserver.New(cfg)
webserver.RegisterProbes(server.App)
server.App.Get("/ping", func(c fiber.Ctx) error {
	return c.JSON(webserver.GetSuccessResponse("ok"))
})

return server.Run(ctx)

Configuration

Default environment variables are APP_ADDR, APP_HOST, APP_SCHEME, APP_NAME, APP_MONITOR_ADDR, and APP_SHUTDOWN_TIMEOUT. Pass a custom prefix to GetEnvConfig("api") to read variables such as API_ADDR.

Operational Notes

This package exposes Fiber for server composition. Server.Run registers SIGINT, SIGTERM, and SIGQUIT shutdown handlers through oslistener, marks the profiler state ready before serving, and uses DefaultShutdownTimeout when no timeout is configured.

Documentation

Index

Constants

View Source
const (
	// EnvPrefix is the default environment variable prefix for HTTP server config.
	EnvPrefix = "APP"

	// DefaultShutdownTimeout is the default graceful shutdown timeout.
	DefaultShutdownTimeout = 10 * time.Second
)
View Source
const ReadBufferSize = 16384

Variables

View Source
var ErrInternal = errors.New("internal error")
View Source
var ErrorHandler = func(c fiber.Ctx, err error) error {
	return c.Status(http.StatusInternalServerError).JSON(Response{
		Ok: false,
		Error: &ErrorResponse{
			Message: err.Error(),
			Code:    0,
		},
	})
}

Functions

func NewFiberApp

func NewFiberApp(name string) *fiber.App

func RegisterHealthz deprecated added in v1.1.0

func RegisterHealthz(router fiber.Router)

RegisterHealthz adds probe endpoints to the router.

Deprecated: use RegisterProbes.

func RegisterProbes added in v1.1.0

func RegisterProbes(router fiber.Router)

RegisterProbes adds GET /healthz, /readyz, /livez, and /startupz endpoints.

func RegisterProbesWithState added in v1.1.0

func RegisterProbesWithState(router fiber.Router, state *profiler.State)

RegisterProbesWithState adds probe endpoints backed by explicit profiler state.

Types

type Chain deprecated

type Chain func(h fiber.Handler) fiber.Handler

Chain single sequence

Deprecated: use core-owned Client/Runtime contracts for new code that does not need Fiber middleware.

type Client added in v1.1.0

type Client interface {
	Do(ctx context.Context, req HTTPRequest) (HTTPResponse, error)
}

Client executes HTTP requests without exposing net/http request and response values.

type Config added in v1.1.0

type Config struct {
	Address          string                     `env:"_ADDR" envDefault:":8080"`
	Host             string                     `env:"_HOST" envDefault:"localhost:8080"`
	Scheme           string                     `env:"_SCHEME" envDefault:"http"`
	Name             string                     `env:"_NAME" envDefault:"server"`
	MonitorAddr      string                     `env:"_MONITOR_ADDR" envDefault:":8011"`
	ShutdownTimeout  time.Duration              `env:"_SHUTDOWN_TIMEOUT" envDefault:"10s"`
	ShutdownListener *oslistener.SignalListener `env:"-"`
	ProfilerState    *profiler.State            `env:"-"`
}

Config holds HTTP server configuration.

func GetEnvConfig added in v1.1.0

func GetEnvConfig(prefix ...string) (*Config, error)

GetEnvConfig reads HTTP server configuration from environment variables.

type ErrorResponse

type ErrorResponse struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

func (ErrorResponse) MarshalEasyJSON

func (v ErrorResponse) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (ErrorResponse) MarshalJSON

func (v ErrorResponse) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*ErrorResponse) UnmarshalEasyJSON

func (v *ErrorResponse) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*ErrorResponse) UnmarshalJSON

func (v *ErrorResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

type FiberRouter added in v1.1.1

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

FiberRouter adapts Fiber routers to the core-owned Router contract.

func NewFiberRouter added in v1.1.1

func NewFiberRouter(router fiber.Router) *FiberRouter

NewFiberRouter wraps a Fiber router with the core-owned Router contract.

func (*FiberRouter) Handle added in v1.1.1

func (r *FiberRouter) Handle(method string, path string, handler RouteHandler)

Handle registers one route on the wrapped Fiber router.

type HTTPClient deprecated

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is the legacy net/http client boundary.

Deprecated: use StandardClient with Request and Response for a core-owned contract.

type HTTPRequest added in v1.1.0

type HTTPRequest struct {
	Method string
	URL    string
	Header map[string][]string
	Body   []byte
}

HTTPRequest is the core-owned HTTP request shape for outbound web calls.

type HTTPResponse added in v1.1.0

type HTTPResponse struct {
	StatusCode int
	Header     map[string][]string
	Body       []byte
}

HTTPResponse is the core-owned HTTP response shape for outbound web calls.

type Middleware

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

Middleware contains methods to call before handle request

func NewMiddleware

func NewMiddleware(c ...Chain) *Middleware

NewMiddleware return new natsmiddleware

func (*Middleware) AddChain

func (m *Middleware) AddChain(c Chain)

AddChain add natsmiddleware to execute

func (*Middleware) Copy

func (m *Middleware) Copy() *Middleware

Copy return copied sequence

func (*Middleware) Merge

func (m *Middleware) Merge(middlewares ...*Middleware)

Merge merge logmiddlewares into current

func (*Middleware) Then

func (m *Middleware) Then(h fiber.Handler) fiber.Handler

Then return router handler

type Options added in v1.1.1

type Options struct {
	Address          string
	Host             string
	Scheme           string
	Name             string
	MonitorAddr      string
	ShutdownTimeout  time.Duration
	ShutdownListener *oslistener.SignalListener
	ProfilerState    *profiler.State
	InitRoutes       RouteInitializer
}

Options is the core-owned input for creating a web server runtime.

type Pagination

type Pagination struct {
	Total   int `json:"total"`
	Page    int `json:"page"`
	Pages   int `json:"pages"`
	PerPage int `json:"per_page"`
}

func (Pagination) MarshalEasyJSON

func (v Pagination) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (Pagination) MarshalJSON

func (v Pagination) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*Pagination) UnmarshalEasyJSON

func (v *Pagination) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*Pagination) UnmarshalJSON

func (v *Pagination) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

type Response

type Response struct {
	Data       interface{}    `json:"data,omitempty"`
	Error      *ErrorResponse `json:"error,omitempty"`
	Pagination *Pagination    `json:"pagination,omitempty"`
	Ok         bool           `json:"ok"`
}

func GetResponseWithError

func GetResponseWithError(err error, code int) *Response

func GetSuccessResponse

func GetSuccessResponse(data interface{}) *Response

func GetSuccessResponseList

func GetSuccessResponseList(data interface{}, total, page, perPage int) *Response

func (Response) MarshalEasyJSON

func (v Response) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (Response) MarshalJSON

func (v Response) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*Response) UnmarshalEasyJSON

func (v *Response) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*Response) UnmarshalJSON

func (v *Response) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

type RouteChain added in v1.1.0

type RouteChain func(h RouteHandler) RouteHandler

RouteChain composes core-owned route handlers.

type RouteHandler added in v1.1.1

type RouteHandler func(ctx context.Context, req RouteRequest) (RouteResponse, error)

RouteHandler handles inbound HTTP requests without exposing Fiber context values.

type RouteInitializer added in v1.1.1

type RouteInitializer func(ctx context.Context, router Router) error

RouteInitializer configures routes through a core-owned router.

type RouteMiddleware added in v1.1.0

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

RouteMiddleware contains core-owned route middleware chains.

func NewRouteMiddleware added in v1.1.0

func NewRouteMiddleware(chains ...RouteChain) *RouteMiddleware

NewRouteMiddleware returns middleware for core-owned route handlers.

func (*RouteMiddleware) AddChain added in v1.1.0

func (m *RouteMiddleware) AddChain(chain RouteChain)

AddChain appends a core-owned route middleware chain.

func (*RouteMiddleware) Copy added in v1.1.0

func (m *RouteMiddleware) Copy() *RouteMiddleware

Copy returns a copy of the route middleware chain.

func (*RouteMiddleware) Merge added in v1.1.0

func (m *RouteMiddleware) Merge(middlewares ...*RouteMiddleware)

Merge appends chains from other route middleware values.

func (*RouteMiddleware) Then added in v1.1.0

func (m *RouteMiddleware) Then(handler RouteHandler) RouteHandler

Then wraps the route handler with all configured route chains.

type RouteRequest added in v1.1.1

type RouteRequest struct {
	Method      string
	Path        string
	OriginalURL string
	Header      map[string][]string
	Query       map[string]string
	Body        []byte
}

RouteRequest is the core-owned inbound HTTP request shape for route callbacks.

type RouteResponse added in v1.1.1

type RouteResponse struct {
	StatusCode int
	Header     map[string][]string
	Body       []byte
}

RouteResponse is the core-owned outbound HTTP response shape for route callbacks.

type Router added in v1.1.1

type Router interface {
	Handle(method string, path string, handler RouteHandler)
}

Router registers HTTP routes without exposing Fiber router values.

type RunResult added in v1.1.1

type RunResult struct {
	Name    string
	Address string
}

RunResult is the core-owned result for a completed web server run.

type Runtime added in v1.1.1

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

Runtime wraps the Fiber-backed server behind core-owned lifecycle methods.

func NewRuntime added in v1.1.1

func NewRuntime(options Options) *Runtime

NewRuntime creates a server runtime from core-owned options.

func (*Runtime) Run added in v1.1.1

func (r *Runtime) Run(ctx context.Context) (RunResult, error)

Run starts the server and returns a core-owned result when it stops.

type Server added in v1.1.0

type Server struct {
	App *fiber.App
	// contains filtered or unexported fields
}

Server wraps fiber.App with graceful shutdown support.

func New added in v1.1.0

func New(cfg *Config) *Server

New creates a new HTTP server with the given configuration.

func (*Server) MustRun added in v1.1.0

func (s *Server) MustRun(ctx context.Context)

MustRun starts the server and exits the process on failure.

func (*Server) Run added in v1.1.0

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

Run starts the Fiber server and blocks until shutdown.

type StandardClient added in v1.1.0

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

StandardClient adapts a legacy HTTPClient to the core-owned Client contract.

func NewStandardClient added in v1.1.0

func NewStandardClient(client HTTPClient) *StandardClient

NewStandardClient wraps a net/http-compatible client with the core-owned Client contract.

func (*StandardClient) Do added in v1.1.0

Do executes a request and returns a core-owned response.

Directories

Path Synopsis
Package mock_webserver is a generated GoMock package.
Package mock_webserver is a generated GoMock package.

Jump to

Keyboard shortcuts

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