httplib

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2023 License: MIT Imports: 7 Imported by: 0

README

httplib - A library for HTTP requests

GoDoc Build codecov License GoVersion Go Report Card

Features

  • Build HTTP request in an easy way.
  • The headers package provides HTTP header constants.
  • Shortcut methods for reading string/binary body directly from an URL.

Install

go get -u github.com/cmstar/go-httplib@latest

Quick start

RequestBuilder

RequestBuilder is used to simply build HTTP request.

// Setup RequestBuilder. It supports fluent APIs.
b := httplib.NewBuilder("POST", "http://example.org").
    WithQueries(map[string]any{
        "q2": "v2",
        "q3": 3,
    }).
    WithHeader("x-custom-value", 112233).
    WithForm("f1", "vf1").
    WithForm("f2", "vf2")

// Do request. This will send a request like this:
// ====
// POST http://example.org?q2=v2&q3=3 HTTP/1.1
// Host: example.org
// X-Custom-Value: 112233
// <Some other headers such as User-Agent ...>
//
// f1=vf1&f2=vf2
// ====
resp, err := b.ReadString()

// Upload a file.
file, _ := os.Open("/some/file")
defer file.Close()

b = httplib.NewBuilder("PUT", "http://example.org")
b.SetReaderBody(file)
resp := b.MustDo()
Shortcuts

Send request directly.

// Send a GET request.
stringResponse, err := httplib.Get("http://example.org")

// Send a POST request with custom headers.
customHeaders := map[string]any{
    "Custom-Header":  "v1",
    "Custom-Header2": "v2",
}
binaryBody := []byte("request-body")
binaryResponse, err := httplib.PostBinaryWithHeaders("http://example.org", binaryBody, customHeaders)

Documentation

Overview

Package httplib provides a set of utilities for HTTP requests.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(uri string) (string, error)

Get sends a GET request. If the status code of the response is 200 OK, returns the whole response body as a string. Returns an error if the status code is not 200 OK.

func GetBinary

func GetBinary(uri string) ([]byte, error)

GetBinary sends a GET request. If the status code of the response is 200 OK, returns the whole response body as a slice of byte. Returns an error if the status code is not 200 OK.

func GetBinaryWithHeaders

func GetBinaryWithHeaders(uri string, headers map[string]any) ([]byte, error)

GetBinaryWithHeaders sends a GET request. If the status code of the response is 200 OK, returns the whole response body as a slice of byte. Returns an error if the status code is not 200 OK.

A map gives out the HTTP headers. If the map is nil, it is ignored. All header names will be converted to the Header-Naming-Style.

func GetWithHeaders

func GetWithHeaders(uri string, headers map[string]any) (string, error)

GetWithHeaders sends a GET request. If the status code of the response is 200 OK, returns the whole response body as a string. Returns an error if the status code is not 200 OK.

A map gives out the HTTP headers. If the map is nil, it is ignored. All header names will be converted to the Header-Naming-Style.

func MustGet

func MustGet(uri string) string

MustGet sends a GET request. If the status code of the response is 200 OK, returns the whole response body as a string. Panics if the status code is not 200 OK.

func MustGetBinary

func MustGetBinary(uri string) []byte

MustGetBinary sends a GET request. If the status code of the response is 200 OK, returns the whole response body as a slice of byte. Panics if the status code is not 200 OK.

func MustGetBinaryWithHeaders

func MustGetBinaryWithHeaders(uri string, headers map[string]any) []byte

MustGetBinaryWithHeaders sends a GET request. If the status code of the response is 200 OK, returns the whole response body as a slice of byte. Panics if the status code is not 200 OK.

A map gives out the HTTP headers. If the map is nil, it is ignored. All header names will be converted to the Header-Naming-Style.

func MustGetWithHeaders

func MustGetWithHeaders(uri string, headers map[string]any) string

MustGetWithHeaders sends a GET request. If the status code of the response is 200 OK, returns the whole response body as a string. Panics if the status code is not 200 OK.

