net

package
v2.18.0-prerelease Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2023 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultMaxRetries is used as the maximum retries in the backoff when Backoff is called.
	DefaultMaxRetries = 5
	// DefaultMinimumCycle is used as the minimum cycle duration when Backoff is called.
	DefaultMinimumCycle = 100 * time.Millisecond
	// DefaultCeiling is used as the maximum wait time between executions when Backoff is called.
	DefaultCeiling = 15 * time.Second
)
View Source
const (
	// HeaderAuthorization is the HTTP header for Authorization
	HeaderAuthorization = "Authorization"
	// HeaderContentType is the HTTP header Content Type
	HeaderContentType = "Content-Type"
	// HeaderContentLength is the HTTP header name for specifying length of the body in bytes
	HeaderContentLength = "Content-Length"
	// HeaderAccept is the HTTP header Accept
	HeaderAccept = "Accept"
	// HeaderAllow is the HTTP header for Allow which indicates which methods are allowed on the URL
	HeaderAllow = "Allow"
	// HeaderHost specifies the domain name of the server
	HeaderHost = "Host"
	// HeaderKeepAlive allows the sender to hint about how the connection may be used to set a timeout and max # of requests
	HeaderKeepAlive = "Keep-Alive"
	// HeaderConnection controls whether or not the network connection stays open after the transaction finishes
	HeaderConnection = "Connection"
	// HeaderUserAgent allows network peers to identify the application type, os, software vendor or version of requesting software user agent
	HeaderUserAgent = "User-Agent"
	// HeaderCacheControl specifies directives for caching mechanisms in both requests and responses
	HeaderCacheControl = "Cache-Control"
	// HeaderContentEncoding specifies how the payload of the http message is encoded
	HeaderContentEncoding = "Content-Encoding"

	// MIMEAppJSON is the HTTP value application/json for ContentType
	MIMEAppJSON = "application/json"
	// MIMEAppFormURLEncoded is the HTTP value application/x-www-form-urlencoded for ContentType
	MIMEAppFormURLEncoded = "application/x-www-form-urlencoded"
	// CacheControlNone is the Cache-Control value for disabling cacheing
	CacheControlNone = "no-cache"
)
View Source
const (
	DefaultMinWorkers    = 300
	DefaultBufferedTasks = 10000
	DefaultIdleTimeout   = 24 * time.Hour
)

Sensible Defaults

Variables

This section is empty.

Functions

func Backoff

func Backoff(f F) error

Backoff Executes the passed function with exponential back off up to a maximum a number of tries with the minimum amount of time per cycle using default values.

func BackoffExtended

func BackoffExtended(f F, maxTries int, minimumCycle time.Duration, maxCycle time.Duration) error

BackoffExtended Executes the passed function with exponential back off up to a maximum a number of tries with the minimum amount of time per cycle.

func CalculateBackoff

func CalculateBackoff(r *rand.Rand, attempt int, minimumCycle time.Duration, maxCycle time.Duration) time.Duration

CalculateBackoff returns a duration for exponential backoff

func GetInt16Value

func GetInt16Value(values url.Values, key string, def int16) int16

GetInt16Value attempts to retrieve the value from url.Values, otherwise returns the default

func GetInt32Value

func GetInt32Value(values url.Values, key string, def int32) int32

GetInt32Value attempts to retrieve the value from url.Values, otherwise returns the default

func GetInt64Value

func GetInt64Value(values url.Values, key string, def int64) int64

GetInt64Value attempts to retrieve the value from url.Values, otherwise returns the default

func GetInt8Value

func GetInt8Value(values url.Values, key string, def int8) int8

GetInt8Value attempts to retrieve the value from url.Values, otherwise returns the default

func GetIntValue

func GetIntValue(values url.Values, key string, def int) int

GetIntValue attempts to retrieve the value from url.Values, otherwise returns the default

func GetUint16Value

func GetUint16Value(values url.Values, key string, def uint16) uint16

GetUint16Value attempts to retrieve the value from url.Values, otherwise returns the default

func GetUint32Value

func GetUint32Value(values url.Values, key string, def uint32) uint32

GetUint32Value attempts to retrieve the value from url.Values, otherwise returns the default

func GetUint64Value

func GetUint64Value(values url.Values, key string, def uint64) uint64

GetUint64Value attempts to retrieve the value from url.Values, otherwise returns the default

func GetUint8Value

func GetUint8Value(values url.Values, key string, def uint8) uint8

GetUint8Value attempts to retrieve the value from url.Values, otherwise returns the default

func GetUintValue

func GetUintValue(values url.Values, key string, def uint) uint

GetUintValue attempts to retrieve the value from url.Values, otherwise returns the default

func NewBadStatusError

