http

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2020 License: MIT Imports: 16 Imported by: 63

Documentation

Index

Constants

View Source
const (
	FlorenceHeaderKey        = "X-Florence-Token"
	DownloadServiceHeaderKey = "X-Download-Service-Token"

	FlorenceCookieKey = "access_token"

	AuthHeaderKey    = "Authorization"
	UserHeaderKey    = "User-Identity"
	RequestHeaderKey = "X-Request-Id"

	DeprecatedAuthHeader = "Internal-Token"
	LegacyUser           = "legacyUser"
	BearerPrefix         = "Bearer "

	UserIdentityKey     = ContextKey("User-Identity")
	CallerIdentityKey   = ContextKey("Caller-Identity")
	RequestIdKey        = ContextKey("request-id")
	FlorenceIdentityKey = ContextKey("florence-id")
)

A list of common constants used across dp-net packages

View Source
const (
	LangEN = "en"
	LangCY = "cy"

	DefaultLang = LangEN

	LocaleCookieKey = "lang"
	LocaleHeaderKey = "LocaleCode"
)
View Source
const CollectionIDCookieKey = "collection"
View Source
const CollectionIDHeaderKey = "Collection-Id"
View Source
const LogHandlerKey string = "Log"
View Source
const RequestIDHandlerKey string = "RequestID"

Variables

View Source
var DefaultClient = &Client{
	MaxRetries: 10,
	RetryTime:  20 * time.Millisecond,

	HTTPClient: &http.Client{
		Timeout: 10 * time.Second,
		Transport: &http.Transport{
			DialContext: (&net.Dialer{
				Timeout: 5 * time.Second,
			}).DialContext,
			TLSHandshakeTimeout: 5 * time.Second,
			MaxIdleConns:        10,
			IdleConnTimeout:     30 * time.Second,
		},
	},
}

DefaultClient is a dp-net specific http client with sensible timeouts, exponential backoff, and a contextual dialer.

View Source
var SupportedLanguages = [2]string{LangEN, LangCY}

Functions

func AddAuthHeaders

func AddAuthHeaders(ctx context.Context, r *http.Request, serviceToken string)

AddAuthHeaders sets authentication headers for request

func AddDeprecatedHeader

func AddDeprecatedHeader(r *http.Request, token string)

AddDeprecatedHeader sets the deprecated header on the given request

func AddDownloadServiceTokenHeader

func AddDownloadServiceTokenHeader(r *http.Request, serviceToken string)

AddDownloadServiceTokenHeader sets the given download service token on the given request

func AddFlorenceHeader

func AddFlorenceHeader(r *http.Request, userAccessToken string)

AddFlorenceHeader sets the given user access token (florence token) token on the given request

func AddRequestIdHeader

func AddRequestIdHeader(r *http.Request, token string)

AddRequestIdHeader add header for given correlation ID

func AddServiceTokenHeader

func AddServiceTokenHeader(r *http.Request, serviceToken string)

AddServiceTokenHeader sets the given service token on the given request

func AddUserHeader

func AddUserHeader(r *http.Request, user string)

AddUserHeader sets the given user ID on the given request

func Caller

func Caller(ctx context.Context) string

Caller gets the caller identity from the context

func GetLangFromCookieOrDefault

func GetLangFromCookieOrDefault(c *http.Cookie) string

GetLangFromCookieOrDefault returns a language based on the lang cookie or if not valid defaults it

func GetLangFromSubDomain

func GetLangFromSubDomain(req *http.Request) string

GetLangFromSubDomain returns a language based on subdomain

func GetRequestId

func GetRequestId(ctx context.Context) string

GetRequestId gets the correlation id on the context

func HandlerRequestID

func HandlerRequestID(size int) func(http.Handler) http.Handler

HandlerRequestID is a wrapper which adds an X-Request-Id header if one does not yet exist

func IsCallerPresent

func IsCallerPresent(ctx context.Context) bool

IsCallerPresent determines if an identity is present on the given context.

func IsFlorenceIdentityPresent

func IsFlorenceIdentityPresent(ctx context.Context) bool

IsFlorenceIdentityPresent determines if a florence identity is present on the given context

func IsUserPresent

func IsUserPresent(ctx context.Context) bool

IsUserPresent determines if a user identity is present on the given context

func NewRequestID

func NewRequestID(size int) string

NewRequestID generates a random string of requested length

func SetCaller

func SetCaller(ctx context.Context, caller string) context.Context

SetCaller sets the caller identity on the context

func SetFlorenceHeader

