hreq

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2022 License: MIT Imports: 14 Imported by: 0

README

HReq

GitHub go.mod Go version GitHub tag (latest SemVer) GoDoc Go Report Card Unit-Tests Coverage Status

HReq A simple http client request builder and sender

hreq inspired from dghubble/sling and more projects, please see refers.

Features

  • Make http requests, supports GET,POST,PUT,PATCH,DELETE,HEAD
  • Transform request and response data
  • Supports chain configuration request
  • Supports defining and adding middleware
  • Supports defining request body provider and response decoder
  • Built-In: fom, json request body provider
  • Built-In: xml, json response body decoder

Install

go get github.com/gookit/hreq

Quick start

package main

import (
	"github.com/gookit/goutil/dump"
	"github.com/gookit/hreq"
)

func main() {
	resp, err := hreq.New("https://httpbin.org").
		JSONType().
		UserAgent("custom-client/1.0").
		PostDo("/post")

	if err != nil {
		panic(err)
	}

	ret := make(map[string]interface{})
	err = resp.Decode(&ret)
	if err != nil {
		panic(err)
	}

	dump.P(ret)
}

Result:

PRINT AT github.com/gookit/hreq_test.TestHReq_Send(hreq_test.go:73)
map[string]interface {} { #len=4
  "args": map[string]interface {} { #len=0
  },
  "headers": map[string]interface {} { #len=4
    "Host": string("httpbin.org"), #len=11
    "User-Agent": string("custom-client/1.0"), #len=17
    "X-Amzn-Trace-Id": string("Root=1-61e4d41e-06e27ae12ff872a224373ca7"), #len=40
    "Accept-Encoding": string("gzip"), #len=4
  },
  "origin": string("222.210.59.218"), #len=14
  "url": string("https://httpbin.org/post"), #len=24
},

Request headers

hreq.New("some.host/api").
	SetHeader("req-id", "a string")

Set multi at once:

hreq.New("some.host/api").
	SetHeaders(map[string]string{
		"req-id": "a string",
	})
Set content type
hreq.New("some.host/api").
    ContentType("text/html")

Built in JSONType() FromType() XMLType()

hreq.New("some.host/api").JSONType()

Use middleware

	buf := &bytes.Buffer{}
	mid0 := hreq.MiddleFunc(func(r *http.Request, next hreq.HandleFunc) (*hreq.Response, error) {
		buf.WriteString("MID0>>")
		w, err := next(r)
		buf.WriteString(">>MID0")
		return w, err
	})

	mid1 := hreq.MiddleFunc(func(r *http.Request, next hreq.HandleFunc) (*hreq.Response, error) {
		buf.WriteString("MID1>>")
		w, err := next(r)
		buf.WriteString(">>MID1")
		return w, err
	})

	mid2 := hreq.MiddleFunc(func(r *http.Request, next hreq.HandleFunc) (*hreq.Response, error) {
		buf.WriteString("MID2>>")
		w, err := next(r)
		buf.WriteString(">>MID2")
		return w, err
	})

	resp, err := hreq.New("https://httpbin.org").
		Doer(httpreq.DoerFunc(func(req *http.Request) (*http.Response, error) {
			tw := httptest.NewRecorder()
			buf.WriteString("(CORE)")
			return tw.Result(), nil
		})).
		Middleware(mid0, mid1, mid2).
		GetDo("/get")

    fmt.Println(buf.String())

Output:

MID2>>MID1>>MID0>>(CORE)>>MID0>>MID1>>MID2

More usage

Check response
  • Response.IsOK() bool
  • Response.IsFail() bool
  • Response.IsEmptyBody() bool
  • Response.IsJSONType() bool
  • Response.IsContentType(prefix string) bool
Get response data
  • Response.ContentType() string
  • Response.Decode(ptr interface{}) error
Request to string
    str := hreq.New("https://httpbin.org").
		UserAgent("some-client/1.0").
		BasicAuth("inhere", "some string").
		JSONType().
		Body("hi, with body").
		Post("/post").
		String()

	fmt.Println(str)

