serv

package module
v0.2.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2024 License: BSD-3-Clause Imports: 18 Imported by: 8

README

serv

Latest release Build status Go Report Card Documentation

Package serv contains a server implementation based on http.Server, with sane and safe defaults.

go get github.com/go-pogo/serv
import "github.com/go-pogo/serv"

Documentation

Additional detailed documentation is available at pkg.go.dev

Created with

License

Copyright © 2021-2024 Roel Schut. All rights reserved.

This project is governed by a BSD-style license that can be found in the LICENSE file.

Documentation

Index

Examples

Constants

View Source
const (
	ErrMissingPort   errors.Msg = "missing port"
	ErrInvalidFormat errors.Msg = "invalid format"
)
View Source
const (
	ErrAlreadyStarted    errors.Msg = "server is already started"
	ErrUnstartedShutdown errors.Msg = "cannot shutdown server that is not started"
	ErrUnstartedClose    errors.Msg = "cannot close server that is not started"
)
View Source
const ErrHandlerIsNoRouteHandler errors.Msg = "server handler is not a RouteHandler"

Variables

This section is empty.

Functions

func BaseContext

func BaseContext(ctx context.Context) func(_ net.Listener) context.Context

BaseContext returns a function which returns the provided context.

func DefaultTLSConfig

func DefaultTLSConfig() *tls.Config

DefaultTLSConfig returns a modern preconfigured tls.Config.

func JoinHostPort

func JoinHostPort(host string, port Port) string

JoinHostPort uses net.JoinHostPort to combine host and port into a network address of the form "host:port". If host contains a colon, as found in literal IPv6 addresses, then JoinHostPort returns "[host]:port".

func ServerName

func ServerName(ctx context.Context) string

ServerName gets the server's name from context values. Its return value may be an empty string.

func WriteJSON added in v0.2.0

func WriteJSON(w http.ResponseWriter, v any) error

WriteJSON encodes v to JSON and writes it to w.

Types

type CertificateLoader

type CertificateLoader interface {
	LoadCertificate() (*tls.Certificate, error)
}

CertificateLoader loads a tls.Certificate from any source.

type Config

type Config struct {
	// ReadTimeout is the maximum duration for reading the entire request,
	// including the body.
	// See http.Server for additional information.
	ReadTimeout time.Duration `default:"5s"`

	// ReadHeaderTimeout is the amount of time allowed to read request headers.
	// See http.Server for additional information.
	ReadHeaderTimeout time.Duration `default:"2s"`

	// WriteTimeout is the maximum duration before timing out writes of the
	// response.
	// See http.Server for additional information.
	WriteTimeout time.Duration `default:"10s"`

	// IdleTimeout is the maximum amount of time to wait for the next request
	// when keep-alives are enabled.
	// See http.Server for additional information.
	IdleTimeout time.Duration `default:"120s"`

	// ShutdownTimeout is the maximum duration for shutting down the server and
	// waiting for all connections to be closed.
	ShutdownTimeout time.Duration `default:"60s"`

	// MaxHeaderBytes controls the maximum number of bytes the server will read
	// parsing the request header's keys and values, including the request line.
	// It does not limit the size of the request body.
	// See http.Server for additional information.
	MaxHeaderBytes uint64 `default:"10240"` // data.Bytes => 10 KiB
}

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with default values.

func (*Config) ApplyTo

func (cfg *Config) ApplyTo(s *http.Server)

ApplyTo applies the Config fields values to *http.Server s.

func (*Config) Default

func (cfg *Config) Default()

Default sets any zero values on Config to a default non-zero value.

type DefaultLogger

type DefaultLogger struct {
	*log.Logger
}

func (*DefaultLogger) ServerClose

func (l *DefaultLogger) ServerClose(name string)

func (*DefaultLogger) ServerShutdown

func (l *DefaultLogger) ServerShutdown(name string)

func (*DefaultLogger) ServerStart

func (l *DefaultLogger) ServerStart(name, addr string)

type Logger

type Logger interface {
	ServerStart(name, addr string)
	ServerShutdown(name string)
	ServerClose(name string)
}

func NopLogger

func NopLogger() Logger

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithBaseContext added in v0.2.0

func WithBaseContext(ctx context.Context) Option

func WithDefaultLogger added in v0.2.0

func WithDefaultLogger() Option

func WithHandler added in v0.2.0

func WithHandler(h http.Handler) Option

func WithLogger

func WithLogger(l Logger) Option

func WithMiddleware

func WithMiddleware(mw ...middleware.Wrapper) Option

WithMiddleware adds the middleware.Middleware to an internal list. When the Server is started, it's Handler is wrapped with this middleware.

func WithName

func WithName(name string) Option

WithName adds the server's name as value to the request's context.

func WithOptions

func WithOptions(opts ...Option) Option

WithOptions wraps multiple Option(s) into a single Option.

func WithRoutes

func WithRoutes(reg ...RoutesRegisterer) Option

func WithTLS

func WithTLS(conf *tls.Config, opts ...TLSOption) Option

type Port

type Port uint16

func ParsePort

func ParsePort(s string) (Port, error)
Example
port, err := ParsePort(":8080")
if err != nil {
	log.Fatal(err)
}
fmt.Println(port)
Output:

8080

func SplitHostPort

func SplitHostPort(hostport string) (string, Port, error)

SplitHostPort uses net.SplitHostPort to split a network address of the form "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port" into host or host%zone and Port.

Example
host, port, err := SplitHostPort("localhost:8080")
if err != nil {
	log.Fatal(err)
}
fmt.Println(host, port)
Output:

localhost 8080

func (Port) Addr

func (p Port) Addr() string

func (Port) MarshalText

func (p Port) MarshalText() ([]byte, error)

