greq

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 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

greq 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/greq

Quick start

package main

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

func main() {
	resp, err := greq.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/greq_test.TestHReq_Send(greq_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

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

Set multi at once:

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

Built in JSONType() FromType() XMLType()

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

Use middleware

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

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

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

	resp, err := greq.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 := greq.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

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

package main

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

func main() {
	resp, err := greq.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 greq is a simple http client request builder, inspired from https://github.com/dghubble/sling

Index

Constants

This section is empty.

Variables

View Source
var DefaultDoer = http.DefaultClient

DefaultDoer for request.

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 HandleFunc

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

HandleFunc for the Middleware

type HiReq

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

HiReq is an HTTP Request builder and sender.

func BaseURL

func BaseURL(baseURL string) *HiReq

BaseURL set base URL for request

func New

func New(baseURL ...string) *HiReq

New create

func Reset

func Reset() *HiReq

Reset std

func Std

func Std() *HiReq

Std instance

func (*HiReq) AddHeader

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

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

func (*HiReq) AddHeaders

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

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

func (*HiReq) BaseURL

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

BaseURL set base URL for all request

func (*HiReq) BasicAuth

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

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 (*HiReq) Body

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

Body with custom body

func (*HiReq) BodyProvider

func (h *HiReq) BodyProvider(bp BodyProvider) *HiReq

BodyProvider with custom body provider

func (*HiReq) BodyReader

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

BodyReader with custom io reader body

func (*HiReq) Build

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

Build new request

func (*HiReq) BytesBody

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

BytesBody with custom string body

func (*HiReq) Client

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

Client custom set http request doer

func (*HiReq) Config

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

Config custom config http request doer

func (*HiReq) ConfigHClient

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

ConfigHClient custom config http client.

Usage:

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

func (*HiReq) Connect

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

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

func (*HiReq) ConnectDo

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

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

func (*HiReq) ContentType

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

ContentType with custom ContentType header

Usage:

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

func (*HiReq) Delete

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

Delete sets the method to DELETE and sets the given pathURL

func (*HiReq) DeleteDo

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

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

func (*HiReq) Do

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

Do send request and return response

func (*HiReq) DoWithCtx

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

DoWithCtx request with context, then return response

func (*HiReq) Doer

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

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

func (*HiReq) FileContentsBody

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

FileContentsBody read file contents as body

func (*HiReq) FormBody

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

FormBody with form data body

func (*HiReq) FormType

func (h *HiReq) FormType() *HiReq

FormType with from Content-Type header

func (*HiReq) Get

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

Get sets the method to GET and sets the given pathURL

func (*HiReq) GetDo

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

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

func (*HiReq) Head

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

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

func (*HiReq) HeadDo

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

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

func (*HiReq) HttpClient

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

HttpClient custom set http client as request doer

func (*HiReq) JSONBody

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

JSONBody with JSON data body

func (*HiReq) JSONType

func (h *HiReq) JSONType() *HiReq

JSONType with json Content-Type header

func (*HiReq) Method

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

Method set http method name.

func (*HiReq) Middleware

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

Middleware add one or multi middlewares

func (*HiReq) Middlewares

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

Middlewares add one or multi middlewares

func (*HiReq) Multipart

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

Multipart with custom multipart body

func (*HiReq) MultipartType

func (h *HiReq) MultipartType() *HiReq

MultipartType with multipart/form-data Content-Type header

func (*HiReq) MustSend

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

MustSend send request and return response, will panic on error

func (*HiReq) New

func (h *HiReq) New() *HiReq

New create an instance from current.

func (*HiReq) NewRequest

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

NewRequest build new request

func (*HiReq) NewRequestWithCtx

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

NewRequestWithCtx build new request with context

func (*HiReq) Options

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

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

func (*HiReq) OptionsDo

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

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

func (*HiReq) Patch

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

Patch sets the method to PATCH and sets the given pathURL

func (*HiReq) PatchDo

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

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

func (*HiReq) PathURL

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

PathURL set path URL for current request

func (*HiReq) Post

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

Post sets the method to POST and sets the given pathURL

func (*HiReq) PostDo

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

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

func (*HiReq) Put

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

Put sets the method to PUT and sets the given pathURL

func (*HiReq) PutDo

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

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

func (*HiReq) QueryParam

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

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

func (*HiReq) QueryParams

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

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 (*HiReq) QueryValues

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

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

func (*HiReq) Send

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

Send request and return response

func (*HiReq) SendRaw

func (h *HiReq) SendRaw(raw string) (*Response, error)

SendRaw http request text.

func (*HiReq) SendRequest

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

SendRequest send request

func (*HiReq) SendWithCtx

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

SendWithCtx request with context, then return response

func (*HiReq) SetCookieString

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

SetCookieString set cookie header value.

Usage:

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

func (*HiReq) SetCookies

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

SetCookies to request

func (*HiReq) SetHeader

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

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

func (*HiReq) SetHeaders

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

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

func (*HiReq) String

func (h *HiReq) String() string

String request to string.

func (*HiReq) StringBody

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

StringBody with custom string body

func (*HiReq) Trace

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

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

func (*HiReq) TraceDo

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

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

func (*HiReq) Use

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

Use one or multi middlewares

func (*HiReq) UserAgent

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

UserAgent with User-Agent header setting.

func (*HiReq) UserAuth

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

UserAuth with user auth header value.

func (*HiReq) Uses

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

Uses one or multi middlewares

func (*HiReq) WithRespDecoder

func (h *HiReq) WithRespDecoder(respDecoder RespDecoder) *HiReq

WithRespDecoder for client

func (*HiReq) XMLType

func (h *HiReq) XMLType() *HiReq

XMLType with xml Content-Type header

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) BodyBuffer

func (r *Response) BodyBuffer() *bytes.Buffer

BodyBuffer read body to buffer.

NOTICE: must close resp body.

func (*Response) BodyString

func (r *Response) BodyString() string

BodyString convert response body to string

func (*Response) CloseBody

func (r *Response) CloseBody() error

CloseBody close resp body

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 := greq.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) QuietCloseBody

func (r *Response) QuietCloseBody()

QuietCloseBody close resp body, ignore error

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

type XmlDecoder

type XmlDecoder struct {
}

XmlDecoder decodes http response body into a XML-tagged struct value.

func (XmlDecoder) Decode

func (d XmlDecoder) Decode(resp *http.Response, ptr interface{}) error

Decode decodes the Response body into the value pointed to by ptr.

Jump to

Keyboard shortcuts

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