httpclient

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

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

Go to latest
Published: Mar 6, 2023 License: Apache-2.0 Imports: 14 Imported by: 0

README

httpclient

codecov

httpclient is a thin wrapper around http.Client with some useful features.

  • methods: .Post, .Get, .Put, .Delete, etc.
  • simplified JSON, form and multipart requests

Installation

go get -v github.com/ninedraft/httpclient@latest

Usage

Simple POST request

resp, err := client.Post(ctx, "https://httpbin.org/post", "application/json",
		strings.NewReader(`{"foo": "bar"}`))

JSON request

resp, err := client.PostJSON(ctx, "https://httpbin.org/post", map[string]string{"foo": "bar"})

Form request

resp, err := client.PostForm(ctx, "https://httpbin.org/post", 
    url.Values{
        "foo": {"bar"}",
    })

Multipart request

resp, err = client.PostMultipart(ctx, "https://httpbin.org/post",
    httpclient.WriteMultiparts(
	    httpclient.MultipartFields(url.Values{
		    "foo": []string{"bar"},
		}),
        httpclient.MultipartFile("file", "file.txt", strings.NewReader("file content")),
    ))

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Header     http.Header
	Doer       Doer
	Middleware func(req *http.Request) (*http.Request, error)
}

Client is a thin wrapper around http.Client. It provides a convenient way to set default headers and middleware.

func New

func New() *Client

New returns a new Client with default settings.

func NewFrom

func NewFrom(doer Doer) *Client

NewFrom returns a new Client with the given transport.

func (*Client) Delete

func (client *Client) Delete(ctx context.Context, addr string) (*http.Response, error)

Delete makes a DELETE request to the given address.

func (*Client) Get

func (client *Client) Get(ctx context.Context, addr string) (*http.Response, error)

Get makes a GET request to the given address.

Example
package main

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/ninedraft/httpclient"
)

type exampleRoundTripper struct{}

func (exampleRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	_, _ = io.Copy(io.Discard, req.Body)

	resp := httptest.NewRecorder()

	resp.WriteHeader(http.StatusOK)
	resp.WriteString("OK")

	return resp.Result(), nil
}

func main() {
	ctx := context.Background()
	client := httpclient.NewFrom(&http.Client{
		Transport: exampleRoundTripper{},
	})

	// GET request
	resp, err := client.Get(ctx, "https://example.com")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
}
Output:

func (*Client) GetForm

func (client *Client) GetForm(ctx context.Context, addr string, data url.Values) (*http.Response, error)

GetForm makes a GET request to the given address with the given form data. The data is encoded as URL query parameters.

func (*Client) Head

func (client *Client) Head(ctx context.Context, addr string) (*http.Response, error)

Head makes a HEAD request to the given address.

func (*Client) Options

func (client *Client) Options(ctx context.Context, addr string) (*http.Response, error)

Options makes a OPTIONS request to the given address.

func (*Client) Patch

func (client *Client) Patch(ctx context.Context, addr, bodyType string, body io.Reader) (*http.Response, error)

Patch makes a PATCH request to the given address.

func (*Client) PatchForm

func (client *Client) PatchForm(ctx context.Context, addr string, data url.Values) (*http.Response, error)

PatchForm makes a PATCH request to the given address with the given form data. The data is encoded as "application/x-www-form-urlencoded".

func (*Client) PatchJSON

func (client *Client) PatchJSON(ctx context.Context, addr string, obj any) (*http.Response, error)

PatchJSON makes a PATCH request to the given address with JSON-encoded body.

func (*Client) PatchMultipart

func (client *Client) PatchMultipart(ctx context.Context, addr string, writeMultipart WriteMultipart) (*http.Response, error)

PatchMultipart sends a PATCH request with multipart data.

func (*Client) Post

func (client *Client) Post(ctx context.Context, addr, bodyType string, body io.Reader) (*http.Response, error)

Post makes a POST request to the given address.

Example
package main

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/ninedraft/httpclient"
)

type exampleRoundTripper struct{}

func (exampleRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	_, _ = io.Copy(io.Discard, req.Body)

	resp := httptest.NewRecorder()

	resp.WriteHeader(http.StatusOK)
	resp.WriteString("OK")

	return resp.Result(), nil
}

func main() {
	ctx := context.Background()
	client := httpclient.NewFrom(&http.Client{
		Transport: exampleRoundTripper{},
	})

	// POST request
	resp, err := client.Post(ctx, "https://example.com", "application/json",
		strings.NewReader(`{"foo": "bar"}`))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
}
Output:

func (*Client) PostForm

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

PostForm makes a POST request to the given address with the given form data. The data is encoded as "application/x-www-form-urlencoded".

Example
package main

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"

	"github.com/ninedraft/httpclient"
)

type exampleRoundTripper struct{}

func (exampleRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	_, _ = io.Copy(io.Discard, req.Body)

	resp := httptest.NewRecorder()

	resp.WriteHeader(http.StatusOK)
	resp.WriteString("OK")

	return resp.Result(), nil
}