func SetFlorenceHeader(ctx context.Context, r *http.Request)

SetFlorenceHeader sets a florence Header if the corresponding Identity key is in context

func SetFlorenceIdentity

func SetFlorenceIdentity(ctx context.Context, user string) context.Context

SetFlorenceIdentity sets the florence identity for authentication

func SetLocaleCode

func SetLocaleCode(req *http.Request) *http.Request

SetLocaleCode sets the Locale code used to set the language

func SetUser

func SetUser(ctx context.Context, user string) context.Context

SetUser sets the user identity on the context

func User

func User(ctx context.Context) string

User gets the user identity from the context

func WithRequestId

func WithRequestId(ctx context.Context, correlationId string) context.Context

WithRequestId sets the correlation id on the context

Types

type CheckRequester

type CheckRequester interface {
	CheckRequest(*http.Request) (context.Context, int, error)
}

CheckRequester is an interface to allow mocking of auth.CheckRequest

type Client

type Client struct {
	MaxRetries         int
	RetryTime          time.Duration
	PathsWithNoRetries map[string]bool
	HTTPClient         *http.Client
}

Client is an extension of the net/http client with ability to add timeouts, exponential backoff and context-based cancellation.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request) (*http.Response, error)

Do calls ctxhttp.Do with the addition of retries with exponential backoff

func (*Client) Get

func (c *Client) Get(ctx context.Context, url string) (*http.Response, error)

Get calls Do with a GET.

func (*Client) GetMaxRetries

func (c *Client) GetMaxRetries() int

GetMaxRetries gets the HTTP request maximum number of retries.

func (*Client) GetPathsWithNoRetries

func (c *Client) GetPathsWithNoRetries() (paths []string)

GetPathsWithNoRetries gets a list of paths that will HTTP request will not retry on error.

func (*Client) Head

func (c *Client) Head(ctx context.Context, url string) (*http.Response, error)

Head calls Do with a HEAD.

func (*Client) Post

func (c *Client) Post(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)

Post calls Do with a POST and the appropriate content-type and body.

func (*Client) PostForm

func (c *Client) PostForm(ctx context.Context, uri string, data url.Values) (*http.Response, error)

PostForm calls Post with the appropriate form content-type.

func (*Client) Put

func (c *Client) Put(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)

Put calls Do with a PUT and the appropriate content-type and body.

func (*Client) SetMaxRetries

func (c *Client) SetMaxRetries(maxRetries int)

SetMaxRetries sets HTTP request maximum number of retries.

func (*Client) SetPathsWithNoRetries

func (c *Client) SetPathsWithNoRetries(paths []string)

SetPathsWithNoRetries sets a list of paths that will HTTP request will not retry on error.

func (*Client) SetTimeout

func (c *Client) SetTimeout(timeout time.Duration)

SetTimeout sets HTTP request timeout.

type Clienter

type Clienter interface {
	SetTimeout(timeout time.Duration)
	SetMaxRetries(int)
	GetMaxRetries() int
	SetPathsWithNoRetries([]string)
	GetPathsWithNoRetries() []string

	Get(ctx context.Context, url string) (*http.Response, error)
	Head(ctx context.Context, url string) (*http.Response, error)
	Post(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)
	Put(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)
	PostForm(ctx context.Context, uri string, data url.Values) (*http.Response, error)

	Do(ctx context.Context, req *http.Request) (*http.Response, error)
}

Clienter provides an interface for methods on an HTTP Client.

func ClientWithListOfNonRetriablePaths

func ClientWithListOfNonRetriablePaths(c Clienter, paths []string) Clienter

ClientWithListOfNonRetriablePaths facilitates creating a client and setting a list of paths that should not be retried on failure.

func ClientWithTimeout

func ClientWithTimeout(c Clienter, timeout time.Duration) Clienter

ClientWithTimeout facilitates creating a client and setting request timeout.

func NewClient

func NewClient() Clienter

NewClient returns a copy of DefaultClient.

type ClienterMock