func (*Port) Set added in v0.2.0

func (p *Port) Set(s string) (err error)

func (Port) String

func (p Port) String() string

func (*Port) UnmarshalText

func (p *Port) UnmarshalText(text []byte) (err error)

type PortParseError

type PortParseError struct {
	// Cause is the underlying error. It is never nil.
	Cause error
	// Input string that triggered the error
	Input string
}

func (*PortParseError) Error

func (p *PortParseError) Error() string

func (*PortParseError) Unwrap

func (p *PortParseError) Unwrap() error

type Route added in v0.2.0

type Route struct {
	// Name of the route.
	Name string
	// Method used to handle the route.
	Method string
	// Pattern to access the route.
	Pattern string
	// Handler is the http.Handler that handles the route.
	Handler http.Handler
}

func (Route) ServeHTTP added in v0.2.0

func (r Route) ServeHTTP(wri http.ResponseWriter, req *http.Request)

type RouteHandler added in v0.2.0

type RouteHandler interface {
	HandleRoute(route Route)
}

RouteHandler handles routes.

type Router added in v0.2.0

type Router interface {
	RouteHandler
	http.Handler
}

Router is a http.Handler that can handle routes.

type RoutesRegisterer added in v0.2.0

type RoutesRegisterer interface {
	RegisterRoutes(r RouteHandler)
}

RoutesRegisterer registers routes to a RouteHandler.

type RoutesRegistererFunc added in v0.2.0

type RoutesRegistererFunc func(r RouteHandler)

RoutesRegistererFunc registers routes to a RouteHandler.

func (RoutesRegistererFunc) RegisterRoutes added in v0.2.0

func (fn RoutesRegistererFunc) RegisterRoutes(r RouteHandler)

type ServeMux added in v0.2.0

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

ServeMux is a http.ServeMux wrapper which implements the Router interface. See http.ServeMux for more information.

func NewServeMux added in v0.2.0

func NewServeMux() *ServeMux

NewServeMux creates a new ServeMux and is ready to be used.

func (*ServeMux) HandleRoute added in v0.2.0

func (mux *ServeMux) HandleRoute(route Route)

type Server

type Server struct {

	// Config to apply to the server, DefaultConfig if nil.
	Config *Config
	// Addr optionally specifies the TCP address for the server to listen on.
	// See net.Dial for details of the address format.
	// See http.Server for additional information.
	Addr string
	// Handler to invoke, http.DefaultServeMux if nil.
	Handler http.Handler
	// contains filtered or unexported fields
}

Server is a wrapper for http.Server. The zero value is safe and ready to use, and will apply safe defaults on starting the server.

func New

func New(opts ...Option) (*Server, error)

New creates a new Server. DefaultConfig is applied to it when no other Config is provided as option.

func (*Server) Close

func (srv *Server) Close() error

Close immediately closes all active net.Listeners and any connections in state http.StateNew, http.StateActive, or http.StateIdle. For a graceful shutdown, use Shutdown. It is a wrapper for http.NewClient.Close.

func (*Server) IsStarted

func (srv *Server) IsStarted() bool

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

ListenAndServe is a wrapper for http.Server.ListenAndServe.

func (*Server) ListenAndServeTLS

func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS is a wrapper for http.Server.ListenAndServeTLS.

func (*Server) Name

func (srv *Server) Name() string

func (*Server) Run

func (srv *Server) Run() error

func (*Server) Serve

func (srv *Server) Serve(l net.Listener) error

Serve is a wrapper for http.Server.Serve.

func (*Server) ServeTLS

func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error

ServeTLS is a wrapper for http.Server.ServeTLS.

func (*Server) Shutdown

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

Shutdown gracefully shuts down the server without interrupting any active connections. Just like the underlying http.Server, Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If ShutdownTimeout is set and/or the provided context expires before the shutdown is complete, Shutdown returns the context's error. Otherwise, it returns any error returned from closing the Server's underlying net.Listener(s).

func (*Server) With added in v0.2.0

func (srv *Server) With(opts ...Option) error

type TLSConfig

type TLSConfig struct {
	CaCertFile string `env:"" flag:"tls-cacert"`
	CertFile   string `env:"" flag:"tls-cert"`
	KeyFile    string `env:"" flag:"tls-key"`

	// VerifyClient enables mutual tls authentication.
	VerifyClient bool `env:""`
	// InsecureSkipVerify disabled all certificate verification and should only
	// be used for testing.
	InsecureSkipVerify bool `env:""`
}

func (TLSConfig) ApplyTo added in v0.2.0

func (tc TLSConfig) ApplyTo(conf *tls.Config) error

func (TLSConfig) IsZero

func (tc TLSConfig) IsZero() bool

type TLSKeyPair

type TLSKeyPair struct {
	CertFile string
	KeyFile  string
}

TLSKeyPair contains the paths to a public/private key pair of files.

func (TLSKeyPair) ApplyTo added in v0.2.0

func (kp TLSKeyPair) ApplyTo(conf *tls.Config) error

func (TLSKeyPair) LoadCertificate

func (kp TLSKeyPair) LoadCertificate() (*tls.Certificate, error)

LoadCertificate reads and parses the key pair files with tls.LoadX509KeyPair. The files must contain PEM encoded data.

type TLSOption

type TLSOption interface {
	ApplyTo(conf *tls.Config) error
}

type TLSPemBlocks

type TLSPemBlocks struct {
	Cert []byte
	Key  []byte
}

certPEMBlock, keyPEMBlock

func (TLSPemBlocks) ApplyTo added in v0.2.0

func (pb TLSPemBlocks) ApplyTo(conf *tls.Config) error

func (TLSPemBlocks) LoadCertificate

func (pb TLSPemBlocks) LoadCertificate() (*tls.Certificate, error)

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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