func main() {
	ctx := context.Background()
	client := httpclient.NewFrom(&http.Client{
		Transport: exampleRoundTripper{},
	})

	// POST request
	resp, err := client.PostForm(ctx, "https://example.com",
		url.Values{
			"foo": []string{"bar"},
		})
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	// POST request
	resp, err = client.PostMultipart(ctx, "https://example.com",
		httpclient.MultipartFile("file", "file.txt", strings.NewReader("file content")))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	// POST request
	resp, err = client.PostMultipart(ctx, "https://example.com",
		httpclient.MultipartFile("file", "file.txt", strings.NewReader("file content")))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	// POST request
	resp, err = client.PostMultipart(ctx, "https://example.com",
		httpclient.WriteMultiparts(
			httpclient.MultipartFields(url.Values{
				"foo": []string{"bar"},
			}),
			httpclient.MultipartFile("file", "file.txt", strings.NewReader("file content")),
		))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
}
Output:

func (*Client) PostJSON

func (client *Client) PostJSON(ctx context.Context, addr string, obj any) (*http.Response, error)

PostJSON makes a POST request to the given address with JSON-encoded body.

Example
package main

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/ninedraft/httpclient"
)

type exampleRoundTripper struct{}

func (exampleRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	_, _ = io.Copy(io.Discard, req.Body)

	resp := httptest.NewRecorder()

	resp.WriteHeader(http.StatusOK)
	resp.WriteString("OK")

	return resp.Result(), nil
}

func main() {
	ctx := context.Background()
	client := httpclient.NewFrom(&http.Client{
		Transport: exampleRoundTripper{},
	})

	// POST request
	resp, err := client.PostJSON(ctx, "https://example.com",
		map[string]string{
			"foo": "bar",
		})
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
}
Output:

func (*Client) PostMultipart

func (client *Client) PostMultipart(ctx context.Context, addr string, writeMultipart WriteMultipart) (*http.Response, error)

PostMultipart sends a POST request with multipart data.

func (*Client) Put

func (client *Client) Put(ctx context.Context, addr, bodyType string, body io.Reader) (*http.Response, error)

Put makes a PUT request to the given address.

func (*Client) PutForm

func (client *Client) PutForm(ctx context.Context, addr string, data url.Values) (*http.Response, error)

PutForm makes a PUT request to the given address with the given form data. The data is encoded as "application/x-www-form-urlencoded".

func (*Client) PutJSON

func (client *Client) PutJSON(ctx context.Context, addr string, obj any) (*http.Response, error)

PutJSON makes a PUT request to the given address with JSON-encoded body.

func (*Client) PutMultipart

func (client *Client) PutMultipart(ctx context.Context, addr string, writeMultipart WriteMultipart) (*http.Response, error)

PutMultipart sends a PUT request with multipart data.

func (*Client) Query

func (client *Client) Query(ctx context.Context, addr, bodyType string, body io.Reader) (*http.Response, error)

Query makes a QUERY request to the given address. QUERY methods // https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html#name-introduction.

func (*Client) QueryForm

func (client *Client) QueryForm(ctx context.Context, addr string, data url.Values) (*http.Response, error)

QueryForm makes a QUERY request to the given address with the given form data. The data is encoded as "application/x-www-form-urlencoded".

func (*Client) QueryJSON

func (client *Client) QueryJSON(ctx context.Context, addr string, obj any) (*http.Response, error)

QueryJSON makes a QUERY request to the given address with JSON-encoded body.

func (*Client) QueryMultipart

func (client *Client) QueryMultipart(ctx context.Context, addr string, writeMultipart WriteMultipart) (*http.Response, error)

type Doer

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

Doer describes a HTTP request executor.

type MultipartWriter

type MultipartWriter interface {
	// CreateFormField calls CreatePart with a header using the
	// given field name.
	CreateFormField(name string) (io.Writer, error)

	// CreateFormFile is a convenience wrapper around CreatePart. It creates
	// a new form-data header with the provided field name and file name.
	CreateFormFile(field, filename string) (io.Writer, error)

	// WriteField calls CreateFormField and then writes the given value.
	WriteField(fieldname, value string) error

	// CreatePart creates a new multipart section with the provided
	// header. The body of the part should be written to the returned
	// Writer. After calling CreatePart, any previous part may no longer
	// be written to.
	CreatePart(header textproto.MIMEHeader) (io.Writer, error)
}

MultipartWriter is an interface that allows writing multipart data.

type WriteMultipart

type WriteMultipart func(w MultipartWriter) error

WriteMultipart is a function that writes multipart data to the given writer.

func MultipartFields

func MultipartFields(fields url.Values) WriteMultipart

MultiFields creates a WriteMultipart that writes the given fields.

func MultipartFile

func MultipartFile(field, filename string, data io.Reader) WriteMultipart

MultiFile creates a WriteMultipart that writes a file to the given field.

func WriteMultiparts

func WriteMultiparts(writers ...WriteMultipart) WriteMultipart

MultiFiles creates a WriteMultipart that applies the given multipart writers.

Jump to

Keyboard shortcuts

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