client

package module
v0.0.0-...-fbaf9a3 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2024 License: MIT Imports: 11 Imported by: 1

README

http.client

A module to help make HTTP requests to REST APIs.

example

package main

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

	"github.com/alexferl/golib/http/client"
)

func before(req *http.Request) error {
	fmt.Printf("sending request to: %s\n", req.URL.String())
	return nil
}

func main() {
	hc := client.DefaultHTTPClient()
	hc.Timeout = 42 * time.Second // set default timeout for every requests
	contentType := "application/json"
	auth := "token"
	url := "https://example.com"
	headers := map[string]string{
		"X-Custom-Header1": "1",
		"X-Custom-Header2": "2",
	}

	c := client.New(
		client.WithHTTPClient(hc),
		client.WithBaseURL(url),
		client.WithAuthBearer(auth),
		client.WithContentType(contentType),
		client.WithHeaders(headers),
		client.WithBeforeRequest(before),
	)

	// Creating and sending requests manually
	req, err := c.NewRequest(context.Background(), http.MethodGet, "/users/1", nil)
	if err != nil {
		panic(err)
	}

	resp, err := c.Do(req)
	if err != nil {
		panic(err)
	}

	b, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	fmt.Printf("received body: %s\n", b)

	// Using method helpers to create and send requests automatically
	// Override the timeout on the http.Client with a context, this is
	// the preferred method over changing the http.Client timeout.
	ctx, cancel := context.WithTimeout(context.Background(), 10 * time.Second)
	defer cancel()
	resp, err = c.Post(ctx, "/users", bytes.NewBuffer([]byte("payload")))
	if err != nil {
		panic(err)
	}

	fmt.Printf("response code: %d\n", resp.StatusCode)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("not found")

Functions

func BuildURLWithQuery

func BuildURLWithQuery(url string, qs map[string]string) (string, error)

BuildURLWithQuery build a URL with query strings.

func DefaultHTTPClient

func DefaultHTTPClient() *http.Client

DefaultHTTPClient returns a http.Client with sane defaults. It should be used as a starting point instead of an empty http.Client.

func DefaultHTTPTransport

func DefaultHTTPTransport() *http.Transport

DefaultHTTPTransport returns a http.Transport with sane defaults. It should be used as a starting point instead of an empty http.Transport.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func New

func New(opt ...Option) *Client

New creates a new client.

func (*Client) Delete

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

Delete sends a DELETE HTTP request and returns an HTTP response.

func (*Client) Do

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

Do sends an HTTP request and returns an HTTP response.

func (*Client) Get

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

Get sends a GET HTTP request and returns an HTTP response.

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method string, url string, body io.Reader) (*http.Request, error)

NewRequest creates a new HTTP request.

func (*Client) OverrideURL

func (c *Client) OverrideURL(url string)

OverrideURL overrides the request's URL. Mostly for testing and using with httptest.Server.

func (*Client) Patch

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

Patch sends a PATCH HTTP request and returns an HTTP response.

func (*Client) Post

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

Post sends a POST HTTP request and returns an HTTP response.

func (*Client) Put

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

Put sends a PUT HTTP request and returns an HTTP response.

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithAccept

func WithAccept(s string) Option

WithAccept sets the Accept header that will be sent with all request.

func WithAfterRequest

func WithAfterRequest(f func(resp *Response) error) Option

WithAfterRequest sets a function that will run after every request and has access to the current response to inspect and/or modify it. Can be called multiple times to chain functions.

func WithAuth

func WithAuth(s string) Option

WithAuth sets the Authorization header that will be sent with all requests.

func WithAuthBearer

func WithAuthBearer(s string) Option

WithAuthBearer sets the Authorization header with the Bearer prefix that will be sent with all requests.

func WithBaseURL

func WithBaseURL(s string) Option

WithBaseURL sets a base URL that will be prepended to every subsequent URL when making requests.

func WithBeforeRequest

func WithBeforeRequest(f func(req *http.Request) error) Option

WithBeforeRequest sets a function that will run before every request and has access to the current request to inspect and/or modify it. Can be called multiple times to chain functions.

func WithContentType

func WithContentType(s string) Option

WithContentType sets the ContentType header that will be sent with POST, PUT and PATCH requests.

func WithDebugRequest

func WithDebugRequest(l zerolog.Logger) Option

WithDebugRequest will log the request to the supplied zerolog.Logger.

func WithDebugResponse

func WithDebugResponse(l zerolog.Logger) Option

WithDebugResponse will log the response to the supplied zerolog.Logger.

func WithFormatErrors

func WithFormatErrors(b bool) Option

WithFormatErrors will format the >= 400 responses and return them in the following format: 'http.client: <status_code> response for <url>: <body>'. 404 responses will return ErrNotFound instead as sometimes a 404 is expected.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets the http.Client.

func WithHeaders

func WithHeaders(m map[string]string) Option

WithHeaders sets headers that will be sent with all requests.

type Response

type Response struct {
	*http.Response
}

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(v any) error

Jump to

Keyboard shortcuts

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