httpu

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2021 License: MIT Imports: 33 Imported by: 8

README

httpu

HTTP server and protocol utilities

Installation

go get -u github.com/moisespsena-go/httpu

See example for usage.

Documentation

Index

Constants

View Source
const (
	HeaderXRequestedWith  = "X-Requested-With"
	HeaderXRequestedFrame = "X-Requested-Frame"

	RequestedByActionFormFrame = "Action"
)

Variables

View Source
var (
	// DefaultKeepAliveIdleInterval specifies how long connection can be idle
	// before sending keepalive message.
	DefaultKeepAliveIdleInterval = 15 * time.Minute
	// DefaultKeepAliveCount specifies maximal number of keepalive messages
	// sent before marking connection as dead.
	DefaultKeepAliveCount = 8
	// DefaultKeepAliveInterval specifies how often retry sending keepalive
	// messages when no response is received.
	DefaultKeepAliveInterval = 5 * time.Second
)
View Source
var (
	ErrNoListenersFound = errors.New("No listeners found")
)

Functions

func Fallback

func Fallback(handlers ...http.Handler) http.Handler

func GetUrl

func GetUrl(r *http.Request) string

func HttpScheme

func HttpScheme(r *http.Request) (scheme string)

func IsActionFormRequest

func IsActionFormRequest(r *http.Request) bool

func IsXhrRequest

func IsXhrRequest(r *http.Request) bool

func NewResponseWriter

func NewResponseWriter(w http.ResponseWriter) *responseWriter

func NewTeeResponseWriter

func NewTeeResponseWriter(w http.ResponseWriter, tee ...io.Writer) *teeResponseWriter

func PopPrefix

func PopPrefix(ctx context.Context, pth string) context.Context

func Prefix

func Prefix(ctx context.Context) string

func PrefixHandler

func PrefixHandler(prefix string, handler http.Handler, defaultHandler ...http.Handler) http.Handler

func PrefixR

func PrefixR(r *http.Request) string

func PushPrefix

func PushPrefix(ctx context.Context, pth string) context.Context

func PushPrefixR

func PushPrefixR(r *http.Request, pth string) *http.Request

func Redirect

func Redirect(w http.ResponseWriter, r *http.Request, url string, status int, force ...bool)

func RedirectHeader

func RedirectHeader(headerName string, w http.ResponseWriter, r *http.Request, url string, status int, force ...bool)

func RemoteIP

func RemoteIP(r *http.Request) (ip net.IP)

func ServeContent

func ServeContent(w http.ResponseWriter, r *http.Request, name string, modtime time.Time, content io.Reader, sizeFunc func() (int64, error))

ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to DetectContentType. The name is otherwise unused; in particular it can be empty and is never sent in the response.

If modtime is not the zero time or Unix epoch, ServeContent includes it in a Last-Modified header in the response. If the request includes an If-Modified-Since header, ServeContent uses modtime to decide whether the content needs to be sent at all.

The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size.

If the caller has set w's ETag header formatted per RFC 7232, section 2.3, ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.

Note that *os.File implements the io.ReadSeeker interface. if name is empty, filename is unknown. (used for mime type, before sniffing) if modtime.IsZero(), modtime is unknown. content must be seeked to the beginning of the file. The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.

func SetPrefix

func SetPrefix(ctx context.Context, pth string) context.Context

func SetPrefixR

func SetPrefixR(r *http.Request, pth string) *http.Request

func StripPrefix

func StripPrefix(w http.ResponseWriter, r *http.Request, handler http.Handler, prefix string, slashPermanentRedirect bool)

func StripStaticPrefix

func StripStaticPrefix(prefix string, h http.Handler) http.Handler

StripStaticPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h.

func URL

func URL(r *http.Request, pth ...string) string

func URLScheme

func URLScheme(r *http.Request, scheme string, pth ...string) string

func WsScheme

func WsScheme(r *http.Request) (scheme string)

func WsURL

func WsURL(r *http.Request, pth ...string) string

Types

type Addr

type Addr string

func (Addr) CreateListener

func (a Addr) CreateListener() (net.Listener, error)

func (Addr) IsUnix

func (a Addr) IsUnix() bool

func (Addr) Network

func (a Addr) Network() (net string, addr string)

func (Addr) Port

func (a Addr) Port() int

func (Addr) UnixPath

func (a Addr) UnixPath() string

type Config

