httpclient

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2025 License: MIT Imports: 15 Imported by: 0

README

httpcleint

Simple HTTP and REST client library for Go without dependency

Features

  • GET, POST, PUT, DELETE, HEAD. Can be extended in the future
  • Simple and chainable methods for settings and request
  • [Request] Body can be string, []byte, struct, map, slice and io.Reader too
  • Can add any middlewares you want in the httpclient

Installation

httpclient supports Go Modules. Run go mod tidy in your project's directory to collect the required packages automatically.

go get github.com/kepinsu/httpclient

Or with imports:

// Import httpclient into your code and refer it as `httpclient`.
import "github.com/kepinsu/httpclient"

Usage

Simple POST

// Create the client
c ,err := httpclient.NewClient("")
if err !=nil{
  // handle your error
}

// My result structure
type Result struct{
  ...
}

// My error result structure if your api return a error
type ErrorResult struct{
  ...
}

var result Result
var errorresult ErrorResult


httpresponse , err :=c.Post(context.Todo(), "/endpoint", body , &result, &errorresult, 
  // Say this request is in json
  httpclient.WithIsJSON())
// handle the error or the result
...

Simple POST with Multipart body

	// Create a http client
	client, err := httpclient.NewClient("http://example.com")
	if err != nil {
		fmt.Println("fail to setup the client", err)
		return
	}
	// prepare the multipart body
	m := httpclient.NewMultipartBody()
	m.SetMultipartFields(
		httpclient.MultipartField{
			Param:       "uploadManifest1",
			FileName:    "upload-file-1.json",
			ContentType: "application/json",
			Reader:      strings.NewReader(`{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`),
		},
		httpclient.MultipartField{
			Param:       "uploadManifest2",
			ContentType: "application/json",
			ContentID:   "up",
			Reader:      strings.NewReader(`{"input": {"name": "random file"}}`),
		})

	// Want the response in JSON decode
	client.Post(context.Background(), "", m, nil, nil, httpclient.WithIsJson())

Simple Decorator

	// Random Decorator like Logging
	var logger httpclient.Decorator = func(d httpclient.Doer) httpclient.Doer {
		return httpclient.DoerFunc(func(r *http.Request) (*http.Response, error) {
			return d.Do(r)
		})
	}
	// Create a http client
	client, err := httpclient.NewClient("http://example.com",
		httpclient.WithDecorator(logger))
	if err != nil {
		fmt.Println("fail to setup the client", err)
		return
	}

	// Want the response in JSON decode
	client.Delete(context.Background(), "", nil, nil, nil, httpclient.WithIsJson())

Documentation

Overview

Package httpclient provides simple httpclient for any REST request in XML or JSON payload

Example (Delete_WithDecorators)
package main

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

	"github.com/kepinsu/httpclient"
)

func main() {

	// Random Decorator like Logging
	var logger httpclient.Decorator = func(d httpclient.Doer) httpclient.Doer {
		return httpclient.DoerFunc(func(r *http.Request) (*http.Response, error) {
			return d.Do(r)
		})
	}
	// Create a http client
	client, err := httpclient.NewClient("http://example.com",
		httpclient.WithDecorator(logger))
	if err != nil {
		fmt.Println("fail to setup the client", err)
		return
	}

	// Want the response in JSON decode
	client.Delete(context.Background(), "", nil, nil, nil, httpclient.WithIsJson())

}
Output:

Example (Get)
package main

import (
	"context"
	"fmt"

	"github.com/kepinsu/httpclient"
)

func main() {
	// Create a http client
	client, err := httpclient.NewClient("http://example.com")
	if err != nil {
		fmt.Println("fail to setup the client", err)
		return
	}
	client.Get(context.Background(), "", nil, nil)
}
Output:

Example (Post_Multipart)
package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/kepinsu/httpclient"
)

