startup_http

package
v2.4.39 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License: MIT Imports: 31 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CustomTypes = map[reflect.Type]Setter{
	reflect.TypeOf(time.Time{}): setterTime,
}

Type registry for custom setters. Only modify in your modules init function.

View Source
var MapErrorToStatusCode = func(err error) int {
	switch {
	case errors.Is(err, sql.ErrNoRows):
		return http.StatusNotFound

	default:
		return http.StatusInternalServerError
	}
}

MapErrorToStatusCode maps an error to a status code. The default implementation converts sql.ErrNoRows into status code 404, and returns http.StatusInternalServerError in all other cases.

You can set this variable to do your own custom error mapping.

View Source
var WriteError = func(ctx context.Context, writer http.ResponseWriter, statusCode int, err error) {
	LoggerOf(ctx).Warnf("Writing response error: %s", err)

	if statusCode == 0 {
		statusCode = MapErrorToStatusCode(err)
	}

	WriteJSON(ctx, writer, statusCode, ErrorResponse{
		Status:     statusCode,
		ErrorValue: err.Error(),
	})
}

WriteError formats an error value. The default implementation wraps the error text into a ErrorResponse object and serializes it to json.

You can set this variable to do your own custom error mapping.

Functions

func ExtractAndCall

func ExtractAndCall(target interface{}, w http.ResponseWriter, r *http.Request, params httprouter.Params, handler func() (interface{}, error))

ExtractAndCall extracts and validates the path and request parameters before calling the given method.

func ExtractAndCallWithBody

func ExtractAndCallWithBody(
	target interface{},
	body interface{},
	w http.ResponseWriter,
	r *http.Request,
	params httprouter.Params,
	handler func() (interface{}, error),
)

ExtractAndCallWithBody parses the body, path and request parameters and then calls the given handler function.

func ExtractParameters

func ExtractParameters(target interface{}, r *http.Request, params httprouter.Params) error

ExtractParameters parses the 'path' parameters as well as the 'query' parameters into the given object. Returns an error, if parsing failed.

func Map

func Map(tag string, source Source, target interface{}) error

Runs a mapping operation on the given target. The target must be a pointer to a struct.

func RegisterSignalHandlerForServer

func RegisterSignalHandlerForServer(server *http.Server) <-chan struct{}

func WithPrometheusMetrics added in v2.4.11

func WithPrometheusMetrics(s string) admin.RouteConfig

func WriteBody

func WriteBody(ctx context.Context, writer http.ResponseWriter, statusCode int, contentType string, content []byte)

func WriteJSON

func WriteJSON(ctx context.Context, w http.ResponseWriter, status int, value interface{})

func WriteResponseValue

func WriteResponseValue(ctx context.Context, w http.ResponseWriter, value interface{}, err error)

Types

type Config

type Config struct {
	// name for the service. Will be used in the admin panel
	Name string

	// Routing configuration. You can use the supplied router or
	// return your own handler.
	Routing func(*httprouter.Router) http.Handler

	// Extra admin handlers to register on the admin page
	AdminHandlers []admin.RouteConfig

	// Registers a shutdown handler for the http server. If not set,
	// a default signal handler for clean shutdown on SIGINT and SIGTERM is used.
	RegisterSignalHandlerForServer func(*http.Server) <-chan struct{}

	// Wrap the http server with this middleware in the end. A good example would
	// be to use a tracing middleware at this point.
	UseMiddleware HttpMiddleware
}

type ErrorResponse

type ErrorResponse struct {
	Status     int    `json:"status"`
	ErrorValue string `json:"error"`
}

func (ErrorResponse) Error

func (err ErrorResponse) Error() string

type HTTPOptions

type HTTPOptions struct {
	Address string `long:"http-address" default:":3080" description:"Address to listen on."`

	TLSKeyFile  string `long:"http-tls-key" description:"Private key file to enable SSL support."`
	TLSCertFile string `long:"http-tls-cert" description:"Certificate file to enable SSL support."`

	DisableAdminRedirect bool   `long:"http-disable-admin-redirect" description:"Disable admin redirect on /"`
	DisableAuth          bool   `long:"http-disable-admin-auth" description:"Disable basic auth"`
	BasicAuthUsername    string `long:"http-admin-username" default:"admin" description:"Basic auth username for admin panel."`
	BasicAuthPassword    string `long:"http-admin-password" default:"bingo" description:"Basic auth password for admin panel."`

	AccessLog           string `long:"http-access-log" description:"Write http access log to a file. Defaults to stdout."`
	AccessLogAdminRoute bool   `long:"http-access-log-admin-route" description:"If enabled, admin route requests will also be logged."`
}

func (HTTPOptions) Serve

func (opts HTTPOptions) Serve(config Config)

type HttpMiddleware

type HttpMiddleware func(http.Handler) http.Handler

func AdaptMiddlewareForHttp

func AdaptMiddlewareForHttp(middleware HttpRouterMiddleware) HttpMiddleware

Takes a httprouter.Handle middleware and wraps it so it can be used with http.Handler functions.

type HttpRouterMiddleware

type HttpRouterMiddleware func(httprouter.Handle) httprouter.Handle

func AdaptMiddlewareForHttpRouter

func AdaptMiddlewareForHttpRouter(w HttpMiddleware) HttpRouterMiddleware

Takes a normal http.Handler middleware and wraps it so it can be used with httprouter.Handle functions.

type MapSource

type MapSource map[string]string

Default implementation for a source that uses a simple string map for lookup.

func (MapSource) Get

func (m MapSource) Get(key string) (string, bool)

type ResponseValue

type ResponseValue struct {
	StatusCode int
	Headers    http.Header
	Body       interface{}
}

type Setter

type Setter func(value string, target reflect.Value) error

Take the given string value, converts it and assigns it to the target value. It is expected, that the target value.

type SlogRecoveryHandlerLogger added in v2.4.20

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

SlogRecoveryHandlerLogger implements the handlers.RecoveryHandlerLogger interface by logging panic details at slog.LevelError in JSON format.

func NewSlogRecoveryHandlerLogger added in v2.4.20

func NewSlogRecoveryHandlerLogger() *SlogRecoveryHandlerLogger

NewSlogRecoveryHandlerLogger creates and returns a new SlogRecoveryHandlerLogger.

func (*SlogRecoveryHandlerLogger) Println added in v2.4.20

func (l *SlogRecoveryHandlerLogger) Println(v ...interface{})

Println implements the handlers.RecoveryHandlerLogger interface. It receives the arguments from RecoveryHandler (typically panic_value, stack_trace_string) and logs them as structured JSON at slog.LevelError.

type Source

type Source interface {
	Get(key string) (string, bool)
}

A source returns a value for a given key. A source might be backed by a map or something else.

Jump to

Keyboard shortcuts

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