type ClienterMock struct {
	// DoFunc mocks the Do method.
	DoFunc func(ctx context.Context, req *http.Request) (*http.Response, error)

	// GetFunc mocks the Get method.
	GetFunc func(ctx context.Context, url string) (*http.Response, error)

	// GetMaxRetriesFunc mocks the GetMaxRetries method.
	GetMaxRetriesFunc func() int

	// GetPathsWithNoRetriesFunc mocks the GetPathsWithNoRetries method.
	GetPathsWithNoRetriesFunc func() []string

	// HeadFunc mocks the Head method.
	HeadFunc func(ctx context.Context, url string) (*http.Response, error)

	// PostFunc mocks the Post method.
	PostFunc func(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)

	// PostFormFunc mocks the PostForm method.
	PostFormFunc func(ctx context.Context, uri string, data url.Values) (*http.Response, error)

	// PutFunc mocks the Put method.
	PutFunc func(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)

	// SetMaxRetriesFunc mocks the SetMaxRetries method.
	SetMaxRetriesFunc func(in1 int)

	// SetPathsWithNoRetriesFunc mocks the SetPathsWithNoRetries method.
	SetPathsWithNoRetriesFunc func(in1 []string)

	// SetTimeoutFunc mocks the SetTimeout method.
	SetTimeoutFunc func(timeout time.Duration)
	// contains filtered or unexported fields
}

ClienterMock is a mock implementation of Clienter.

    func TestSomethingThatUsesClienter(t *testing.T) {

        // make and configure a mocked Clienter
        mockedClienter := &ClienterMock{
            DoFunc: func(ctx context.Context, req *http.Request) (*http.Response, error) {
	               panic("mock out the Do method")
            },
            GetFunc: func(ctx context.Context, url string) (*http.Response, error) {
	               panic("mock out the Get method")
            },
            GetMaxRetriesFunc: func() int {
	               panic("mock out the GetMaxRetries method")
            },
            GetPathsWithNoRetriesFunc: func() []string {
	               panic("mock out the GetPathsWithNoRetries method")
            },
            HeadFunc: func(ctx context.Context, url string) (*http.Response, error) {
	               panic("mock out the Head method")
            },
            PostFunc: func(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error) {
	               panic("mock out the Post method")
            },
            PostFormFunc: func(ctx context.Context, uri string, data url.Values) (*http.Response, error) {
	               panic("mock out the PostForm method")
            },
            PutFunc: func(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error) {
	               panic("mock out the Put method")
            },
            SetMaxRetriesFunc: func(in1 int)  {
	               panic("mock out the SetMaxRetries method")
            },
            SetPathsWithNoRetriesFunc: func(in1 []string)  {
	               panic("mock out the SetPathsWithNoRetries method")
            },
            SetTimeoutFunc: func(timeout time.Duration)  {
	               panic("mock out the SetTimeout method")
            },
        }

        // use mockedClienter in code that requires Clienter
        // and then make assertions.

    }

func (*ClienterMock) Do

func (mock *ClienterMock) Do(ctx context.Context, req *http.Request) (*http.Response, error)

Do calls DoFunc.

func (*ClienterMock) DoCalls

func (mock *ClienterMock) DoCalls() []struct {
	Ctx context.Context
	Req *http.Request
}

DoCalls gets all the calls that were made to Do. Check the length with:

len(mockedClienter.DoCalls())

func (*ClienterMock) Get

func (mock *ClienterMock) Get(ctx context.Context, url string) (*http.Response, error)

Get calls GetFunc.

func (*ClienterMock) GetCalls

func (mock *ClienterMock) GetCalls() []struct {
	Ctx context.Context
	URL string
}

GetCalls gets all the calls that were made to Get. Check the length with:

len(mockedClienter.GetCalls())

func (*ClienterMock) GetMaxRetries

func (mock *ClienterMock) GetMaxRetries() int

GetMaxRetries calls GetMaxRetriesFunc.

func (*ClienterMock) GetMaxRetriesCalls

func (mock *ClienterMock) GetMaxRetriesCalls() []struct {
}

GetMaxRetriesCalls gets all the calls that were made to GetMaxRetries. Check the length with:

len(mockedClienter.GetMaxRetriesCalls())

func (*ClienterMock) GetPathsWithNoRetries

func (mock *ClienterMock) GetPathsWithNoRetries() []string

GetPathsWithNoRetries calls GetPathsWithNoRetriesFunc.

func (*ClienterMock) GetPathsWithNoRetriesCalls

func (mock *ClienterMock) GetPathsWithNoRetriesCalls() []struct {
}

GetPathsWithNoRetriesCalls gets all the calls that were made to GetPathsWithNoRetries. Check the length with:

len(mockedClienter.GetPathsWithNoRetriesCalls())

func (*ClienterMock) Head

func (mock *ClienterMock) Head(ctx context.Context, url string) (*http.Response, error)

Head calls HeadFunc.

func (*ClienterMock) HeadCalls

func (mock *ClienterMock) HeadCalls() []struct {
	Ctx context.Context
	URL string
}

HeadCalls gets all the calls that were made to Head. Check the length with:

len(mockedClienter.HeadCalls())

func (*ClienterMock) Post

func (mock *ClienterMock) Post(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)

Post calls PostFunc.

func (*ClienterMock) PostCalls

func (mock *ClienterMock) PostCalls() []struct {
	Ctx         context.Context
	URL         string
	ContentType string
	Body        io.Reader
}

PostCalls gets all the calls that were made to Post. Check the length with:

len(mockedClienter.PostCalls())

func (*ClienterMock) PostForm

func (mock *ClienterMock) PostForm(ctx context.Context, uri string, data url.Values) (*http.Response, error)

PostForm calls PostFormFunc.

func (*ClienterMock) PostFormCalls

func (mock *ClienterMock) PostFormCalls() []struct {
	Ctx  context.Context
	URI  string
	Data url.Values
}

PostFormCalls gets all the calls that were made to PostForm. Check the length with:

len(mockedClienter.PostFormCalls())

func (*ClienterMock) Put

func (mock *ClienterMock) Put(ctx context.Context, url string, contentType string, body io.Reader) (*http.Response, error)

Put calls PutFunc.

func (*ClienterMock) PutCalls

func (mock *ClienterMock) PutCalls() []struct {
	Ctx         context.Context
	URL         string
	ContentType string
	Body        io.Reader
}

PutCalls gets all the calls that were made to Put. Check the length with:

len(mockedClienter.PutCalls())

func (*ClienterMock) SetMaxRetries

func (mock *ClienterMock) SetMaxRetries(in1 int)

SetMaxRetries calls SetMaxRetriesFunc.

func (*ClienterMock) SetMaxRetriesCalls

func (mock *ClienterMock) SetMaxRetriesCalls() []struct {
	In1 int
}

SetMaxRetriesCalls gets all the calls that were made to SetMaxRetries. Check the length with:

len(mockedClienter.SetMaxRetriesCalls())

func (*ClienterMock) SetPathsWithNoRetries

func (mock *ClienterMock) SetPathsWithNoRetries(in1 []string)

SetPathsWithNoRetries calls SetPathsWithNoRetriesFunc.

func (*ClienterMock) SetPathsWithNoRetriesCalls

func (mock *ClienterMock) SetPathsWithNoRetriesCalls() []struct {
	In1 []string
}

SetPathsWithNoRetriesCalls gets all the calls that were made to SetPathsWithNoRetries. Check the length with:

len(mockedClienter.SetPathsWithNoRetriesCalls())

func (*ClienterMock) SetTimeout

func (mock *ClienterMock) SetTimeout(timeout time.Duration)

SetTimeout calls SetTimeoutFunc.

func (*ClienterMock) SetTimeoutCalls

func (mock *ClienterMock) SetTimeoutCalls() []struct {
	Timeout time.Duration
}

SetTimeoutCalls gets all the calls that were made to SetTimeout. Check the length with:

len(mockedClienter.SetTimeoutCalls())

type ContextKey

type ContextKey string

ContextKey is an alias of type string

type Doer

type Doer = func(context.Context, *http.Client, *http.Request) (*http.Response, error)

type IdentityResponse

type IdentityResponse struct {
	Identifier string `json:"identifier"`
}

IdentityResponse represents the response from the identity service

type Params

type Params map[string]string

Params represents a generic map of key value pairs, expected by go-ns/audit Auditor.Record()

func (Params) Copy

func (originalParams Params) Copy() Params

Copy preserves the original params value (key value pair) but stores the data in a different reference address

type Server

type Server struct {
	http.Server
	Middleware             map[string]alice.Constructor
	MiddlewareOrder        []string
	Alice                  *alice.Chain
	CertFile               string
	KeyFile                string
	DefaultShutdownTimeout time.Duration
	HandleOSSignals        bool
}

Server is a http.Server with sensible defaults, which supports configurable middleware and timeouts, and shuts down cleanly on SIGINT/SIGTERM

func NewServer

func NewServer(bindAddr string, router http.Handler) *Server

NewServer creates a new server

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe sets up SIGINT/SIGTERM signals, builds the middleware chain, and creates/starts a http.Server instance

If CertFile/KeyFile are both set, the http.Server instance is started using ListenAndServeTLS. Otherwise ListenAndServe is used.

Specifying one of CertFile/KeyFile without the other will panic.

func (*Server) ListenAndServeTLS

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

ListenAndServeTLS sets KeyFile and CertFile, then calls ListenAndServe

func (*Server) Shutdown

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

Shutdown will gracefully shutdown the server, using a default shutdown timeout if a context is not provided.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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