func main() {
	// Create a http client
	client, err := httpclient.NewClient("http://example.com")
	if err != nil {
		fmt.Println("fail to setup the client", err)
		return
	}
	// prepare the multipart body
	m := httpclient.NewMultipartBody()
	m.SetMultipartFields(
		httpclient.MultipartField{
			Param:       "uploadManifest1",
			FileName:    "upload-file-1.json",
			ContentType: "application/json",
			Reader:      strings.NewReader(`{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`),
		},
		httpclient.MultipartField{
			Param:       "uploadManifest2",
			ContentType: "application/json",
			ContentID:   "up",
			Reader:      strings.NewReader(`{"input": {"name": "random file"}}`),
		})

	// Want the response in JSON decode
	client.Post(context.Background(), "", m, nil, nil, httpclient.WithIsJson())
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrResponseBodyTooLarge = errors.New("httpclient: response body too large")

Functions

This section is empty.

Types

type Client

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

Client struct is used to create a httpclient with client-level settings, these settings apply to all the requests raised from the client.

func NewClient

func NewClient(baseURL string, opts ...ClientsOption) (*Client, error)

func (*Client) Delete

func (c *Client) Delete(
	ctx context.Context,
	path string,
	body any,
	result any,
	resultError any,
	opts ...RequestOption,
) (Response, error)

Delete method does DELETE HTTP request. It's defined in section 4.3.5 of RFC7231.

func (*Client) Do

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

Do method returns the http.Request if your need to send your own request.

func (*Client) Get

func (c *Client) Get(
	ctx context.Context,
	path string,
	result any,
	resultError any,
	opts ...RequestOption,
) (Response, error)

Get method does GET HTTP request. It's defined in section 4.3.1 of RFC7231.

func (*Client) Head

func (c *Client) Head(
	ctx context.Context,
	path string,
	resultError any,
	opts ...RequestOption,
) (Response, error)

func (*Client) NewRequest

func (c *Client) NewRequest(
	path string,
	method string,
	body any,
	opts ...RequestOption) (*http.Request, error)

NewRequest method returns the http.Request if your need to create your own request.

func (*Client) NewRequestWithContext

func (c *Client) NewRequestWithContext(ctx context.Context,
	path string,
	method string,
	body any,
	opts ...RequestOption) (*http.Request, error)

NewRequestWithContext method returns the http.Request if your need to create your own request.

func (*Client) Post

func (c *Client) Post(
	ctx context.Context,
	path string,
	body any,
	result any,
	resultError any,
	opts ...RequestOption,
) (Response, error)

Post method does POST HTTP request. It's defined in section 4.3.3 of RFC7231.

func (*Client) PostForm

func (c *Client) PostForm(
	ctx context.Context,
	path string, data url.Values,
	result any,
	resultError any,
	opts ...RequestOption) (Response, error)

Post method does POST HTTP request. It's defined in section 4.3.3 of RFC7231.

func (*Client) Put

func (c *Client) Put(
	ctx context.Context,
	path string,
	body any,
	result any,
	resultError any,
	opts ...RequestOption,
) (Response, error)

Put method does PUT HTTP request. It's defined in section 4.3.4 of RFC7231.

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(url string) *Client

SetBaseURL method sets the Base URL in the client instance. It will be used with a request raised from this client with a relative URL

// Setting HTTP address
client.SetBaseURL("http://myjeeva.com")

// Setting HTTPS address
client.SetBaseURL("https://myjeeva.com")

type ClientsOption

type ClientsOption func(*clientConfig)

ClientsOption is to create convenient client options like wait custom RoundTripper, custom http.client

func WithDecorator

func WithDecorator(decorators ...Decorator) ClientsOption

WithDecorators is to add custom Decorators for http call Is more like http middlewares

func WithSizeLimit

func WithSizeLimit(limitSize int) ClientsOption

WithDecorators is to add custom Decorators for http call Is more like http middlewares

func WithTransport

func WithTransport(t http.RoundTripper) ClientsOption

WithTransport is to add custom Transport for http call

func WithUserAgent

func WithUserAgent(u string) ClientsOption

WithUserAgent is to add user agent for any http request

type Decorator

type Decorator func(Doer) Doer

type Doer

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

Interface for HTTP.Client

type DoerFunc

type DoerFunc func(*http.Request) (*http.Response, error)

DoerFunc is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signture

func (DoerFunc) Do

func (f DoerFunc) Do(r *http.Request) (*http.Response, error)

The do function allows the clientsFunc to satisafy the Doer interface

type MultipartBody added in v0.1.0

type MultipartBody struct {
	// The Header of the Boundary like multipart/form-data
	Boundary string
	List     []MultipartField
}

MultipartBody struct represents the multipart body in HTTP request

func NewMultipartBody added in v0.1.0

func NewMultipartBody() *MultipartBody

func (*MultipartBody) SetMultipartFields added in v0.1.0

func (m *MultipartBody) SetMultipartFields(fields ...MultipartField)

SetMultipartFields method sets multiple data fields using io.Reader for multipart upload.

For Example:

 m := NewMultipartBody()
 m.SetMultipartFields(
		httpclient.MultipartField{
			Param:       "uploadManifest1",
			FileName:    "upload-file-1.json",
			ContentType: "application/json",
			Reader:      strings.NewReader(`{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`),
		},
		httpclient.MultipartField{
			Param:       "uploadManifest2",
			ContentID:   "2",
			ContentType: "application/json",
			Reader:      strings.NewReader(`{"input": {"name": "random file"}}`),
		})

If you have a `slice` of fields already, then call-

m.SetMultipartFields.SetMultipartFields(fields...)

type MultipartField added in v0.1.0

type MultipartField struct {
	Param       string
	FileName    string
	ContentType string
	ContentID   string
	io.Reader
}

MultipartField struct represents the custom data part for a multipart request

type RequestOption

type RequestOption func(*requestConfig)

RequestOption is to create convenient request options like wait custom fields for http.request

func WithHeaders

func WithHeaders(headers http.Header) RequestOption

WithHeaders is when you need to add specific headers in your request

func WithIsJson

func WithIsJson() RequestOption

WithIsJson is to indicate this request/response is in json payload

func WithIsXml

func WithIsXml() RequestOption

WithIsXml is to indicate this request/response is in xml payload

func WithQueries

func WithQueries(
	queries map[string]string) RequestOption

WithQueries is when you need to add specific query in your request

type Response

type Response struct {
	// Raw request send by the client
	Request *http.Request
	// Raw response receive by the client
	RawResponse *http.Response
}

The response from the HTTP Request

Jump to

Keyboard shortcuts

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