A map gives out the HTTP headers. If the map is nil, it is ignored. All header names will be converted to the Header-Naming-Style.

func MustPost

func MustPost(uri string, body string) string

MustPost sends a POST request. If the status code of the response is 200 OK, returns the whole response body as a string. Panics if the status code is not 200 OK.

func MustPostBinary

func MustPostBinary(uri string, body []byte) []byte

MustPostBinary sends a POST request. If the status code of the response is 200 OK, returns the whole response body as a slice of byte. Panics if the status code is not 200 OK.

func MustPostBinaryWithHeaders

func MustPostBinaryWithHeaders(uri string, body []byte, headers map[string]any) []byte

MustPostBinaryWithHeaders sends a POST request. If the status code of the response is 200 OK, returns the whole response body as a slice of byte. Panics if the status code is not 200 OK.

A map gives out the HTTP headers. If the map is nil, it is ignored. All header names will be converted to the Header-Naming-Style.

func MustPostWithHeaders

func MustPostWithHeaders(uri string, body string, headers map[string]any) string

MustPostWithHeaders sends a POST request. If the status code of the response is 200 OK, returns the whole response body as a string. Panics if the status code is not 200 OK.

A map gives out the HTTP headers. If the map is nil, it is ignored. All header names will be converted to the Header-Naming-Style.

func Post

func Post(uri string, body string) (string, error)

Post sends a POST request. If the status code of the response is 200 OK, returns the whole response body as a string. Returns an error if the status code is not 200 OK.

func PostBinary

func PostBinary(uri string, body []byte) ([]byte, error)

PostBinary sends a POST request. If the status code of the response is 200 OK, returns the whole response body as a slice of byte. Returns an error if the status code is not 200 OK.

func PostBinaryWithHeaders

func PostBinaryWithHeaders(uri string, body []byte, headers map[string]any) ([]byte, error)

PostBinaryWithHeaders sends a POST request. If the status code of the response is 200 OK, returns the whole response body as a slice of byte. Returns an error if the status code is not 200 OK.

A map gives out the HTTP headers. If the map is nil, it is ignored. All header names will be converted to the Header-Naming-Style.

func PostWithHeaders

func PostWithHeaders(uri string, body string, headers map[string]any) (string, error)

PostWithHeaders sends a POST request. If the status code of the response is 200 OK, returns the whole response body as a string. Returns an error if the status code is not 200 OK.

A map gives out the HTTP headers. If the map is nil, it is ignored. All header names will be converted to the Header-Naming-Style.

Types

type RequestBuilder

type RequestBuilder struct {
	Method string
	// contains filtered or unexported fields
}

RequestBuilder is used to simply build HTTP request.

Example
// Create a test server.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	fmt.Println("===request===")
	fmt.Println(r.RequestURI)

	for k, v := range r.Header {
		if strings.HasPrefix(k, "X-Custom") {
			fmt.Printf("%s: %s\n", k, strings.Join(v, ", "))
		}
	}

	body, _ := io.ReadAll(r.Body)
	fmt.Println(string(body))

	w.Write([]byte("It works!"))
}))
defer ts.Close()

// Setup RequestBuilder. It supports fluent APIs.
b := httplib.NewBuilder("POST", ts.URL).
	WithQueries(map[string]any{
		"q2": "v2",
		"q3": 3,
	}).
	WithHeader("x-custom-value", 112233).
	WithForm("f1", "vf1").
	WithForm("f2", "vf2")

// Do request.
resp, err := b.ReadString()

fmt.Println("===response===")
fmt.Println(resp, err)
Output:

===request===
/?q2=v2&q3=3
X-Custom-Value: 112233
f1=vf1&f2=vf2
===response===
It works! <nil>

func NewBuilder

func NewBuilder(method string, baseUrl string) *RequestBuilder

NewBuilder creates a new instance of RequestBuilder.

func (*RequestBuilder) Build

func (x *RequestBuilder) Build() (*http.Request, error)

Build returns a instance of http.Request, which includes the options set in other methods.

If the body is string/[]byte or one of one of strings.Reader/bytes.Buffer/bytes.Reader, Build() can be called multiple times.

