util

package
v0.16.10 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2020 License: Apache-2.0, BSD-3-Clause, MIT Imports: 22 Imported by: 22

Documentation

Overview

Package util contains web utils for APIs, clients and error handling

  • Copyright 2018 The Service Manager Authors *

  • Licensed under the Apache License, Version 2.0 (the "License");

  • you may not use this file except in compliance with the License.

  • You may obtain a copy of the License at *

  • http://www.apache.org/licenses/LICENSE-2.0 *

  • Unless required by applicable law or agreed to in writing, software

  • distributed under the License is distributed on an "AS IS" BASIS,

  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

  • See the License for the specific language governing permissions and

  • limitations under the License.

  • Copyright 2018 The Service Manager Authors *

  • Licensed under the Apache License, Version 2.0 (the "License");

  • you may not use this file except in compliance with the License.

  • You may obtain a copy of the License at *

  • http://www.apache.org/licenses/LICENSE-2.0 *

  • Unless required by applicable law or agreed to in writing, software

  • distributed under the License is distributed on an "AS IS" BASIS,

  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

  • See the License for the specific language governing permissions and

  • limitations under the License.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFoundInStorage error returned from storage when entity is not found
	ErrNotFoundInStorage = errors.New("not found")

	// ErrAlreadyExistsInStorage error returned from storage when entity has conflicting fields
	ErrAlreadyExistsInStorage = errors.New("unique constraint violation")

	// ErrConcurrentResourceModification error returned when concurrent resource updates are happening
	ErrConcurrentResourceModification = errors.New("another resource update happened concurrently. Please reattempt the update")

	// ErrInvalidNotificationRevision provided notification revision is not valid, must return http status GONE
	ErrInvalidNotificationRevision = errors.New("notification revision is not valid")
)

Functions

func BodyToBytes

func BodyToBytes(closer io.ReadCloser) ([]byte, error)

BodyToBytes of the request inside given struct

func BodyToObject

func BodyToObject(closer io.ReadCloser, object interface{}) error

BodyToObject of the request inside given struct

func BytesToObject

func BytesToObject(bytes []byte, object interface{}) error

BytesToObject converts the provided bytes to object and validates it

func ClientRequest added in v0.12.0

func ClientRequest(request *http.Request, client *http.Client) (*http.Response, error)

func GenerateCredential added in v0.11.0

func GenerateCredential() (string, error)

GenerateCredential generates a 32bit random string which can be used as broker platform credential

func HandleInterrupts

func HandleInterrupts(ctx context.Context, cancel context.CancelFunc)

HandleInterrupts handles process signal interrupts

func HandleResponseError

func HandleResponseError(response *http.Response) error

HandleResponseError builds an error from the given response

func HandleStorageError

func HandleStorageError(err error, entityName string) error

HandleStorageError handles storage errors by converting them to relevant HTTPErrors

func HasRFC3986ReservedSymbols

func HasRFC3986ReservedSymbols(input string) bool

HasRFC3986ReservedSymbols returns true if input contains any reserver characters as defined in RFC3986 section oidc_authn.oidc_authn

func ListAll added in v0.6.0

func ListAll(ctx context.Context, doRequest DoRequestFunc, url string, items interface{}) error

ListAll retrieves all the objects from the given url by loading all the pages items should be a pointer to a slice, that will be populated with all the items doRequest function executes the HTTP request, it is responsible for authentication

func NewJSONResponse

func NewJSONResponse(code int, value interface{}) (*web.Response, error)

NewJSONResponse turns plain object into a byte array representing JSON value and wraps it in web.Response

func NewJSONResponseWithHeaders added in v0.9.8

func NewJSONResponseWithHeaders(code int, value interface{}, additionalHeaders map[string]string) (*web.Response, error)

func NewLocationResponse added in v0.14.0

func NewLocationResponse(operationID, resourceID, resourceBaseURL string) (*web.Response, error)

func RequestBodyToBytes

func RequestBodyToBytes(request *http.Request) ([]byte, error)

RequestBodyToBytes reads the request body and returns []byte with its content or an error if the media type is unsupported or if the body is not a valid JSON

func SendRequest

func SendRequest(ctx context.Context, doRequest DoRequestFunc, method, url string, params map[string]string, body interface{}) (*http.Response, error)

SendRequest sends a request to the specified client and the provided URL with the specified parameters and body.

func SendRequestWithHeaders added in v0.1.11

func SendRequestWithHeaders(ctx context.Context, doRequest DoRequestFunc, method, url string, params map[string]string, body interface{}, headers map[string]string) (*http.Response, error)

SendRequestWithHeaders sends a request to the specified client and the provided URL with the specified parameters, body and headers.

