httputil

package
v2.1.10 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrTimeout = errors.New("timed out waiting for the condition")

ErrTimeout is returned if SleepUntil condition isn't met.

Functions

func IsHTTPS

func IsHTTPS(r *http.Request) bool

func SleepUntil

func SleepUntil(backoff Backoff, condition ConditionFunc) error

SleepUntil waits for condition to succeeds.

Types

type Backoff

type Backoff struct {
	// The initial duration.
	Duration time.Duration
	// Maximum number of tries.
	MaxTries int
}

Backoff slices.Contains struct for retrying strategy.

type ConditionFunc

type ConditionFunc func() (done bool, err error)

ConditionFunc returns true if the condition is satisfied, or an error if the loop should be aborted.

type ErrorResponse

type ErrorResponse struct {
	Code      uint              `json:"code,omitempty" example:"400"`
	Message   string            `json:"message" example:"Bad request"`
	ErrorType string            `json:"error_type,omitempty" example:"invalid_scope"`
	Params    map[string]string `json:"params,omitempty"`
}

ErrorResponse provides HTTP error response.

func (ErrorResponse) Error

func (e ErrorResponse) Error() string

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient allows inserting either *http.Client or mock client.

type MockClient

type MockClient struct {
	DoFunc func(req *http.Request) (*http.Response, error)
}

MockClient is helper client for mock tests.

func (*MockClient) Do

func (m *MockClient) Do(req *http.Request) (*http.Response, error)

Do executes the HTTPClient interface Do function.

type Request

type Request struct {
	Method                 string
	URL                    string
	Body                   []byte
	Cookies                []*http.Cookie
	Headers                map[string]string
	BearerTokenFile        string
	OKCode                 []int
	Unmarshaler            func(data []byte, v any) error
	RetryOnContextDeadline bool
}

Request contains all relevant data for making http requst.

type Response

type Response struct {
	Body       []byte
	StatusCode int
	Headers    http.Header
}

Response contains basic fields extracted from http.Response.

func MakeRequest

func MakeRequest(ctx context.Context, request Request, output interface{}, client HTTPClient, backoff Backoff) (*Response, error)

MakeRequest is hihg level wrapper for http.Do with added functionality like retries and automatic response parsing.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/elisasre/go-common/v2/httputil"
)

func main() {
	// retry once in second, maximum retries 2 times
	backoff := httputil.Backoff{
		Duration: 1 * time.Second,
		MaxTries: 2,
	}

	type Out struct {
		Message string `json:"message"`
	}
	out := Out{}
	client := &http.Client{}
	ctx := context.Background()
	body, err := httputil.MakeRequest(
		ctx,
		httputil.Request{
			URL:    "https://ingress-api.csf.elisa.fi/healthz",
			Method: "GET",
			OKCode: []int{200},
		},
		&out,
		client,
		backoff,
	)

	fmt.Printf("%s\n%s\n%d\n%v\n", out.Message, body.Body, body.StatusCode, err)

	ctx, cancel := context.WithTimeout(ctx, 1*time.Millisecond)
	defer cancel()
	_, err = httputil.MakeRequest(
		ctx,
		httputil.Request{
			URL:    "https://ingress-api.csf.elisa.fi/healthz",
			Method: "GET",
			OKCode: []int{200},
		},
		&out,
		client,
		backoff,
	)

	fmt.Printf("%v", err)
}
Output:

pong
{"message":"pong","error":""}
200
<nil>
Get "https://ingress-api.csf.elisa.fi/healthz": context deadline exceeded

Jump to

Keyboard shortcuts

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