func NewBadStatusError(method string, url string, status int) errors.TracerError

NewBadStatusError for a http request

func RandomizeIPArray

func RandomizeIPArray(a []nnet.IP) []nnet.IP

RandomizeIPArray for basic load balancing

func ValidateIPv4Address

func ValidateIPv4Address(s string) bool

ValidateIPv4Address with or without a port and return a boolean indicating success.

func ValidateIPv6Address

func ValidateIPv6Address(s string) bool

ValidateIPv6Address with or without a port and return a boolean indicating success.

Types

type Address

type Address struct {
	Host    string
	Port    int
	IsIPv6  bool
	HasPort bool
}

Address of a remote host with port information. Does not handle Zones.

func NewAddressFromConnection

func NewAddressFromConnection(conn net.Conn) (*Address, error)

NewAddressFromConnection if the RemoteAddr is set to a valid address.

func ParseAddress

func ParseAddress(address string) (*Address, errors.TracerError)

ParseAddress from the passed string and return it.

func (*Address) MarshalString

func (addr *Address) MarshalString() (string, error)

MarshalString from the address.

func (*Address) Network

func (addr *Address) Network() string

Network implements net.Addr interface

func (*Address) String

func (addr *Address) String() string

func (*Address) UnmarshalString

func (addr *Address) UnmarshalString(s string) error

UnmarshalString to an address

type BadStatusError

type BadStatusError struct {
	Method string
	URL    string
	Status int
	// contains filtered or unexported fields
}

BadStatusError is returned when a request results in a non-successful status code ![200-299]

func (*BadStatusError) Error

func (err *BadStatusError) Error() string

func (*BadStatusError) Trace

func (err *BadStatusError) Trace() []string

Trace for this error.

type DoHTTPRequest

type DoHTTPRequest interface {
	// Do the request by sending the payload to the remote server and returning the response and any errors
	Do(*http.Request) (*http.Response, errors.TracerError)
	// DoWithContext the request by sending the payload to the remote server and returning the response and any errors
	// cancelling the request at the transport level when the context returns on it's 'Done' channel.
	DoWithContext(context.Context, *http.Request) (*http.Response, errors.TracerError)
	// AddCookieJar to http client to make cookies available to future requests
	AddCookieJar(http.CookieJar)
	// Cookies lists cookies in the jar
	Cookies(url *url.URL) []*http.Cookie
	// SetCookies adds cookies to the jar
	SetCookies(url *url.URL, cookies []*http.Cookie)
}

DoHTTPRequest provides an interface for an HTTP Client.

func NewHTTPRedirectClient

func NewHTTPRedirectClient(timeout time.Duration, logger log.Logger) DoHTTPRequest

NewHTTPRedirectClient is the default net/http client with headers being set on redirect

type F

type F func() error

F is a function that will be called sequentially

type GetListenerGetTask

type GetListenerGetTask interface {
	// GetListener for accepting connections.
	GetListener() (net.Listener, error)
	// GetTask to be executed in response to an inbound connection.
	GetTask(conn net.Conn) (dispatcher.Task, error)
}

GetListenerGetTask provides functions for getting a listener and a task from a connection.

type MockAddr

type MockAddr struct {
	SNetwork string
	Address  string
}

MockAddr implements the net.MockAddr interface

func (*MockAddr) Network

func (addr *MockAddr) Network() string

Network is the name of the network address

func (*MockAddr) String

func (addr *MockAddr) String() string

String form of the address

type MockConn

type MockConn struct {
	ID            int
	RAddress      net.Addr
	LAddress      net.Addr
	Closed        bool
	ReadComplete  bool
	ReadMultiple  bool
	Deadline      time.Time
	ReadDeadline  time.Time
	WriteDeadline time.Time
	ReadF         func(b []byte) (n int, err error)
	WriteF        func(b []byte) (n int, err error)
}

MockConn is a mock implementation of the io.ReadWriteCloser interface

func (*MockConn) Close

func (conn *MockConn) Close() error

Close sets the Closed attribute to true on the mock connection

func (*MockConn) LocalAddr

func (conn *MockConn) LocalAddr() net.Addr

LocalAddr returns a new mock Addr or the LAddress on the mock connection

func (*MockConn) Read

func (conn *MockConn) Read(b []byte) (n int, err error)

Read mocks reading to a connection

func (*MockConn) RemoteAddr

func (conn *MockConn) RemoteAddr() net.Addr

RemoteAddr returns a new mock Addr or the RAddress on the mock connection

func (*MockConn) SetDeadline

func (conn *MockConn) SetDeadline(t time.Time) error

SetDeadline is a no-op mock that returns nil

func (*MockConn) SetReadDeadline

func (conn *MockConn) SetReadDeadline(t time.Time) error