Output:

POST https://httpbin.org/post/ HTTP/1.1
User-Agent: some-client/1.0
Authorization: Basic aW5oZXJlOnNvbWUgc3RyaW5n
Content-Type: application/json; charset=utf-8

hi, with body
Response to string

hreq.Response.String() can convert response to string.

package main

import (
	"fmt"
	
	"github.com/gookit/goutil/dump"
	"github.com/gookit/hreq"
)

func main() {
	resp, err := hreq.New("https://httpbin.org").
		UserAgent("custom-client/1.0").
		Send("/get")
	
	if err != nil {
		panic(err)
	}

	fmt.Print(resp.String())
}

Output:

HTTP/2.0 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Date: Tue, 18 Jan 2022 04:52:39 GMT
Content-Type: application/json
Content-Length: 272
Server: gunicorn/19.9.0

{
  "args": {}, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Host": "httpbin.org", 
    "User-Agent": "custom-client/1.0", 
    "X-Amzn-Trace-Id": "Root=1-61e64797-3e428a925f7709906a8b7c01"
  }, 
  "origin": "222.210.59.218", 
  "url": "https://httpbin.org/get"
}

Refers

Documentation

Overview

Package hreq is a simple http client request builder, inspired from https://github.com/dghubble/sling

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ToString

func ToString(r *http.Request, err error) string

ToString convert http Request to string

Types

type BodyProvider

type BodyProvider interface {
	// ContentType returns the Content-Type of the body.
	ContentType() string
	// Body returns the io.Reader body.
	Body() (io.Reader, error)
}

BodyProvider provides Body content for http.Request attachment.

type HReq

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

HReq is an HTTP Request builder and sender.

func BaseURL

func BaseURL(baseURL string) *HReq

BaseURL set base URL for request

func New

func New(baseURL ...string) *HReq

New create

func Reset

func Reset() *HReq

Reset std

func Std

func Std() *HReq

Std instance

func (*HReq) AddHeader

func (h *HReq) AddHeader(key, value string) *HReq

AddHeader adds the key, value pair in Headers, appending values for existing keys to the key's values. Header keys are canonicalized.

func (*HReq) AddHeaders

func (h *HReq) AddHeaders(headers http.Header) *HReq

AddHeaders adds all the http.Header values, appending values for existing keys to the key's values. Header keys are canonicalized.

func (*HReq) BaseURL

func (h *HReq) BaseURL(baseURL string) *HReq

BaseURL set base URL for all request

func (*HReq) BasicAuth

func (h *HReq) BasicAuth(username, password string) *HReq

BasicAuth sets the Authorization header to use HTTP Basic Authentication with the provided username and password. With HTTP Basic Authentication the provided username and password are not encrypted.

func (*HReq) Body

func (h *HReq) Body(body interface{}) *HReq

Body with custom body

func (*HReq) BodyProvider

func (h *HReq) BodyProvider(bp BodyProvider) *HReq

BodyProvider with custom body provider

func (*HReq) BodyReader

func (h *HReq) BodyReader(r io.Reader) *HReq

BodyReader with custom io reader body

func (*HReq) Build

func (h *HReq) Build(pathURLAndMethod ...string) (*http.Request, error)

Build new request

func (*HReq) BytesBody

func (h *HReq) BytesBody(bs []byte) *HReq

BytesBody with custom string body

func (*HReq) Client

func (h *HReq) Client(doer httpreq.Doer) *HReq

Client custom set http request doer

func (*HReq) Config

func (h *HReq) Config(fn func(doer httpreq.Doer)) *HReq

Config custom config http request doer

func (*HReq) ConfigHClient

func (h *HReq) ConfigHClient(fn func(hClient *http.Client)) *HReq

ConfigHClient custom config http client.

Usage:

h.ConfigHClient(func(hClient *http.Client) {
	hClient.Timeout = 30 * time.Second
})

func (*HReq) Connect

func (h *HReq) Connect(pathURL string) (*Response, error)

Connect sets the method to CONNECT and sets the given pathURL, then send request and return http response.