type Config struct {
	Listeners []ListenerConfig

	Prefix                        string
	RequestPrefixHeader           string `mapstructure:"request_prefix_header" yaml:"request_prefix_header"`
	DisableStripRequestPrefix     bool   `mapstructure:"disable_strip_request_prefix" yaml:"disable_strip_request_prefix"`
	DisableSlashPermanentRedirect bool   `mapstructure:"disable_slash_permanent_redirect" yaml:"disable_slash_permanent_redirect"`
	MaxPostSize                   int64  `mapstructure:"max_post_size" yaml:"max_post_size"`
	UnlimitedPostSize             bool   `mapstructure:"unlimited_request_size" yaml:"unlimited_post_size"`
	NotFoundDisabled              bool   `mapstructure:"not_found_disabled" yaml:"not_found_disabled"`
}

type ContextKey

type ContextKey int
const (
	DefaultUriPrefixHeader = "X-Uri-Prefix"

	CtxPrefix ContextKey = 1
)

type FallbackHandlers

type FallbackHandlers []http.Handler

func (*FallbackHandlers) Add

func (this *FallbackHandlers) Add(handler ...http.Handler)

func (FallbackHandlers) ServeHTTP

func (this FallbackHandlers) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Http2Config

type Http2Config struct {
	Disabled bool
	Config   *http2.Server
}

type KeepAliveConfig

type KeepAliveConfig struct {
	Duration time.Duration
	Value    string `mapstructure:"str" yaml:"str"`
}

KeepAliveConfig TCP keep alive duration. A duration string is a possibly signed value (seconds) or signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

func (KeepAliveConfig) Get

func (ka KeepAliveConfig) Get() (dur time.Duration, err error)

type KeepAliveListener

type KeepAliveListener struct {
	net.Listener

	// DefaultKeepAliveCount specifies maximal number of keepalive messages
	// sent before marking connection as dead.
	KeepAliveCount int
	// DefaultKeepAliveIdleInterval specifies how long connection can be idle
	// before sending keepalive message.
	KeepAliveIdleInterval time.Duration
	// DefaultKeepAliveInterval specifies how often retry sending keepalive
	// messages when no response is received.
	KeepAliveInterval time.Duration
}

func NewKeepAliveListener

func NewKeepAliveListener(listener net.Listener) *KeepAliveListener

func (KeepAliveListener) Accept

func (ln KeepAliveListener) Accept() (net.Conn, error)

type Listener

type Listener struct {
	net.Listener

	Server    *http.Server
	KeepAlive time.Duration
	Tls       *TlsConfig

	Log logging.Logger
	// contains filtered or unexported fields
}

func (*Listener) Accept

func (l *Listener) Accept() (con net.Conn, err error)

func (*Listener) Close

func (l *Listener) Close() (err error)

func (*Listener) Connections

func (l *Listener) Connections() (cons []net.Conn)

func (*Listener) IsRunning

func (l *Listener) IsRunning() bool

func (*Listener) ListenAndServe

func (l *Listener) ListenAndServe() error

func (*Listener) Setup

func (l *Listener) Setup() error

func (*Listener) Shutdown

func (l *Listener) Shutdown(ctx context.Context) (err error)

func (*Listener) ShutdownLog

func (l *Listener) ShutdownLog(ctx context.Context) (err error)

func (*Listener) Start

func (l *Listener) Start(done func()) (stop task.Stoper, err error)

func (*Listener) Stop

func (l *Listener) Stop()

type ListenerConfig

type ListenerConfig struct {
	Addr  Addr
	Tls   *TlsConfig
	Http2 Http2Config

	// DefaultKeepAliveCount specifies maximal number of keepalive messages
	// sent before marking connection as dead.
	KeepAliveCount int
	// DefaultKeepAliveIdleInterval specifies how long connection can be idle
	// before sending keepalive message.
	KeepAliveIdleInterval *KeepAliveConfig
	// DefaultKeepAliveInterval specifies how often retry sending keepalive
	// messages when no response is received.
	KeepAliveInterval *KeepAliveConfig

	Timeouts TimeoutsConfig `mapstructure:"timeouts" yaml:"timeouts"`
}

func (*ListenerConfig) CreateServer

func (cfg *ListenerConfig) CreateServer() (s *http.Server, err error)

type Listeners

type Listeners []*Listener

func (Listeners) Tasks

func (l Listeners) Tasks() task.Slice

type PrefixHandlers

type PrefixHandlers []struct {
	// contains filtered or unexported fields
}

func (PrefixHandlers) Get

func (this PrefixHandlers) Get(uri string) http.Handler

