api

package module
v0.0.18 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2025 License: Unlicense Imports: 17 Imported by: 0

README

seahax.com/go/api

Utility for composing HTTP services.

import (
  "seahax.com/go/api"
  "seahax.com/go/api/log"
  "seahax.com/go/api/secure"
  "seahax.com/go/api/compress"
)

app := &api.API{}

// Add middleware
app.UseMiddleware(&log.Middleware{})
app.UseMiddleware(&secure.Middleware{})
app.UseMiddleware(&compress.Middleware{})

// Configure routes
app.HandleRoute(&api.Route{
  Pattern: "GET /hello",
  Handler: func(ctx *api.Context) {
    ctx.Response.WriteString("Hello, World!")
  },
})

// Listen and serve
app.BindAddress(":8080")

Documentation

Index

Constants

View Source
const (
	// Default listen address (127.0.0.1:8080).
	DefaultAddr string = "127.0.0.1:8080"

	// Default read timeout (5 minutes).
	DefaultReadTimeout time.Duration = 5 * time.Minute

	// Default read header timeout (30 seconds).
	DefaultReadHeaderTimeout time.Duration = 30 * time.Second

	// Default write timeout (10 minutes).
	DefaultWriteTimeout time.Duration = 10 * time.Minute

	// Default idle timeout (5 seconds).
	DefaultIdleTimeout time.Duration = 5 * time.Second
)

Variables

This section is empty.

Functions

This section is empty.

Types

type API added in v0.0.10

type API struct {

	// Global middleware handlers applied to all requests handled by this API,
	// even if no route is matched. Middleware is executed in the order it is
	// added.
	MiddlewareHandlers []MiddlewareHandler

	// Optional request Context Logger. If nil, then slog.Default() is used.
	Logger *slog.Logger

	// Optional callback that is called when a listener is created.
	Listening func(url string)

	// Optional callback that is called to handle server errors. If this is nil,
	// server errors will cause a panic.
	OnServerError func(err *ServerError)
	// contains filtered or unexported fields
}

A wrapper for the Go built-in net/http.Mux with quality-of-life enhancements like non-blocking server binding, graceful shutdown, and middleware support.

func (*API) BindAddress added in v0.0.10

func (i *API) BindAddress(addr string)

Bind this API to a new HTTP server listening on the given address. This call is non-blocking.

Listening

If Addr is empty, the listener will bind to DefaultAddr.

Errors

If the server fails and the API's Error field is non-nil, it will be called with the server and the error. If the Error field is nil, a panic will occur.

func (*API) BindServer added in v0.0.10

func (i *API) BindServer(server *http.Server)

Bind this API to the given HTTP server. This function is non-blocking. This function will mutate the given server's fields!

Defaults

Server fields will be updated as follows.

  • Handler is set to the API instance.
  • Addr is set to the final listener address.
  • If ReadTimeout is zero, DefaultReadTimeout is used.
  • If ReadHeaderTimeout is zero, DefaultReadHeaderTimeout is used.
  • If WriteTimeout is zero, DefaultWriteTimeout is used.
  • If IdleTimeout is zero, DefaultIdleTimeout is used.

Listening

If Addr is empty, the listener will bind to DefaultAddr.

TLS

If TLSConfig is non-nil, TLS is used.

Errors

If the server fails and the API's Error field is non-nil, it will be called with the server and the error. If the Error field is nil, a panic will occur.

func (*API) HandleGroup added in v0.0.10

func (i *API) HandleGroup(groupProvider GroupProvider, middlewareProviders ...MiddlewareProvider)

Add a group of routes to the API with optional middleware.

func (*API) HandleRoute added in v0.0.10

func (i *API) HandleRoute(routeProvider RouteProvider, middlewareProviders ...MiddlewareProvider)

Add a route to the API with optional middleware.

func (*API) ServeHTTP added in v0.0.10

func (i *API) ServeHTTP(writer http.ResponseWriter, request *http.Request)

func (*API) Shutdown added in v0.0.10

func (i *API) Shutdown() ShutdownError

Attempt to gracefully shutdown all servers that were started by the API. If a server does not shutdown within 10 seconds, it will be forcibly closed.

func (*API) UseMiddleware added in v0.0.10

func (i *API) UseMiddleware(providers ...MiddlewareProvider)

Use middleware in all requests handled by this API, even if no route is matched. Middleware is executed in the order it is added.

type Context

type Context struct {
	// A logger specific to this request context.
	Logger *slog.Logger
	// The associated HTTP request.
	Request *http.Request
	// The associated HTTP response.
	Response *Response
}

Context for an API request, containing request-specific data and convenience methods.

Use the NewContext constructor to create Context instances.

func GetContext added in v0.0.7

func GetContext(api *API, request *http.Request) *Context

Retrieve the api.Context from the net/http.Request. This will panic if the request was not handled by the given API instance and has no associated api.Context.