SetReadDeadline is a no-op mock that returns nil

func (*MockConn) SetWriteDeadline

func (conn *MockConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline is a no-op mock that returns nil

func (*MockConn) Write

func (conn *MockConn) Write(b []byte) (n int, err error)

Write mocks writing to a connection

type MockHTTPClient

type MockHTTPClient struct {
	DoReturn collection.Stack[interface{}]
	DoCalled collection.Stack[interface{}]
	// contains filtered or unexported fields
}

MockHTTPClient mocks the DoHTTPRequest interface

func NewMockHTTPClient

func NewMockHTTPClient(returnStackItems ...interface{}) *MockHTTPClient

NewMockHTTPClient returns a mocked version of the DoHTTPRequest interface

func (*MockHTTPClient) AddCookieJar

func (client *MockHTTPClient) AddCookieJar(jar http.CookieJar)

AddCookieJar to http client to make them available to all future requests

func (*MockHTTPClient) Cookies

func (client *MockHTTPClient) Cookies(url *url.URL) []*http.Cookie

Cookies lists cookies in the jar

func (*MockHTTPClient) Do

func (client *MockHTTPClient) Do(req *http.Request) (*http.Response, errors.TracerError)

Do returns the http.Response / error from the DoReturn stack and records the request on the DoCalled stack

func (*MockHTTPClient) DoCalledPop

func (client *MockHTTPClient) DoCalledPop() *http.Request

DoCalledPop pops the last http.Request from the DoCalled stack if it exists

func (*MockHTTPClient) DoWithContext

func (client *MockHTTPClient) DoWithContext(ctx context.Context, req *http.Request) (*http.Response, errors.TracerError)

DoWithContext returns the http.Response / error from the DoReturn stack and records the request on the DoCalled stack

func (*MockHTTPClient) SetCookies

func (client *MockHTTPClient) SetCookies(url *url.URL, cookies []*http.Cookie)

SetCookies adds cookies to the jar

type MockListener

type MockListener struct {
	Address       net.Addr
	GetConnection func() *MockConn
	AcceptError   error
}

MockListener is a mock implementation of the net.MockListener interface

func (*MockListener) Accept

func (listener *MockListener) Accept() (conn net.Conn, err error)

Accept returnes the MockConn and the AcceptError

func (*MockListener) Addr

func (listener *MockListener) Addr() net.Addr

Addr returns the listener's network address.

func (*MockListener) Close

func (listener *MockListener) Close() error

Close is a no-op.

type SimpleDoRequest

type SimpleDoRequest struct {
	DoFunc func(req *http.Request) (*http.Response, error)
	// contains filtered or unexported fields
}

SimpleDoRequest allows for providing a function as a client.

func (*SimpleDoRequest) AddCookieJar

func (m *SimpleDoRequest) AddCookieJar(jar http.CookieJar)

AddCookieJar to http client to make them available to all future requests

func (*SimpleDoRequest) Cookies

func (m *SimpleDoRequest) Cookies(url *url.URL) []*http.Cookie

Cookies lists cookies in the jar

func (*SimpleDoRequest) Do

Do implements DoHTTPRequest.Do

func (*SimpleDoRequest) DoWithContext

func (m *SimpleDoRequest) DoWithContext(ctx context.Context, req *http.Request) (*http.Response, errors.TracerError)

DoWithContext implements DoHTTPRequest.DoWithContext

func (*SimpleDoRequest) SetCookies

func (m *SimpleDoRequest) SetCookies(url *url.URL, cookies []*http.Cookie)

SetCookies adds cookies to the jar

type TCPServer

type TCPServer struct {
	MaxConsecutiveErrors int
	MaxWorkers           int

	Dispatcher dispatcher.Dispatcher
	// contains filtered or unexported fields
}

TCPServer serves as a base struct for all TCP service instances that listen on a Port.

func NewTCPServer

func NewTCPServer(maxConsecutiveErrors, maxWorkers int,
	getListenerGetTask GetListenerGetTask, logger log.Logger) *TCPServer

NewTCPServer that will exit listen on the number of MaxConsecutiveErrors specified and use the number of workers specified to asynchronously process incoming connections.

func (*TCPServer) Dispatch

func (server *TCPServer) Dispatch(task dispatcher.Task)

Dispatch a task using this TCPServer's worker pool.

func (*TCPServer) Listen

func (server *TCPServer) Listen() (chan bool, error)

Listen for incoming connection, wrap them using GetTask and execute them asynchronously.

func (*TCPServer) SetIdleTimeout

func (server *TCPServer) SetIdleTimeout(timeout time.Duration, onIdle func())

SetIdleTimeout and on idle handler for this server

Jump to

Keyboard shortcuts

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