If the body is io.Read and is not one of strings.Reader/bytes.Buffer/bytes.Reader, once the request is performed, the reader reached the end and is not reusable, you can call SetReaderBody() again to setup a new body.

func (*RequestBuilder) Do

func (x *RequestBuilder) Do() (*http.Response, error)

Do executes the HTTP request.

func (*RequestBuilder) MustDo

func (x *RequestBuilder) MustDo() *http.Response

MustDo is the panic version of Do().

func (*RequestBuilder) MustReadBinary

func (x *RequestBuilder) MustReadBinary() []byte

MustReadBinary is the panic version of ReadBinary().

func (*RequestBuilder) MustReadString

func (x *RequestBuilder) MustReadString() string

MustReadString is the panic version of ReadString().

func (*RequestBuilder) ReadBinary

func (x *RequestBuilder) ReadBinary() (data []byte, err error)

ReadBinary executes the HTTP request, if the status code of the response is 200 OK, it returns the whole response body as a slice of byte; otherwise returns an error.

If you need to get the body when the status code is not 200 OK, call Do().

func (*RequestBuilder) ReadString

func (x *RequestBuilder) ReadString() (string, error)

ReadString executes the HTTP request, if the status code of the response is 200 OK, it returns the whole response body as a string; otherwise returns an error.

If you need to get the body when the status code is not 200 OK, call Do().

func (*RequestBuilder) SetBinaryBody

func (x *RequestBuilder) SetBinaryBody(body []byte) *RequestBuilder

SetBinaryBody set a slice of bytes as the request body. If another body was set, it will be replaced.

func (*RequestBuilder) SetReaderBody

func (x *RequestBuilder) SetReaderBody(reader io.Reader) *RequestBuilder

SetBinaryBody set a io.Reader as the request body. If another body was set, it will be replaced.

The reader will be closed if it implements io.ReadCloser.

func (*RequestBuilder) SetStringBody

func (x *RequestBuilder) SetStringBody(body string) *RequestBuilder

SetStringBody set a string as the request body. If another body was set, it will be replaced.

func (*RequestBuilder) URL

func (x *RequestBuilder) URL() string

URL returns the whole URL, includes all added query strings.

func (*RequestBuilder) WithForm

func (x *RequestBuilder) WithForm(name string, value any) *RequestBuilder

WithForm appends a parameter to the form, and sets the header Content-Type to 'application/x-www-form-urlencoded'.

If the given value is not a string, it will be converted to a string.

If the current body set is not a form, it will be replaced.

func (*RequestBuilder) WithForms

func (x *RequestBuilder) WithForms(values map[string]any) *RequestBuilder

WithForms appends a group of parameters to the form, and sets the header Content-Type to 'application/x-www-form-urlencoded'.

If a value in the map is not a string, it will be converted to a string.

If the current body set is not a form, it will be replaced.

func (*RequestBuilder) WithHeader

func (x *RequestBuilder) WithHeader(name string, value any) *RequestBuilder

WithHeader appends a HTTP header. The name will be converted to the Header-Naming-Style.

If the given value is not a string, it will be converted to a string.

func (*RequestBuilder) WithHeaders

func (x *RequestBuilder) WithHeaders(values map[string]any) *RequestBuilder

WithHeader appends a group of HTTP headers. The name will be converted to the Header-Naming-Style.

If a value in the map is not a string, it will be converted to a string.

func (*RequestBuilder) WithQueries

func (x *RequestBuilder) WithQueries(values map[string]any) *RequestBuilder

WithQuery appends a group of query strings to the URL.

If a value in the map is not a string, it will be converted to a string.

func (*RequestBuilder) WithQuery

func (x *RequestBuilder) WithQuery(name string, value any) *RequestBuilder

WithQuery appends a query string to the URL.

If the given value is not a string, it will be converted to a string.

Directories

Path Synopsis
Package headers package provides constants of HTTP headers.
Package headers package provides constants of HTTP headers.

Jump to

Keyboard shortcuts

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