func NewContext added in v0.0.7

func NewContext(api *API, writer http.ResponseWriter, request *http.Request) *Context

Create a new API request Context, and associate it with the given net/http.Request so that it can be retrieved given the same API and request pointers.

type Group

type Group struct {
	Prefix             string
	MiddlewareHandlers []MiddlewareHandler
	Routes             []*Route
	// contains filtered or unexported fields
}

A group of routes with a common prefix and shared middleware.

func (*Group) GetGroup added in v0.0.7

func (g *Group) GetGroup() (prefix string, routes []*Route)

func (*Group) HandleGroup added in v0.0.8

func (g *Group) HandleGroup(groupProvider GroupProvider, middlewareProviders ...MiddlewareProvider)

Add a sub-group of routes to the group with optional middleware.

func (*Group) HandleRoute added in v0.0.8

func (g *Group) HandleRoute(routeProvider RouteProvider, middlewareProviders ...MiddlewareProvider)

Add a route to the group with optional route specific middleware.

func (*Group) Use

func (g *Group) Use(providers ...MiddlewareProvider)

Use middleware in all requests handled by routes in this group. These will only be applied when a route in this group (or a sub-group) is matched. Middleware is executed in the order it is added.

type GroupProvider added in v0.0.7

type GroupProvider interface {
	GetGroup() (prefix string, routes []RouteProvider)
}

Provides a group of routes.

type MiddlewareHandler added in v0.0.11

type MiddlewareHandler func(ctx *Context, next func())

type MiddlewareProvider added in v0.0.11

type MiddlewareProvider interface {
	GetMiddleware() MiddlewareHandler
}

MiddlewareProvider is a request handler that can process requests before and/or after passing control to the next handler in the chain.

type Pattern

type Pattern struct {
	Method string
	Domain string
	Path   string
}

A parsed ServeMux route pattern.

func ParsePattern

func ParsePattern(pattern string) *Pattern

Parse a ServeMux route pattern string.

func (*Pattern) String

func (p *Pattern) String() string

Return the string representation of the parsed pattern.

type Response

type Response struct {

	// The underlying [io.Writer] for writing response body data. This can be
	// wrapped by middleware to provide features like compression.
	Writer io.Writer
	// contains filtered or unexported fields
}

Response accessor with convenience methods for writing common responses.

Use the NewResponse constructor to create Response instances.

func NewResponse added in v0.0.7

func NewResponse(
	responseWriter http.ResponseWriter,
	request *http.Request,
) *Response

Create a new Response.

func (*Response) Error

func (r *Response) Error(status int)

Write an error message with the given status code to the response. The plain text message will be the standard HTTP status text for the code.

func (*Response) ErrorMessage

func (r *Response) ErrorMessage(status int, message string)

Write an plain text error message with the given status code to the response.

func (*Response) Header added in v0.0.7

func (r *Response) Header() http.Header

Returns the response header.

func (*Response) RegisterOnBeforeWriteHeader added in v0.0.7

func (r *Response) RegisterOnBeforeWriteHeader(callback func(int))

Register a callback that is called before the response header is written. This can be used to perform last-minute modifications to the header, log information, or decide whether to replace the response Writer.

func (*Response) SetCookie

func (r *Response) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header to the response.

func (*Response) Write added in v0.0.13

func (r *Response) Write(b []byte) (int, error)

func (*Response) WriteHeader added in v0.0.7

func (r *Response) WriteHeader(statusCode int)

Write the header and status code to the response. This should only be called once per response. After it is called, the header and status code can no longer be modified.

func (*Response) WriteJSON

func (r *Response) WriteJSON(v any) error

Write the given value as JSON to the response.

func (*Response) WriteString added in v0.0.12

func (r *Response) WriteString(s string) error

func (*Response) Written added in v0.0.7

func (r *Response) Written() bool

Returns true if WriteHeader has been called for this response.

type Route

type Route struct {
	Pattern string
	Handler RouteHandler
}

A single endpoint which maps a pattern to a handler function.

func (*Route) GetRoute added in v0.0.7

func (r *Route) GetRoute() *Route

Returns route pattern and handler.

type RouteHandler added in v0.0.11

type RouteHandler = func(ctx *Context)

type RouteProvider added in v0.0.7

type RouteProvider interface {
	GetRoute() *Route
}

Provides a single route.

type ServerError

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

Passed to the API.OnServerError callback when an net/http.Server fails that was bound to an API.

func (*ServerError) Error

func (e *ServerError) Error() string

func (*ServerError) Server

func (e *ServerError) Server() *http.Server

type ShutdownError

type ShutdownError []*ServerError

Returned by API.Shutdown if one or more servers failed to shutdown cleanly.

func (ShutdownError) Error

func (e ShutdownError) Error() string

func (ShutdownError) Unwrap

func (e ShutdownError) Unwrap() []error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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