func (*HReq) ConnectDo

func (h *HReq) ConnectDo(pathURL string) (*Response, error)

ConnectDo sets the method to CONNECT and sets the given pathURL, then send request and return http response.

func (*HReq) ContentType

func (h *HReq) ContentType(value string) *HReq

ContentType with custom ContentType header

Usage:

// json type
h.ContentType(httpctype.JSON)
// form type
h.ContentType(httpctype.Form)

func (*HReq) Delete

func (h *HReq) Delete(pathURL string) *HReq

Delete sets the method to DELETE and sets the given pathURL

func (*HReq) DeleteDo

func (h *HReq) DeleteDo(pathURL string) (*Response, error)

DeleteDo sets the method to DELETE and sets the given pathURL, then send request and return http response.

func (*HReq) Do

func (h *HReq) Do(pathURLAndMethod ...string) (*Response, error)

Do send request and return response

func (*HReq) DoWithCtx

func (h *HReq) DoWithCtx(ctx context.Context, pathURLAndMethod ...string) (*Response, error)

DoWithCtx request with context, then return response

func (*HReq) Doer

func (h *HReq) Doer(doer httpreq.Doer) *HReq

Doer custom set http request doer. If a nil client is given, the http.DefaultClient will be used.

func (*HReq) FileContentsBody

func (h *HReq) FileContentsBody(filepath string) *HReq

FileContentsBody read file contents as body

func (*HReq) FormBody

func (h *HReq) FormBody(formData interface{}) *HReq

FormBody with form data body

func (*HReq) FormType

func (h *HReq) FormType() *HReq

FormType with from Content-Type header

func (*HReq) Get

func (h *HReq) Get(pathURL string) *HReq

Get sets the method to GET and sets the given pathURL

func (*HReq) GetDo

func (h *HReq) GetDo(pathURL string) (*Response, error)

GetDo sets the method to GET and sets the given pathURL, then send request and return response.

func (*HReq) Head

func (h *HReq) Head(pathURL string) *HReq

Head sets the method to HEAD and request the pathURL, then send request and return response.

func (*HReq) HeadDo

func (h *HReq) HeadDo(pathURL string) (*Response, error)

HeadDo sets the method to HEAD and request the pathURL, then send request and return response.

func (*HReq) HttpClient

func (h *HReq) HttpClient(hClient *http.Client) *HReq

HttpClient custom set http client as request doer

func (*HReq) JSONBody

func (h *HReq) JSONBody(jsonData interface{}) *HReq

JSONBody with JSON data body

func (*HReq) JSONType

func (h *HReq) JSONType() *HReq

JSONType with json Content-Type header

func (*HReq) Method

func (h *HReq) Method(method string) *HReq

Method set http method name.

func (*HReq) Middleware

func (h *HReq) Middleware(middles ...Middleware) *HReq

Middleware add one or multi middlewares

func (*HReq) Middlewares

func (h *HReq) Middlewares(middles ...Middleware) *HReq

Middlewares add one or multi middlewares

func (*HReq) Multipart

func (h *HReq) Multipart(key, value string) *HReq

Multipart with custom multipart body

func (*HReq) MultipartType

func (h *HReq) MultipartType() *HReq

MultipartType with multipart/form-data Content-Type header

func (*HReq) MustSend

func (h *HReq) MustSend(pathURLAndMethod ...string) *Response

MustSend send request and return response, will panic on error

func (*HReq) New

func (h *HReq) New() *HReq

New create an instance from current.

func (*HReq) NewRequest

func (h *HReq) NewRequest(pathURLAndMethod ...string) (*http.Request, error)

NewRequest build new request

func (*HReq) NewRequestWithCtx

func (h *HReq) NewRequestWithCtx(ctx context.Context, pathURLAndMethod ...string) (*http.Request, error)

NewRequestWithCtx build new request with context

func (*HReq) Options

func (h *HReq) Options(pathURL string) *HReq

Options sets the method to OPTIONS and request the pathURL, then send request and return response.