func StartInWaitGroup added in v0.3.2

func StartInWaitGroup(f func(), group *sync.WaitGroup)

func StartInWaitGroupWithContext added in v0.3.2

func StartInWaitGroupWithContext(ctx context.Context, f func(ctx context.Context), group *sync.WaitGroup)

func ToRFCNanoFormat added in v0.7.1

func ToRFCNanoFormat(timestamp time.Time) string

ToRFCNanoFormat converts a time.Time timestamp to RFC3339Nano format

func Tsprintf added in v0.15.1

func Tsprintf(tmpl string, data map[string]interface{}) (string, error)

tsprintf stands for "template Sprintf" and fills the specified templated string with the provided data

func WriteError

func WriteError(ctx context.Context, err error, writer http.ResponseWriter)

WriteError sends a JSON containing the error to the response writer

func WriteJSON

func WriteJSON(writer http.ResponseWriter, code int, value interface{}) error

WriteJSON writes a JSON value and sets the specified HTTP Status code

Types

type DoRequestFunc

type DoRequestFunc func(request *http.Request) (*http.Response, error)

DoRequestFunc is an alias for any function that takes an http request and returns a response and error

type DoRequestWithClientFunc added in v0.12.0

type DoRequestWithClientFunc func(request *http.Request, client *http.Client) (*http.Response, error)

type EmptyResponseBody added in v0.1.2

type EmptyResponseBody struct{}

EmptyResponseBody represents an empty response body value

type ErrBadRequestStorage added in v0.1.6

type ErrBadRequestStorage struct {
	Cause error
}

ErrBadRequestStorage represents a storage error that should be translated to http.StatusBadRequest

func (*ErrBadRequestStorage) Error added in v0.3.0

func (e *ErrBadRequestStorage) Error() string

type ErrForeignKeyViolation added in v0.9.0

type ErrForeignKeyViolation struct {
	Entity          string
	ReferenceEntity string
}

ErrForeignKeyViolation represents a foreign key constraint storage error that should be translated to a user-friendly http.StatusBadRequest

func (*ErrForeignKeyViolation) Error added in v0.9.0

func (e *ErrForeignKeyViolation) Error() string

type HTTPError

type HTTPError struct {
	ErrorType   string `json:"error,omitempty"`
	Description string `json:"description,omitempty"`
	StatusCode  int    `json:"-"`
}

HTTPError is an error type that provides error details that Service Manager error handlers would propagate to the client

func ToHTTPError added in v0.10.0

func ToHTTPError(ctx context.Context, err error) *HTTPError

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error HTTPError should implement error

type InputValidator

type InputValidator interface {
	Validate() error
}

InputValidator should be implemented by types that need input validation check. For a reference refer to pkg/types

type ListIterator added in v0.6.0

type ListIterator struct {
	// DoRequest function executes the HTTP request, it is responsible for authentication
	DoRequest DoRequestFunc
	// URL is the address of the resource to list
	URL string
	// contains filtered or unexported fields
}

ListIterator lists the objects from the given url by loading one page at a time

func (*ListIterator) Next added in v0.6.0

func (li *ListIterator) Next(ctx context.Context, items interface{}, maxItems int) (more bool, count int64, err error)

Next loads the next page of items items should be a pointer to a slice, that will be populated with the items from the current page, if nil, only the total number is returned maxItems is the maximum numbe of items to load with the next page, -1 - use server default, 0 - just get the count more is true if there are more items count is the total number of items, -1 if not available

type StateContext added in v0.9.8

type StateContext struct {
	Context context.Context
}

StateContext is a Context which only holds values. Its Deadline(), Done() and Err() implementations have been stubbed out. Such a StateContext implementation is needed for scenarios where a request context needs to be copied and not derived, so as to not have to worry about being canceled by it's parent.

func (StateContext) Deadline added in v0.9.8

func (StateContext) Deadline() (deadline time.Time, ok bool)

func (StateContext) Done added in v0.9.8

func (StateContext) Done() <-chan struct{}

func (StateContext) Err added in v0.9.8

func (StateContext) Err() error

func (StateContext) Value added in v0.9.8

func (sc StateContext) Value(key interface{}) interface{}

type UnsupportedQueryError added in v0.1.9

type UnsupportedQueryError struct {
	Message string
}

UnsupportedQueryError is an error to show that the provided query cannot be executed

func (*UnsupportedQueryError) Error added in v0.1.9

func (uq *UnsupportedQueryError) Error() string

Directories

Path Synopsis
Code generated by counterfeiter.
Code generated by counterfeiter.

Jump to

Keyboard shortcuts

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