func (PrefixHandlers) ServeHTTP

func (this PrefixHandlers) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*PrefixHandlers) Set

func (this *PrefixHandlers) Set(prefix string, handler http.Handler)

func (*PrefixHandlers) With

func (this *PrefixHandlers) With(prefix string, handler http.Handler)

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	// WroteHeader returns if has sent header to the client.
	WroteHeader() bool
	// Wrote returns if has sent bytes to the client.
	Wrote() bool
	// Status returns the HTTP status of the request, or 0 if one has not
	// yet been sent.
	Status() int
	// BytesWritten returns the total number of bytes sent to the client.
	BytesWritten() int
	// Unwrap returns the original proxied target.
	Unwrap() http.ResponseWriter
}

func ResponseWriterOf

func ResponseWriterOf(w http.ResponseWriter) (wd ResponseWriter)

type Server

type Server struct {
	Config  *Config
	Handler http.Handler
	// contains filtered or unexported fields
}

func NewServer

func NewServer(cfg *Config, handler http.Handler) *Server

func (*Server) AddTask

func (s *Server) AddTask(t ...task.Task)

func (*Server) Close

func (s *Server) Close() error

func (*Server) GetPostSetup

func (s *Server) GetPostSetup() []func(s *Server) error

func (*Server) GetPostShutdown

func (s *Server) GetPostShutdown() []func()

func (*Server) GetPreSetup

func (s *Server) GetPreSetup() []func(s *Server) error

func (*Server) InitListeners

func (s *Server) InitListeners() (err error)

func (*Server) Listeners

func (s *Server) Listeners() []*Listener

func (*Server) OnListener

func (s *Server) OnListener(f ...func(lis *Listener))

func (*Server) PostSetup

func (s *Server) PostSetup(f ...func(s *Server) error)

func (*Server) PostShutdown

func (s *Server) PostShutdown(f ...func())

func (*Server) PostShutdownE

func (s *Server) PostShutdownE(f ...func() error)

func (*Server) PreSetup

func (s *Server) PreSetup(f ...func(s *Server) error)

func (*Server) Prepare

func (s *Server) Prepare() (err error)

func (*Server) Run

func (s *Server) Run() (err error)

func (*Server) SetLog

func (s *Server) SetLog(log logging.Logger)

func (*Server) Setup

func (s *Server) Setup() (err error)

func (*Server) Shutdown

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

func (*Server) Start

func (s *Server) Start(done func()) (stop task.Stoper, err error)

type TeeResponseWriter

type TeeResponseWriter interface {
	http.ResponseWriter
	// Tee causes the response body to be written to the given io.Writer in
	// addition to proxying the writes through. Only one io.Writer can be
	// tee'd to at once: setting a second one will overwrite the first.
	// Writes will be sent to the proxy before being written to this
	// io.Writer. It is illegal for the tee'd writer to be modified
	// concurrently with writes.
	Tee(io.Writer)
}

func TeeResponseWriterOf

func TeeResponseWriterOf(w http.ResponseWriter) (wd TeeResponseWriter)

type TimeoutsConfig

type TimeoutsConfig struct {
	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body.
	//
	// Because ReadTimeout does not let Handlers make per-request
	// decisions on each request body's acceptable deadline or
	// upload rate, most users will prefer to use
	// ReadHeaderTimeout. It is valid to use them both.
	ReadTimeout time.Duration `mapstructure:"read_timeout" yaml:"read_timeout"`

	// ReadHeaderTimeout is the amount of time allowed to read
	// request headers. The connection's read deadline is reset
	// after reading the headers and the Handler can decide what
	// is considered too slow for the body. If ReadHeaderTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" yaml:"read_header_timeout"`

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	WriteTimeout time.Duration `mapstructure:"write_timeout" yaml:"write_timeout"`

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	IdleTimeout time.Duration `mapstructure:"idle_timeout" yaml:"idle_timeout"`

	// 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.
	// If zero, DefaultMaxHeaderBytes is used.
	MaxHeaderBytes int `mapstructure:"max_header_bytes" yaml:"max_header_bytes"`
}

type TlsConfig

type TlsConfig struct {
	Generate    *tlsgen.Config `mapstructure:"generate" yaml:"generate"`
	CertFile    string         `mapstructure:"cert_file" yaml:"cert_file"`
	KeyFile     string         `mapstructure:"key_file" yaml:"key_file"`
	NPNDisabled bool
}

func (*TlsConfig) Valid

func (cfg *TlsConfig) Valid() bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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