func (*HReq) OptionsDo

func (h *HReq) OptionsDo(pathURL string) (*Response, error)

OptionsDo sets the method to OPTIONS and request the pathURL, then send request and return response.

func (*HReq) Patch

func (h *HReq) Patch(pathURL string) *HReq

Patch sets the method to PATCH and sets the given pathURL

func (*HReq) PatchDo

func (h *HReq) PatchDo(pathURL string) (*Response, error)

PatchDo sets the method to PATCH and sets the given pathURL, then send request and return http response.

func (*HReq) PathURL

func (h *HReq) PathURL(pathURL string) *HReq

PathURL set path URL for current request

func (*HReq) Post

func (h *HReq) Post(pathURL string) *HReq

Post sets the method to POST and sets the given pathURL

func (*HReq) PostDo

func (h *HReq) PostDo(pathURL string) (*Response, error)

PostDo sets the method to POST and sets the given pathURL, then send request and return http response.

func (*HReq) Put

func (h *HReq) Put(pathURL string) *HReq

Put sets the method to PUT and sets the given pathURL

func (*HReq) PutDo

func (h *HReq) PutDo(pathURL string) (*Response, error)

PutDo sets the method to PUT and sets the given pathURL, then send request and return http response.

func (*HReq) QueryParam

func (h *HReq) QueryParam(key string, value interface{}) *HReq

QueryParam appends new k-v param to the query string.

func (*HReq) QueryParams

func (h *HReq) QueryParams(ps interface{}) *HReq

QueryParams appends url.Values/map[string]string to the query string. The value will be encoded as url query parameters on send requests (see Send()).

func (*HReq) QueryValues

func (h *HReq) QueryValues(values url.Values) *HReq

QueryValues appends url.Values to the query string. The value will be encoded as url query parameters on new requests (see Send()).

func (*HReq) Send

func (h *HReq) Send(pathURLAndMethod ...string) (*Response, error)

Send request and return response

func (*HReq) SendRequest

func (h *HReq) SendRequest(req *http.Request) (*Response, error)

SendRequest send request

func (*HReq) SendWithCtx

func (h *HReq) SendWithCtx(ctx context.Context, pathURLAndMethod ...string) (*Response, error)

SendWithCtx request with context, then return response

func (*HReq) SetCookieString

func (h *HReq) SetCookieString(value string) *HReq

SetCookieString set cookie header value.

Usage:

h.New().
	SetCookieString("name=inhere;age=30").
	GetDo("/some/api")

func (*HReq) SetCookies

func (h *HReq) SetCookies(hcs ...*http.Cookie) *HReq

SetCookies to request

func (*HReq) SetHeader

func (h *HReq) SetHeader(key, value string) *HReq

SetHeader sets the key, value pair in Headers, replacing existing values associated with key. Header keys are canonicalized.

func (*HReq) SetHeaders

func (h *HReq) SetHeaders(headers http.Header) *HReq

SetHeaders sets all the http.Header values, replacing values for existing keys to the key's values. Header keys are canonicalized.

func (*HReq) String

func (h *HReq) String() string

String request to string.

func (*HReq) StringBody

func (h *HReq) StringBody(s string) *HReq

StringBody with custom string body

func (*HReq) Trace

func (h *HReq) Trace(pathURL string) *HReq

Trace sets the method to TRACE and sets the given pathURL, then send request and return http response.

func (*HReq) TraceDo

func (h *HReq) TraceDo(pathURL string) (*Response, error)

TraceDo sets the method to TRACE and sets the given pathURL, then send request and return http response.

func (*HReq) Use

func (h *HReq) Use(middles ...Middleware) *HReq

Use one or multi middlewares

func (*HReq) UserAgent

func (h *HReq) UserAgent(value string) *HReq

UserAgent with User-Agent header setting.

func (*HReq) UserAuth

func (h *HReq) UserAuth(value string) *HReq

UserAuth with user auth header value.

func (*HReq) Uses

func (h *HReq) Uses(middles ...Middleware) *HReq

Uses one or multi middlewares

func (*HReq) XMLType

func (h *HReq) XMLType() *HReq

XMLType with xml Content-Type header

type HandleFunc

type HandleFunc func(r *http.Request) (*Response, error)

HandleFunc for the Middleware

type MiddleFunc

type MiddleFunc func(r *http.Request, next HandleFunc) (*Response, error)

MiddleFunc implements the Middleware interface

func (MiddleFunc) Handle

func (mf MiddleFunc) Handle(r *http.Request, next HandleFunc) (*Response, error)

Handle request

type Middleware

type Middleware interface {
	Handle(r *http.Request, next HandleFunc) (*Response, error)
}

Middleware interface for client request.

type RequestCreator

type RequestCreator interface {
	NewRequest(method, target string, body io.Reader) *http.Request
}

RequestCreator interface

type RequestCreatorFunc

type RequestCreatorFunc func(method, target string, body io.Reader) *http.Request

RequestCreatorFunc func

type RespDecoder

type RespDecoder interface {
	// Decode decodes the response into the value pointed to by ptr.
	Decode(resp *http.Response, ptr interface{}) error
}

RespDecoder decodes http responses into struct values.

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

Response is a http.Response wrapper

func ConnectDo

func ConnectDo(pathURL string) (*Response, error)

ConnectDo sets the method to CONNECT and sets the given pathURL, then send request and return http response.

func DeleteDo

func DeleteDo(pathURL string) (*Response, error)

DeleteDo sets the method to DELETE and sets the given pathURL, then send request and return http response.

func GetDo

func GetDo(pathURL string) (*Response, error)

GetDo sets the method to GET and sets the given pathURL, then send request and return response.

func Head(pathURL string) (*Response, error)

Head sets the method to HEAD and request the pathURL, then send request and return response.

func OptionsDo

func OptionsDo(pathURL string) (*Response, error)

OptionsDo sets the method to OPTIONS and request the pathURL, then send request and return response.

func PatchDo

func PatchDo(pathURL string, body ...interface{}) (*Response, error)

PatchDo sets the method to PATCH and sets the given pathURL, then send request and return http response.

func PostDo

func PostDo(pathURL string, body ...interface{}) (*Response, error)

PostDo sets the method to POST and sets the given pathURL, then send request and return http response.

func PutDo

func PutDo(pathURL string, body ...interface{}) (*Response, error)

PutDo sets the method to PUT and sets the given pathURL, then send request and return http response.

func TraceDo

func TraceDo(pathURL string) (*Response, error)

TraceDo sets the method to TRACE and sets the given pathURL, then send request and return http response.

func (*Response) BodyString

func (r *Response) BodyString() string

BodyString convert response body to string

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType get response content type

func (*Response) Decode

func (r *Response) Decode(ptr interface{}) error

Decode get the raw http.Response

func (*Response) HeaderString

func (r *Response) HeaderString() string

HeaderString convert response headers to string

func (*Response) IsContentType

func (r *Response) IsContentType(prefix string) bool

IsContentType check response content type is equals the given.

Usage:

	resp, err := hreq.Post("some.host/path")
 ok := resp.IsContentType("application/xml")

func (*Response) IsEmptyBody

func (r *Response) IsEmptyBody() bool

IsEmptyBody check response body is empty

func (*Response) IsFail

func (r *Response) IsFail() bool

IsFail check response status code != 200

func (*Response) IsJSONType

func (r *Response) IsJSONType() bool

IsJSONType check response content type is JSON

func (*Response) IsOK

func (r *Response) IsOK() bool

IsOK check response status code is 200

func (*Response) IsSuccessful

func (r *Response) IsSuccessful() bool

IsSuccessful check response status code is in 200 - 300

func (*Response) Result

func (r *Response) Result() *http.Response

Result get the raw http.Response

func (*Response) SetDecoder

func (r *Response) SetDecoder(decoder RespDecoder)

SetDecoder for response

func (*Response) String

func (r *Response) String() string

String convert Response to string

Jump to

Keyboard shortcuts

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